SpringBoot整合spring-data-jpa的方法
jpa是JavaEE定义的一种规范,常用的实现一般是Hibernate,而spring-data-jpa则是对jpa的又一层封装,提供了更多便捷的方法。
这里不会深入讲解spring-data-jpa的使用,只是讲解怎么快速的整合使用,目的是帮助那些想学,但是在整合上老是翻车的同学
导入依赖
com.zaxxer HikariCP mysql mysql-connector-java org.springframework.boot spring-boot-starter-data-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 SpringDataWebProperties HibernateProperties
相关配置的文档docs.spring.io/spring-boot…
定义实体类User
importjava.io.Serializable;
importjava.time.LocalDateTime;
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.Enumerated;
importjavax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
importjavax.persistence.Id;
importjavax.persistence.Index;
importjavax.persistence.Table;
//指定表名称
@Table(name="user",indexes={
//定义索引
@Index(columnList="account",unique=true)
})
//标识实体类
@Entity
//设置表注释
@org.hibernate.annotations.Table(appliesTo="user",comment="用户")
publicclassUserimplementsSerializable{
/**
*
*/
privatestaticfinallongserialVersionUID=4953012795378725917L;
@Id//id字段
@Column(columnDefinition="INT(11)UNSIGNEDCOMMENT'id'")
@GeneratedValue(strategy=GenerationType.IDENTITY)//自增
privateIntegerid;
//账户
@Column(columnDefinition="VARCHAR(50)COMMENT'登录账户'",nullable=false)
privateStringaccount;
//密码
@Column(columnDefinition="VARCHAR(255)COMMENT'登录密码'",nullable=false)
privateStringpassword;
//性别
@Column(columnDefinition="TINYINT(1)COMMENT'性别。0:男,1:女'",nullable=false)
@Enumerated
privateGendergender;
//创建时间
@Column(name="created_date",columnDefinition="timestampDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间'",nullable=false)
privateLocalDateTimecreatedDate;
//最后修改时间
@Column(name="last_modified_date",columnDefinition="timestampNULLDEFAULTNULLCOMMENT'最后一次修改时间'")
privateLocalDateTimelastModifiedDate;
//记录状态
@Column(columnDefinition="TINYINT(1)unsignedCOMMENT'是否启用'",nullable=false)
privateBooleanenabled;
publicIntegergetId(){
returnid;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicStringgetAccount(){
returnaccount;
}
publicvoidsetAccount(Stringaccount){
this.account=account;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicGendergetGender(){
returngender;
}
publicvoidsetGender(Gendergender){
this.gender=gender;
}
publicLocalDateTimegetCreatedDate(){
returncreatedDate;
}
publicvoidsetCreatedDate(LocalDateTimecreatedDate){
this.createdDate=createdDate;
}
publicLocalDateTimegetLastModifiedDate(){
returnlastModifiedDate;
}
publicvoidsetLastModifiedDate(LocalDateTimelastModifiedDate){
this.lastModifiedDate=lastModifiedDate;
}
publicBooleangetEnabled(){
returnenabled;
}
publicvoidsetEnabled(Booleanenabled){
this.enabled=enabled;
}
@Override
publicStringtoString(){
return"User[id="+id+",account="+account+",password="+password+",gender="+gender
+",createdDate="+createdDate+",lastModifiedDate="+lastModifiedDate+",enabled="+enabled
+"]";
}
publicstaticenumGender{
BOY,GIRL
}
}
Repository
抽象出BaseRepository
importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.data.jpa.repository.JpaSpecificationExecutor; importorg.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean//该接口不是一个Repository,不需要生成代理实现 publicinterfaceBaseRepositoryextendsJpaRepository ,JpaSpecificationExecutor //,QuerydslPredicateExecutor 如果使用了QueryDSL还可以实现这个接口 { }
定义UserRepository
importio.springboot.jpa.entity.User; publicinterfaceUserRepositoryextendsBaseRepository{ }
Service
抽象出BaseService
importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.data.jpa.repository.JpaSpecificationExecutor; publicinterfaceBaseServiceextendsJpaRepository ,JpaSpecificationExecutor //,QuerydslPredicateExecutor { }
抽象出AbstractService
importjava.util.List; importjava.util.Optional; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.data.domain.Example; importorg.springframework.data.domain.Page; importorg.springframework.data.domain.Pageable; importorg.springframework.data.domain.Sort; importorg.springframework.data.jpa.domain.Specification; importorg.springframework.transaction.annotation.Transactional; importio.springboot.jpa.repository.BaseRepository; publicabstractclassAbstractServiceimplementsBaseService { /** *泛型注入 */ @Autowired protectedBaseRepository baseRepository; @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicList findAll(){ returnthis.baseRepository.findAll(); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicList findAll(Sortsort){ returnthis.baseRepository.findAll(sort); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicList findAllById(Iterable ids){ returnthis.baseRepository.findAllById(ids); } @Override @Transactional(rollbackFor=Throwable.class) public List saveAll(Iterableentities){ returnthis.baseRepository.saveAll(entities); } @Override @Transactional(rollbackFor=Throwable.class) publicvoidflush(){ this.baseRepository.flush(); } @Transactional(rollbackFor=Throwable.class) publicSsaveAndFlush(Sentity){ returnthis.baseRepository.saveAndFlush(entity); } @Override @Transactional(rollbackFor=Throwable.class) publicvoiddeleteInBatch(Iterable entities){ this.baseRepository.deleteInBatch(entities); } @Override @Transactional(rollbackFor=Throwable.class) publicvoiddeleteAllInBatch(){ this.baseRepository.deleteAllInBatch(); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicTgetOne(IDid){ returnthis.baseRepository.getOne(id); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) public List findAll(Exampleexample){ returnthis.baseRepository.findAll(example); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicList findAll(Exampleexample,Sortsort){ returnthis.baseRepository.findAll(example,sort); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicPagefindAll(Pageablepageable){ returnthis.baseRepository.findAll(pageable); } @Override @Transactional(rollbackFor=Throwable.class) public Ssave(Sentity){ returnthis.baseRepository.save(entity); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicOptional findById(IDid){ returnthis.baseRepository.findById(id); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicbooleanexistsById(IDid){ returnthis.baseRepository.existsById(id); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publiclongcount(){ returnthis.baseRepository.count(); } @Override @Transactional(rollbackFor=Throwable.class) publicvoiddeleteById(IDid){ this.baseRepository.deleteById(id); } @Override @Transactional(rollbackFor=Throwable.class) publicvoiddelete(Tentity){ this.baseRepository.delete(entity); } @Override @Transactional(rollbackFor=Throwable.class) publicvoiddeleteAll(Iterableentities){ this.baseRepository.deleteAll(entities); } @Override @Transactional(rollbackFor=Throwable.class) publicvoiddeleteAll(){ this.baseRepository.deleteAll(); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) public Optional findOne(Exampleexample){ returnthis.baseRepository.findOne(example); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicPage findAll(Exampleexample,Pageablepageable){ returnthis.baseRepository.findAll(example,pageable); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publiclongcount(Example example){ returnthis.baseRepository.count(example); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicbooleanexists(Example example){ returnthis.baseRepository.exists(example); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicOptionalfindOne(Specification spec){ returnthis.baseRepository.findOne(spec); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicList findAll(Specification spec){ returnthis.baseRepository.findAll(spec); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicPage findAll(Specification spec,Pageablepageable){ returnthis.baseRepository.findAll(spec,pageable); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publicList findAll(Specification spec,Sortsort){ returnthis.baseRepository.findAll(spec,sort); } @Override @Transactional(readOnly=true,rollbackFor=Throwable.class) publiclongcount(Specification spec){ returnthis.baseRepository.count(spec); } }
定义UserService
importorg.springframework.stereotype.Service; importio.springboot.jpa.entity.User; @Service publicclassUserServiceextendsAbstractService{ }
添加注解驱动
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.boot.autoconfigure.domain.EntityScan;
importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories(basePackages={"io.springboot.jpa.repository"})
@EntityScan(basePackages={"io.springboot.jpa.entity"})
publicclassJpaApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(JpaApplication.class,args);
}
}
@EnableJpaRepositories指定repository所在的包@EntityScan指定entity所在的包
测试
importio.springboot.jpa.JpaApplication;
importio.springboot.jpa.entity.User;
importio.springboot.jpa.service.UserService;
importjava.time.LocalDateTime;
importorg.junit.Test;
importorg.junit.runner.RunWith;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=JpaApplication.class,webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
publicclassJpaApplicationTest{
staticfinalLoggerLOGGER=LoggerFactory.getLogger(JpaApplicationTest.class);
@Autowired
UserServiceuserService;
@Test
publicvoidtest(){
//存储
Useruser=newUser();
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("savesuccess.....");
//检索
Userresults=this.userService.findById(user.getId()).orElseGet(null);
LOGGER.info("queryresult={}",results);
}
}
自动创建的表
CREATETABLE`user`( `id`int(11)unsignedNOTNULLAUTO_INCREMENTCOMMENT'id', `account`varchar(50)NOTNULLCOMMENT'登录账户', `created_date`timestampNOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间', `enabled`tinyint(1)unsignedNOTNULLCOMMENT'是否启用', `gender`tinyint(1)NOTNULLCOMMENT'性别。0:男,1:女', `last_modified_date`timestampNULLDEFAULTNULLCOMMENT'最后一次修改时间', `password`varchar(255)NOTNULLCOMMENT'登录密码', PRIMARYKEY(`id`), UNIQUEKEY`UKdnq7r8jcmlft7l8l4j79l1h74`(`account`) )ENGINE=InnoDBDEFAULTCHARSET=utf8mb4COMMENT='用户';
执行的日志
Hibernate: insert into user (account,created_date,enabled,gender,last_modified_date,password) values (?,?,?,?,?,?) 2020-06-2317:57:36.264INFO7612---[main]i.s.jpa.test.JpaApplicationTest:savesuccess..... Hibernate: select user0_.idasid1_0_0_, user0_.accountasaccount2_0_0_, user0_.created_dateascreated_3_0_0_, user0_.enabledasenabled4_0_0_, user0_.genderasgender5_0_0_, user0_.last_modified_dateaslast_mod6_0_0_, user0_.passwordaspassword7_0_0_ from useruser0_ where user0_.id=? 2020-06-2317:57:36.303INFO7612---[main]i.s.jpa.test.JpaApplicationTest:queryresult=User[id=1,account=kevinblandy.cn@gmail.com,password=123456,gender=GIRL,createdDate=2020-06-23T17:57:36,lastModifiedDate=null,enabled=true]
总结
到此这篇关于SpringBoot整合spring-data-jpa的方法的文章就介绍到这了,更多相关SpringBoot整合spring-data-jpa内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。