SpringBoot整合spring-data-jpa
2021-05-07 16:28
标签:top select 怎么 repos cts led rollback Pageable 格式 这里不会深入讲解spring-data-jpa的使用,只是讲解怎么快速的整合使用,目的是帮助那些想学,但是在整合上老是翻车的同学 这里忽略了数据源的配置 这里仅仅列出了部分常用的配置,如果需要了解所有的配置信息,可以参考配置类 相关配置的文档 单纯的用JPA,局限还是蛮多,不够灵活。但是配合QueryDsl,一切都会不一样。有空我会专门写这个教程。感受到QueryDsl魅力后,保证你从此都不会在用MyBatis(我就是 ??) 同步发布 https://springboot.io/t/topic/2112 SpringBoot整合spring-data-jpa 标签:top select 怎么 repos cts led rollback Pageable 格式 原文地址:https://www.cnblogs.com/kevinblandy/p/13183631.htmlSpringBoot整合spring-data-jpa
jpa
是JavaEE定义的一种规范,常用的实现一般是 Hibernate
,而 spring-data-jpa
则是对jpa
的又一层封装,提供了更多便捷的方法。导入依赖
配置
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
(spring.jpa)SpringDataWebProperties
(spring.data.web)HibernateProperties
(spring.jpa.hibernate)
https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#data-properties定义实体类
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
定义 UserRepository
import io.springboot.jpa.entity.User;
public interface UserRepository extends BaseRepository
Service
抽象出 BaseService
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface BaseService
抽象出 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
List saveAll(Iterable entities) {
return this.baseRepository.saveAll(entities);
}
@Override
@Transactional(rollbackFor = Throwable.class)
public void flush() {
this.baseRepository.flush();
}
@Transactional(rollbackFor = Throwable.class)
public S saveAndFlush(S entity) {
return this.baseRepository.saveAndFlush(entity);
}
@Override
@Transactional(rollbackFor = Throwable.class)
public void deleteInBatch(Iterable List findAll(Example example) {
return this.baseRepository.findAll(example);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public List findAll(Example example, Sort sort) {
return this.baseRepository.findAll(example, sort);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public Page S save(S entity) {
return this.baseRepository.save(entity);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public Optional Optional findOne(Example example) {
return this.baseRepository.findOne(example);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public Page findAll(Example example, Pageable pageable) {
return this.baseRepository.findAll(example, pageable);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public long count(Example example) {
return this.baseRepository.count(example);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public boolean exists(Example example) {
return this.baseRepository.exists(example);
}
@Override
@Transactional(readOnly = true, rollbackFor = Throwable.class)
public Optional定义 UserService
import org.springframework.stereotype.Service;
import io.springboot.jpa.entity.User;
@Service
public class UserService extends AbstractService
添加注解驱动
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]
最后
整合的步骤
JPA + QueryDSL才是最佳搭档
文章标题:SpringBoot整合spring-data-jpa
文章链接:http://soscw.com/index.php/essay/83750.html