在spring Boot中使用Spring-data-jpa操作数据库

上一篇我们了解了如何使用JdbcTemplate操作mysql数据库,但是在实际开发过程中绝大多数对数据库的操作无非就是“增删改查”,很多SQL语句都类似,儿开发人员还不得不一遍一遍的写重复的代码,为了解决这种问题,我们用到了ORM框架,下面介绍一下Spring-data-jpa的一些简单使用。

    Spring Data JPA是在Spring JPA的基础上,对持久层做了简化。用户只需声明持久层的接口,不需要实现该接口。Spring Data JPA内部会根据不同的策略、通过不同的方法创建Query操作数据库

    Spring Data JPA本身已经抽象出了很多数据操作的接口,我们只需要创建一个接口并集成Spring Data JPA中的接口即可完成数据表的增删改查操作。如下图,我们只继承了JpaRepository接口,即可完成对book表的基本的增删改查操作

public interface BookRepository extends JpaRepository<Book,Long> {
}

如何使用Spring Data JPA

  •     在pom.xml中添加jpa的起步依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
  • 配置jap相关参数
spring:
  datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/restful?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: root
      password: root
      initialize: true
  init-db: true
  jpa:
      database: mysql
      show-sql: true
      hibernate:
        ddl-auto: update
        naming:
          strategy: org.hibernate.cfg.ImprovedNamingStrategy
  •     创建实体Bean
@Entity
@Table(name="book")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false)
    private Long id;

    @Column(nullable = false,name = "name")
    private String name;

    @Column(nullable = false,name = "isbn")
    private String isbn;

    @Column(nullable = false,name = "author")
    private String author;

    public Book (String name,String isbn,String author){
        this.name = name;
        this.isbn = isbn;
        this.author = author;
    }
   //由于添加了一个有参构造方法,此处一定要创建一个空的构造方法,否则查询报错
    public Book(){

    }
    public String getAuthor() {
        return author;
    }

    public String getIsbn() {
        return isbn;
    }

    public String getName() {
        return name;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

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

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}
  • 创建数据库访问接口,针对Book实体创建对应的Repository
@Repository("bookRepository")
public interface BookRepository extends JpaRepository<Book,Long> {
    Book findByIsbn(String isbn);
    Book findByName(String name);
    @Query("from Book b where b.name=:name")
    Book findBook(@Param("name") String name);
}

    此处我继承的是JpaRepository这个接口,其实在jpa中提供了多套接口供我们选择

  1. Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。
  2. CrudRepository :是Repository的子接口,提供CRUD的功能
  3. PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
  4. JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等。
  5. JpaSpecificationExecutor:用来做负责查询的接口
  6. Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可

    大家可以根据自己的程序中的实际情况进行选择。jpa还有一个强大的功能就是通过解析方法名称创建sql语句,上面方法中的Book findByIsbn(String isbn);
    Book findByName(String name);
这两个方法就是使用这个特性。下面为jap中支持的关键字:

KeywordSampleJPQL snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstname,findByFirstnameIs,findByFirstnameEquals… where x.firstname = ?1
BetweenfindByStartDateBetween… where x.startDate between ?1 and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age <= ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1(parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1(parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1(parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection age)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)

    当然除了使用方法名称解析sql语句,我们也可以通过@Query注解来创建查询,大家只需要在注解中使用JPQL语句,并通过类似“:name”来映射@Param指定的参数,就像上面的Book findBook(@Param("name") String name);方法一样。

    JPA的能力远不如上面介绍的这一点,本篇主要是以介绍为主,后续会补充一些JPA的其他内容。

  • 单元测试

    根据惯例,我们编写一个单元测试对接口进行测试   

@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo4ApplicationTests {
	@Resource
	private BookRepository bookRepository;
	@Test
	public void test() throws Exception {
		// 创建10条记录
		bookRepository.save(new Book("AAA", "10","123"));
		bookRepository.save(new Book("BBB", "20","123"));
		bookRepository.save(new Book("CCC", "30","123"));
		bookRepository.save(new Book("DDD", "40","123"));
		bookRepository.save(new Book("EEE", "50","123"));
		bookRepository.save(new Book("FFF", "60","123"));
		bookRepository.save(new Book("GGG", "70","123"));
		bookRepository.save(new Book("HHH", "80","123"));
		bookRepository.save(new Book("III", "90","123"));
		bookRepository.save(new Book("JJJ", "00","123"));
		// 测试findAll, 查询所有记录
		Assert.assertEquals(10, bookRepository.findAll().size());
		// 测试findByName, 查询名为FFF的Book
		Assert.assertEquals("60", bookRepository.findByName("FFF").getIsbn().toString());
		// 测试findBook, 查询名为FFF的Book
		Assert.assertEquals("60", bookRepository.findBook("FFF").getIsbn().toString());
		// 测试findByNameAndIsbn, 查询名为FFF并且isbn为60的Book
		Assert.assertEquals("FFF", bookRepository.findByNameAndIsbn("FFF", "60").getName());
		// 测试删除名为AAA的Book
		bookRepository.delete(bookRepository.findByName("AAA"));
		// 测试findAll, 查询所有记录, 验证上面的删除是否成功
		Assert.assertEquals(9, bookRepository.findAll().size());
	}
}

最后介绍一个消除冗长代码的工具“lombok”

    maven坐标为:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

    lombok可以去除pojo中冗余的get、set等方法,常用的注解如下:

  • @Data:注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
  • @Setter:注解在属性上;为属性提供 setting 方法
  • @Getter:注解在属性上;为属性提供 getting 方法
  • @Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
  • @NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
  • @AllArgsConstructor:注解在类上;为类提供一个全参的构造方法

    下面是简单示例

不使用lombok时

public class Person {
 
     private String id;
     private String name;
     private String identity;
     private Logger log = Logger.getLogger(Person.class);
     
     public Person() {
        
    }
    
    public Person(String id, String name, String identity) {
        this.id              = id;
        this.name       = name;
        this.identity  = identity;
    }
    
    public String getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
    
    public String getIdentity() {
        return identity;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setIdentity(String identity) {
        this.identity = identity;
    }
}

使用lombok后

@Data
@Log4j
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    private String id;
    private String name;
    private String identity; 
}

 

转载于:https://my.oschina.net/wangxincj/blog/811611

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值