我爱编程

【Spring Boot】数据库篇——使用spring-data

2018-05-27  本文已影响0人  Jotyy

在上一篇的学习中,我们使用了JdbcTemplate访问数据库。在实际开发过程中,对数据库的操作无非就“增删改查”。就最为普遍的单表操作而言,除了表和字段不同外,语句都是类似的,开发人员需要写大量类似而枯燥的语句来完成业务逻辑。

为了解决这些大量枯燥的数据操作语句,我们第一个想到的是使用ORM框架,比如:Hibernate。通过整合Hibernate之后,我们以操作Java实体的方式最终将数据改变映射到数据库表中。

为了解决抽象各个Java实体基本的“增删改查”操作,我们通常会以泛型的方式封装一个模板Dao来进行抽象简化,但是这样依然不是很方便,我们需要针对每个实体编写一个继承自泛型模板Dao的接口,再编写该接口的实现。虽然一些基础的数据访问已经可以得到很好的复用,但是在代码结构上针对每个实体都会有一堆Dao的接口和实现。

由于模板Dao的实现,使得这些具体实体的Dao层已经变的非常“薄”,有一些具体实体的Dao实现可能完全就是对模板Dao的简单代理,并且往往这样的实现类可能会出现在很多实体上。Spring-data-jpa的出现正可以让这样一个已经很“薄”的数据访问层变成只是一层接口的编写方式。比如,下面的例子:

public interface GirlRepository extends JpaRepository<User, Long> {

    User findByName(String name);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);

}

我们只需要通过编写一个继承自JpaRepository的接口就能完成数据访问,下面以一个具体实例来体验Spring-data-jpa给我们带来的强大功能。

使用示例

一、工程配置

在pom.xml中添加相关依赖:

        <dependency>
            <groupId>com.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

在application.yml中配置数据库连接信息(连接MySQL为例):

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/dbtest?useUnicode=true&characterEncoding=utf8&useSSL=true
    username: dbuser
    password: dbpass
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

其中hibernate.ddl-auto是hibernate的配置属性,主要用于自动创建、更新、验证数据表结构,有以下几种配置方式:

二、创建实体类

这是关键的一步,我们依旧创建一个Girl实体。包含id(主键),name(姓名),cupSize(...),通过ORM框架其会被映射到数据库表中。

@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Long id;
    
    @Column(nullable = false)
    private String name;
    
    @Column(nullable = false)
    private String cupSize;

    public Girl() {
    }

    public Girl(String name, String cupSize) {
        this.name = name;
        this.cupSize = cupSize;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCupSize() {
        return cupSize;
    }

    public void setCupSize(String cupSize) {
        this.cupSize = cupSize;
    }
}

三、创建数据访问接口

创建GirlRepository接口:

public interface GirlRepository extends JpaRepository<Girl,Long> {
    
    Girl findByName(String name);
    
    Girl findByAndAge(String name, Integer age);
    
    @Query("from Girl g where g.name=:name")
    Girl findGirl(@Param("name") String name);
}

在Spring-data-jpa中,只需要编写这样的一个接口,就能实现数据访问。

该接口继承自JpaRepository, JpaRepository中本身已经实现了创建(save)、更新(save)、删除(delete)、查询(findAll、findOne)等基本操作的函数,因此对于这些基础操作的数据访问就不需要再自己定义了。

但在实际开发中,我们必然不能仅仅满足于这些简单的数据库操作,我们要进一步进行更复杂的数据库查询或操作,后面再去详细学习。

在Controller中进行简单的测试:


上一篇 下一篇

猜你喜欢

热点阅读