Spring Boot中的spring-data-jpa

简介

JPA:Java Persistence API,是Sun官方提出的Java持久化规范,而他的出现主要是为了简化现有的持久化开发工作和整合ORM技术,并且其是在充分吸收了现有Hibernate,TopLink,JDO等ORM框架的基础上发展而来的,具有易于使用,伸缩性强等优点
spring-data-jpa是Spring基于Hibernate开发的一个JPA框架

1. pom.xml

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

2. application.properties

#数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/jpa_test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#jpa配置
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.show-sql=true
logging.level.com.example.demo.jpa.repository=debug

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:

  • create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
  • create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
  • update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
  • validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。

3.实体类

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue
    private Integer id;

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

    private Integer age;

    @Column(name = "create_date")
    private Date createDate;
	//get/set
}

@Table标识表的名称
@Id标识主键列
@GeneratedValue标识主键生成策略


4. repository

public interface UserRepository extends JpaRepository<User, Integer> {

    @Query(value = "select * from user where name = :name", nativeQuery = true)
    public User selectUser(@Param("name") String name);

    @Transactional
    @Query(value = "update user set age = :age", nativeQuery = true)
    public Integer updateAge(@Param("age") Integer age);

}

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

  1. JpaRepository继承了PagingAndSortingRepository 和QueryByExampleExecutor两个接口,功能最丰富。

  2. JpaRepository和CrudRepository接口虽然方便,但是暴露了增删查改的所有方法,如果你的DAO层不需要某些方法,就不要继承该接口。Spring提供了其他几个接口,org.springframework.data.repository.Repository接口没有任何方法。

  3. PagingAndSortingRepository接口则提供了分页和排序功能。PagingAndSortingRepository接口的方法接受额外的Pagable和Sort对象,用来指定获取结果的页数和排序方式。返回类型则是Page类型,我们可以调用它的方法获取总页数和可迭代的数据集合.


5.测试

@Resource
private UserRepository userRepository;

@Test
public void testJPA(){
    userRepository.deleteAll();

    User user = new User();
    user.setId(1);
    user.setName("test");
    user.setAge(22);
    user.setCreateDate(new Date());
    userRepository.save(user);

    Page<User> users = userRepository.findAll(PageRequest.of(0, 10));
    System.out.println("总记录数:" + users.getTotalElements());

    User user1 = userRepository.selectUser("test");
    System.out.println("user1 age:" + user1.getAge());

    userRepository.updateAge(11);

    User user2 = userRepository.selectUser("test");
    System.out.println("user2 age:" + user2.getAge());
}

转载
Spring Boot入门教程(十四): spring-data-jpa

猜你喜欢

转载自blog.csdn.net/lolwsyzc/article/details/83104579