SpringBoot整合spring-data-jpa的方法
朱由检 人气:1本文着重讲解了SpringBoot整合spring-data-jpa的方法,文中会用代码示例为大家做详细介绍,希望能够帮助到您,欢迎大家阅读和收藏
jpa
是JavaEE定义的一种规范,常用的实现一般是Hibernate
,而spring-data-jpa
则是对jpa
的又一层封装,提供了更多便捷的方法。
这里不会深入讲解spring-data-jpa的使用,只是讲解怎么快速的整合使用,目的是帮助那些想学,但是在整合上老是翻车的同学
导入依赖
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <https://img.qb5200.com/download-x/dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <https://img.qb5200.com/download-x/dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <https://img.qb5200.com/download-x/dependency>
配置
spring: data: jpa: repositories: # 开启jpa enabled: true bootstrap-mode: default jpa: # 数据库方言 database-platform: org.hibernate.dialect.MySQL57Dialect open-in-view: false # 打印SQL show-sql: false properties: # 格式化输出的SQL语句 hibernate.format_sql: false hibernate: # 自动建表策略 ddl-auto: update
这里忽略了数据源的配置
关于自动建表策略
# 枚举值 spring.jpa.hibernate.ddl-auto create 不管表是否存在, 每次启动都会重新建表(会导致数据丢失) create-drop 启动的时候创建表, 程序退出(SessionFactory关闭)的时候删除表 none 不进行任何操作 update 如果数据表不存在则创建, 在实体对象被修改后,下次启动重新修改表结构(不会删除已经存在的数据) validate 启动的时候验证数据表的结构,
相关的配置类
这里仅仅列出了部分常用的配置,如果需要了解所有的配置信息,可以参考配置类
JpaProperties SpringDataWebProperties HibernateProperties
相关配置的文档docs.spring.io/spring-boot…
定义实体类User
import java.io.Serializable; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Table; // 指定表名称 @Table(name = "user", indexes = { // 定义索引 @Index(columnList = "account", unique = true) }) // 标识实体类 @Entity // 设置表注释 @org.hibernate.annotations.Table(appliesTo = "user", comment = "用户") public class User implements Serializable { /** * */ private static final long serialVersionUID = 4953012795378725917L; @Id // id 字段 @Column(columnDefinition = "INT(11) UNSIGNED COMMENT 'id'") @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增 private Integer id; // 账户 @Column(columnDefinition = "VARCHAR(50) COMMENT '登录账户'", nullable = false) private String account; // 密码 @Column(columnDefinition = "VARCHAR(255) COMMENT '登录密码'", nullable = false) private String password; // 性别 @Column(columnDefinition = "TINYINT(1) COMMENT '性别。0:男,1:女'", nullable = false) @Enumerated private Gender gender; // 创建时间 @Column(name = "created_date", columnDefinition = "timestamp DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'", nullable = false) private LocalDateTime createdDate; // 最后修改时间 @Column(name = "last_modified_date", columnDefinition = "timestamp NULL DEFAULT NULL COMMENT '最后一次修改时间'") private LocalDateTime lastModifiedDate; // 记录状态 @Column(columnDefinition = "TINYINT(1) unsigned COMMENT '是否启用'", nullable = false) private Boolean enabled; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public LocalDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(LocalDateTime createdDate) { this.createdDate = createdDate; } public LocalDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(LocalDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } @Override public String toString() { return "User [id=" + id + ", account=" + account + ", password=" + password + ", gender=" + gender + ", createdDate=" + createdDate + ", lastModifiedDate=" + lastModifiedDate + ", enabled=" + enabled + "]"; } public static enum Gender { BOY, GIRL } }
Repository
抽象出BaseRepository
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean // 该接口不是一个Repository,不需要生成代理实现 public interface BaseRepository <T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor <T> // , QuerydslPredicateExecutor<T> 如果使用了QueryDSL还可以实现这个接口 { }
定义 UserRepository
import io.springboot.jpa.entity.User; public interface UserRepository extends BaseRepository<User, Integer> { }
Service
抽象出 BaseService
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface BaseService<T, ID> extends JpaRepository<T, ID>, JpaSpecificationExecutor <T> // , QuerydslPredicateExecutor<T> { }
抽象出 AbstractService
import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.transaction.annotation.Transactional; import io.springboot.jpa.repository.BaseRepository; public abstract class AbstractService<T, ID> implements BaseService <T, ID> { /** * 泛型注入 */ @Autowired protected BaseRepository<T, ID> baseRepository; @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public List<T> findAll() { return this.baseRepository.findAll(); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public List<T> findAll(Sort sort) { return this.baseRepository.findAll(sort); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public List<T> findAllById(Iterable<ID> ids) { return this.baseRepository.findAllById(ids); } @Override @Transactional(rollbackFor = Throwable.class) public <S extends T> List<S> saveAll(Iterable<S> entities) { return this.baseRepository.saveAll(entities); } @Override @Transactional(rollbackFor = Throwable.class) public void flush() { this.baseRepository.flush(); } @Transactional(rollbackFor = Throwable.class) public <S extends T> S saveAndFlush(S entity) { return this.baseRepository.saveAndFlush(entity); } @Override @Transactional(rollbackFor = Throwable.class) public void deleteInBatch(Iterable<T> entities) { this.baseRepository.deleteInBatch(entities); } @Override @Transactional(rollbackFor = Throwable.class) public void deleteAllInBatch() { this.baseRepository.deleteAllInBatch(); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public T getOne(ID id) { return this.baseRepository.getOne(id); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public <S extends T> List<S> findAll(Example<S> example) { return this.baseRepository.findAll(example); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public <S extends T> List<S> findAll(Example<S> example, Sort sort) { return this.baseRepository.findAll(example, sort); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public Page<T> findAll(Pageable pageable) { return this.baseRepository.findAll(pageable); } @Override @Transactional(rollbackFor = Throwable.class) public <S extends T> S save(S entity) { return this.baseRepository.save(entity); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public Optional<T> findById(ID id) { return this.baseRepository.findById(id); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public boolean existsById(ID id) { return this.baseRepository.existsById(id); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public long count() { return this.baseRepository.count(); } @Override @Transactional(rollbackFor = Throwable.class) public void deleteById(ID id) { this.baseRepository.deleteById(id); } @Override @Transactional(rollbackFor = Throwable.class) public void delete(T entity) { this.baseRepository.delete(entity); } @Override @Transactional(rollbackFor = Throwable.class) public void deleteAll(Iterable<? extends T> entities) { this.baseRepository.deleteAll(entities); } @Override @Transactional(rollbackFor = Throwable.class) public void deleteAll() { this.baseRepository.deleteAll(); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public <S extends T> Optional<S> findOne(Example<S> example) { return this.baseRepository.findOne(example); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) { return this.baseRepository.findAll(example, pageable); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public <S extends T> long count(Example<S> example) { return this.baseRepository.count(example); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public <S extends T> boolean exists(Example<S> example) { return this.baseRepository.exists(example); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public Optional<T> findOne(Specification<T> spec) { return this.baseRepository.findOne(spec); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public List<T> findAll(Specification<T> spec) { return this.baseRepository.findAll(spec); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public Page<T> findAll(Specification<T> spec, Pageable pageable) { return this.baseRepository.findAll(spec, pageable); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public List<T> findAll(Specification<T> spec, Sort sort) { return this.baseRepository.findAll(spec, sort); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class) public long count(Specification<T> spec) { return this.baseRepository.count(spec); } }
定义 UserService
import org.springframework.stereotype.Service; import io.springboot.jpa.entity.User; @Service public class UserService extends AbstractService<User, Integer> { }
添加注解驱动
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @EnableJpaRepositories(basePackages = { "io.springboot.jpa.repository" }) @EntityScan(basePackages = { "io.springboot.jpa.entity" }) public class JpaApplication { public static void main(String[] args) { SpringApplication.run(JpaApplication.class, args); } }
@EnableJpaRepositories
指定repository
所在的包@EntityScan
指定entity
所在的包
测试
import io.springboot.jpa.JpaApplication; import io.springboot.jpa.entity.User; import io.springboot.jpa.service.UserService; import java.time.LocalDateTime; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = JpaApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class JpaApplicationTest { static final Logger LOGGER = LoggerFactory.getLogger(JpaApplicationTest.class); @Autowired UserService userService; @Test public void test () { // 存储 User user = new User(); user.setAccount("kevinblandy.cn@gmail.com"); user.setPassword("123456"); user.setGender(User.Gender.GIRL); user.setEnabled(Boolean.TRUE); user.setCreatedDate(LocalDateTime.now()); this.userService.save(user); LOGGER.info("save success....."); // 检索 User results = this.userService.findById(user.getId()).orElseGet(null); LOGGER.info("query result={}", results); } }
自动创建的表
CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `account` varchar(50) NOT NULL COMMENT '登录账户', `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `enabled` tinyint(1) unsigned NOT NULL COMMENT '是否启用', `gender` tinyint(1) NOT NULL COMMENT '性别。0:男,1:女', `last_modified_date` timestamp NULL DEFAULT NULL COMMENT '最后一次修改时间', `password` varchar(255) NOT NULL COMMENT '登录密码', PRIMARY KEY (`id`), UNIQUE KEY `UKdnq7r8jcmlft7l8l4j79l1h74` (`account`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户';
执行的日志
Hibernate: insert into user (account, created_date, enabled, gender, last_modified_date, password) values (?, ?, ?, ?, ?, ?) 2020-06-23 17:57:36.264 INFO 7612 --- [ main] i.s.jpa.test.JpaApplicationTest : save success..... Hibernate: select user0_.id as id1_0_0_, user0_.account as account2_0_0_, user0_.created_date as created_3_0_0_, user0_.enabled as enabled4_0_0_, user0_.gender as gender5_0_0_, user0_.last_modified_date as last_mod6_0_0_, user0_.password as password7_0_0_ from user user0_ where user0_.id=? 2020-06-23 17:57:36.303 INFO 7612 --- [ main] i.s.jpa.test.JpaApplicationTest : query result=User [id=1, account=kevinblandy.cn@gmail.com, password=123456, gender=GIRL, createdDate=2020-06-23T17:57:36, lastModifiedDate=null, enabled=true]
总结
加载全部内容