首页 > 编程笔记

Spring Boot整合Spring Data JPA

当开发一个小型项目或者一些工具时可以使用 JdbcTemplate 模板类,如果开发的是一个大型项目,推荐使用实现了 ORM 持久化的框架,如 Hibernate 或MyBatis。本文主要介绍集成了 Hibernate 的 Spring Data JPA 组件,它基于 ORM 框架,实现了 JPA 标准并简化了持久层操作,可以让开发人员用极其简单的方式完成对数据库的访问与操作。

Spring Data JPA组件

Spring Data JPA 同样实现了基本的 CRUD 方法,如增、删、改、查等。如果有个性化的查询,则需要自定义 SQL 语句。Spring Data JPA 提供了以下几个核心接口:

Spring Data JPA 提供了很多注解来声明 Entity 实体类,如表 1 所示。

表1 Spring Data JPA注解
注  解 说  明
@Entity 声明类为实体类
@Table 声明表名
@Id 声明类的属性字段,该字段是表的主键
@GeneratedValue 声明主键id的生成方式
@Column 声明表的列
@ManyToMany 声明表之间多对多的关系
@ManyToOne 声明表之间多对一的关系
@OneToMany 声明表之间一对多的关系
@OneToOne 声明表之间一对一的关系

示例

下面我们通过一个示例来演示 Spring Boot 如何整合 Spring Data JPA,Spring Boot 工程依赖 spring-boot-starter-data-jpa 模块。

(1)修改 application.yml 配置文件,代码如下:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test_db?useUnicode=true&character
Encoding=UTF8&characterSetResults=UTF8&serverTimezone=UTC
    username: root
    password: test1111
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
    ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

注意:spring.jpa.hibernate.ddl-auto 的 update 属性用于根据 model 类自动更新表结构。

(2)声明实体类 UserEntity,代码如下:
//定义UserEntity类
@Entity
@Table(name="user") //表名
@Data
public class UserEntity {
    @Id    //声明主键
    //主键ID生成策略
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id") //对应的列名user_id
    private Integer userId;
    @Column(name="user_name") //对应的列名user_name
    private String userName;
    @Column(name="login_name")  //对应的列名login_name
    private String loginName;
    @Column(name="last_login_time") //对应的列名last_login_time
    private Integer lastLoginTime;
    @Column(name="user_head_img")  //对应的列名user_head_img
    private String userHeadImg;
}
(3)声明 Dao 层的类 UserRepository,该类继承自 JpaRepository,代码如下:
//继承JpaRepository
@Repository
public interface UserRepository extends JpaRepository<UserEntity,
Integer> {
}

如果默认情况下无法满足查询需求,可以通过@Query注解来解决这个问题。例如下面的示例:
@Repository
public interface UserRepository extends JpaRepository<UserEntity,
Integer> {
    //自定义查询语句
    @Query(value = "select * from user where user_id = ?", nativeQuery= true)
    UserEntity queryByUserId(Integer userId);
}

注:如果需要执行的是更新操作,则需要使用注解 @Modifying。

(4)声明Controller层的类,代码如下:
@RestController
@RequestMapping("/hi")
public class HiController {
    @Autowired
    private UserRepository userRepository;  //注入UserRepository对象
    @GetMapping("/jpa/findOne")
    public UserEntity jpaFindOne(Integer userId) {
        //根据userId查询
        Optional<UserEntity> optional = userRepository.findById(userId);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
          }
    }
    @GetMapping("/jpa/findAll")
    public Page<UserEntity> jpaFindAll() {
        //分页查询
        Pageable pageable = PageRequest.of(1,2, Sort.by(Sort.Direction.DESC,"userId"));
        userRepository.findAll();
        Page<UserEntity> page = userRepository.findAll(pageable);
        return page;
    }
    @PostMapping("/jpa/add")
    public UserEntity jpaAdd(@RequestBody UserEntity userEntity) {
        //新增用户
        UserEntity uEntity = userRepository.save(userEntity);
        return uEntity;
    }
    @PostMapping("/jpa/update")
    public UserEntity jpaUpdate(@RequestBody UserEntity userEntity) {
        //更新语句
        UserEntity uEntity = userRepository.saveAndFlush(userEntity);
        return uEntity;
    }
    @DeleteMapping("/jpa/delete")
    @Transactional
    public String jpaDelete(Integer userId){
        //根据userId删除信息
    }
}
使用工具 Postman 进行测试,访问 http://localhost:8080/hi/jpa/findAll、http://localhost: 8080/hi/jpa/update、http://localhost:8080/hi/jpa/delete?userId=2 接口,完成查询、更新和删除等操作。

优秀文章