springboot-jpa的实现操作
JPA全称为JavaPersistenceAPI(Java持久层API),它是Sun公司在JavaEE5中提出的Java持久化规范。
它为Java开发人员提供了一种对象/关联映射工具,来管理Java应用中的关系数据,JPA吸取了目前Java持久化技术的优点,旨在规范、简化Java对象的持久化工作。
JPA对于单表的或者简单的SQL查询非常友好,甚至可以说非常智能。他为你准备好了大量的拿来即用的持久层操作方法。甚至只要写findByName这样一个接口方法,他就能智能的帮你执行根据名称查找实体类对应的表数据,完全不用写SQL。
它相对于mybatis来说不用写xml等配置,简直方便的不行,对于我们开发者来说,谁更简单,开发效率更高,我们就喜欢谁(不喜欢不行,看看产品经理手里的菜刀)!!!
这时候mybatis就不服了,我确实需要写一大堆乱七八糟的xml,但是也可以用注解啊。
还不是要写sql,总是一写增删改查sql,有没有把这些常见的增删改查全部封装起来,我们直接调用api,sql让它们自动组装就好了,说实话我自己封装了一个基于mybatis的组件,常见的增删改查,自己组装成sql去查询,后来由于没有oracle,sqlserver的数据库环境,对这些数据库的时间等等函数支持不好,又有jpa和mybatisplus这些现有的,我也就偷懒了
好了我们之前有实现过springboot-mybatis
springboot-mybatisplus的整合,现在就来实现一下jpa的,你们看看哪个比较方便好用,可以自己用用看
这是我实现的demo预览
由于我想看到效果,又不想装postman来测试,我就集成了swagger
最终效果如上图
好了,我直接放代码了
4.0.0 com.zkb spring-data-jpa 1.0-SNAPSHOT org.apache.maven.plugins maven-compiler-plugin 8 8 org.springframework.boot spring-boot-starter-web 2.1.1.RELEASE org.springframework.boot spring-boot-starter-data-jpa 2.1.1.RELEASE mysql mysql-connector-java 8.0.18 org.projectlombok lombok 1.18.12 org.springframework.boot spring-boot-devtools 2.0.4.RELEASE org.springframework.boot spring-boot-starter-test 2.1.2.RELEASE test com.alibaba druid 1.0.31 org.junit.jupiter junit-jupiter RELEASE compile org.junit.jupiter junit-jupiter RELEASE compile org.slf4j slf4j-api 1.7.25 org.springframework.boot spring-boot-test 2.2.2.RELEASE compile io.springfox springfox-swagger2 2.9.2 io.swagger swagger-annotations io.swagger swagger-models io.swagger swagger-annotations 1.5.22 io.swagger swagger-models 1.5.22 io.springfox springfox-swagger-ui 2.9.2 com.github.xiaoymin swagger-bootstrap-ui 1.9.1
server: port:5001 spring: datasource: type:com.alibaba.druid.pool.DruidDataSource#Druid是阿里巴巴开源平台上一个数据库连接池实现,结合了C3P0、DBCP、PROXOOL等DB池的优点,同时加入了日志监控 driver-class-name:com.mysql.cj.jdbc.Driver url:jdbc:mysql://localhost:3306/test-demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull username:root password:root dbcp2: min-idle:5 initial-size:5 max-total:5 max-wait-millis:200 jpa: database:mysql database-platform:org.hibernate.dialect.MySQL5InnoDBDialect show-sql:true hibernate: ddl-auto:update
packagecom.zkb.entity;
importcom.fasterxml.jackson.databind.annotation.JsonSerialize;
importcom.fasterxml.jackson.databind.ser.std.ToStringSerializer;
importio.swagger.annotations.ApiModel;
importio.swagger.annotations.ApiModelProperty;
importlombok.Data;
importjavax.persistence.*;
/**
*实体类
*/
@Entity
@Table(name="t_user")
@Data
@ApiModel(value="用户信息",description="用户信息")
publicclassUser{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@ApiModelProperty(value="主键")
@JsonSerialize(using=ToStringSerializer.class)
privateLongid;
@Column(name="username")
@ApiModelProperty(value="用户名")
privateStringusername;
@Column(name="password")
@ApiModelProperty(value="密码")
privateStringpassword;
}
packagecom.zkb.dao; importcom.zkb.entity.User; importorg.springframework.data.jpa.repository.JpaRepository; publicinterfaceUserRepositoryextendsJpaRepository{ }
packagecom.zkb.service;
importcom.zkb.entity.User;
importjava.util.List;
publicinterfaceUserService{
publicvoiddeleteUser(Longid);
ListgetList();
}
packagecom.zkb.service.impl;
importcom.zkb.dao.UserRepository;
importcom.zkb.entity.User;
importcom.zkb.service.UserService;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Service;
importjava.util.List;
@Service
publicclassUserServiceImplimplementsUserService{
@Autowired
privateUserRepositoryuserRepository;
@Override
publicvoiddeleteUser(Longid){
System.out.println(userRepository);
userRepository.deleteById(id);
}
@Override
publicListgetList(){
returnuserRepository.findAll();
}
}
packagecom.zkb.controller;
importcom.zkb.entity.User;
importcom.zkb.service.UserService;
importio.swagger.annotations.Api;
importio.swagger.annotations.ApiOperation;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
importjava.util.List;
@RestController
@RequestMapping("/user")
@Api(value="user",tags="user")
publicclassUserController{
@Autowired
privateUserServiceuserService;
@PostMapping("/del")
@ApiOperation(value="删除",notes="删除")
publicStringdelete(@RequestParam("id")Longid){
userService.deleteUser(id);
return"true";
}
@PostMapping("/getList")
@ApiOperation(value="查询所有",notes="查询所有")
publicListgetList(){
returnuserService.getList();
}
}
packagecom.zkb.conf;
importio.swagger.annotations.ApiOperation;
importio.swagger.models.auth.In;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importspringfox.documentation.builders.ApiInfoBuilder;
importspringfox.documentation.builders.PathSelectors;
importspringfox.documentation.builders.RequestHandlerSelectors;
importspringfox.documentation.service.ApiInfo;
importspringfox.documentation.service.ApiKey;
importspringfox.documentation.service.Contact;
importspringfox.documentation.spi.DocumentationType;
importspringfox.documentation.spring.web.plugins.Docket;
importspringfox.documentation.swagger2.annotations.EnableSwagger2;
importjava.util.Arrays;
importjava.util.List;
@Configuration
@EnableSwagger2
publicclassSwaggerApp{
@Bean
publicDocketcreateRestApi1(){
returnnewDocket(DocumentationType.SWAGGER_2).enable(true).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.basePackage("com.zkb.controller"))
.paths(PathSelectors.any()).build().securitySchemes(apiKeyList()).groupName("接口中心");
}
privateApiInfoapiInfo(){
returnnewApiInfoBuilder()
.title("API")
.contact(newContact("XXXXX","http://XXXXXX.XXXX/",""))
.version("1.0")
.description("API描述")
.build();
}
privateListapiKeyList(){
returnArrays.asList(newApiKey("登录token","token",In.HEADER.name()),
newApiKey("设备类型(android,ios,pc)---必填","deviceType",In.HEADER.name()));
}
}
packagecom.zkb;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importspringfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
publicclassApp{
publicstaticvoidmain(String[]args){
SpringApplication.run(App.class,args);
}
}
CREATETABLE`t_user`( `id`bigintNOTNULLAUTO_INCREMENT, `username`varchar(50)COLLATEutf8mb4_general_ciDEFAULTNULL, `password`varchar(50)COLLATEutf8mb4_general_ciDEFAULTNULL, PRIMARYKEY(`id`)USINGBTREE )ENGINE=InnoDBAUTO_INCREMENT=1214893367637352451DEFAULTCHARSET=utf8mb4COLLATE=utf8mb4_general_ci;
非常简单的一张表,注意数据库名称
到这里就已经实现了一个非常简单的jpademo了
当然我这里只是指路,让知怎么用
补充:SpringBoot使用JPA实现增删查改
一、运行环境
SpringBoot2.3.0
JDK1.8
IDEA2020.1.2
MySQL5.7
二、依赖及应用程序配置
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-validation org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine
1、升级到SpringBoot2.2,spring-boot-starter-test默认使用JUnit5作为单元测试框架,写单元测试时注解@RunWith(Spring.class)升级为@ExtendWith(SpringExtension.class)
2、升级到SpringBoot2.3,hibernate-validator从spring-boot-starter-web移除,需要单独引入
3、升级到SpringBoot2.3,MySQL驱动由com.mysql.jdbc.Driver变更为com.mysql.cj.jdbc.Driver;同时,数据源url需要添加serverTimezone=UTC&useSSL=false参数
3、升级到SpringBoot2.x,默认不自动注入HiddenHttpMethodFilter,需要设置spring.mvc.hiddenmethod.filter.enabled=true开启PUT、DELETE方法支持
应用程序配置如下:
spring.application.name=springbootjpa management.endpoints.jmx.exposure.include=* management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always #应用服务WEB访问端口 server.port=8080 #ActuatorWeb访问端口 management.server.port=8081 #mysqlsetting spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?serverTimezone=UTC&useSSL=false spring.datasource.username=username spring.datasource.password=password #JPAsetting spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql=true #thymeleafsetting spring.thymeleaf.cache=false #delete、put方法支持 spring.mvc.hiddenmethod.filter.enabled=true
三、定义实体
使用@Entity标记实体类
importlombok.Data;
importjavax.persistence.*;
importjavax.validation.constraints.NotEmpty;
importjava.io.Serializable;
@Entity
@Data
publicclassArticleextendsBaseEntityimplementsSerializable{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
privateLongid;
@Column(nullable=false,unique=true)
@NotEmpty(message="标题不能为空")
privateStringtitle;
@Column(nullable=false)
privateStringbody;
}
为了自动添加创建日期、修改日期、创建人及修改人,我们把创建、修改信息放到父类中由实体类继承,并开启SpringBoot的自动审计功能,将创建/修改信息自动注入
1、定义实体类的父类,@CreatedDate、@LastModifiedDate、@CreatedBy、@LastModifiedBy标注相应字段
importorg.hibernate.annotations.Columns;
importorg.springframework.data.annotation.CreatedBy;
importorg.springframework.data.annotation.CreatedDate;
importorg.springframework.data.annotation.LastModifiedBy;
importorg.springframework.data.annotation.LastModifiedDate;
importorg.springframework.data.jpa.domain.support.AuditingEntityListener;
importjavax.persistence.Column;
importjavax.persistence.EntityListeners;
importjavax.persistence.MappedSuperclass;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
publicclassBaseEntity{
@CreatedDate
privateLongcreateTime;
@LastModifiedDate
privateLongupdateTime;
@Column(name="create_by")
@CreatedBy
privateStringcreateBy;
@Column(name="lastmodified_by")
@LastModifiedBy
privateStringlastmodifiedBy;
publicLonggetCreateTime(){
returncreateTime;
}
publicvoidsetCreateTime(LongcreateTime){
this.createTime=createTime;
}
publicLonggetUpdateTime(){
returnupdateTime;
}
publicvoidsetUpdateTime(LongupdateTime){
this.updateTime=updateTime;
}
publicStringgetCreateBy(){
returncreateBy;
}
publicvoidsetCreateBy(StringcreateBy){
this.createBy=createBy;
}
publicStringgetLastmodifiedBy(){
returnlastmodifiedBy;
}
publicvoidsetLastmodifiedBy(StringlastmodifiedBy){
this.lastmodifiedBy=lastmodifiedBy;
}
}
@MappedSuperclass注解:
作用于实体类的父类上,父类不生成对应的数据库表
标注@MappedSuperclass的类不能再标注@Entity或@Table注解,也无需实现序列化接口
每个子类(实体类)对应一张数据库表,数据库表包含子类属性和父类属性
标注@MappedSuperclass的类可以直接标注@EntityListeners实体监听器
@EntityListeners(AuditingEntityListener.class)注解:
作用范围仅在标注@MappedSuperclass类的所有继承类中,并且实体监听器可以被其子类继承或重载
开启JPA的审计功能,需要在SpringBoot的入口类标注@EnableJpaAuditing
创建日期、修改日期有默认方法注入值,但创建人和修改人注入则需要手动实现AuditorAware接口:
@Configuration publicclassBaseEntityAuditorimplementsAuditorAware{ @Override publicOptional getCurrentAuditor(){ return""; } }
四、DAO层实现
JPA支持通过约定方法名进行数据库查询、修改:
importorg.springframework.data.jpa.repository.JpaRepository; importspringbootjpa.entity.Article; publicinterfaceArticleRepositoryextendsJpaRepository{ ArticlefindById(longid); }
通过约定方法名查询,只需实现JpaRepository接口声明查询方法而不需要具体实现
此外,可以在方法上标注@Query实现JPQL或原生SQL查询
JpaRepository
@Autowired
privateArticleRepositoryarticleRepository;
@RequestMapping("")
publicModelAndViewarticlelist(@RequestParam(value="start",defaultValue="0")Integerstart,@RequestParam(value="limit",defaultValue="5")Integerlimit){
start=start<0?0:start;
Sortsort=Sort.by(Sort.Direction.DESC,"id");
Pageablepageable=PageRequest.of(start,limit,sort);
Pagepage=articleRepository.findAll(pageable);
ModelAndViewmodelAndView=newModelAndView("article/list");
modelAndView.addObject("page",page);
returnmodelAndView;
}
如果根据某一字段排序,可以用Sort.by方法构建Sort对象;如果根据多个字段排序,首先构建Sort.Order数组List
PageRequest.of方法生成Pageable对象
五、Contrller控制器
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.data.domain.Page;
importorg.springframework.data.domain.PageRequest;
importorg.springframework.data.domain.Pageable;
importorg.springframework.data.domain.Sort;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.*;
importorg.springframework.web.servlet.ModelAndView;
importspringbootjpa.entity.Article;
importspringbootjpa.repository.ArticleRepository;
@Controller
@RequestMapping("/article")
publicclassArticleController{
@Autowired
privateArticleRepositoryarticleRepository;
@RequestMapping("")
publicModelAndViewarticlelist(@RequestParam(value="start",defaultValue="0")Integerstart,
@RequestParam(value="limit",defaultValue="5")Integerlimit){
start=start<0?0:start;
Sortsort=Sort.by(Sort.Direction.DESC,"id");
Pageablepageable=PageRequest.of(start,limit,sort);
Pagepage=articleRepository.findAll(pageable);
ModelAndViewmodelAndView=newModelAndView("article/list");
modelAndView.addObject("page",page);
returnmodelAndView;
}
@RequestMapping("/add")
publicStringaddArticle(){
return"article/add";
}
@PostMapping("")
publicStringsaveArticle(Articlearticle){
articleRepository.save(article);
return"redirect:/article";
}
@GetMapping("/{id}")
publicModelAndViewgetArticle(@PathVariable("id")Integerid){
Articlearticle=articleRepository.findById(id);
ModelAndViewmodelAndView=newModelAndView("article/show");
modelAndView.addObject("article",article);
returnmodelAndView;
}
@DeleteMapping("/{id}")
publicStringdeleteArticle(@PathVariable("id")longid){
System.out.println("put方法");
articleRepository.deleteById(id);
return"redirect:/article";
}
@GetMapping("edit/{id}")
publicModelAndVieweditArticle(@PathVariable("id")Integerid){
Articlearticle=articleRepository.findById(id);
ModelAndViewmodelAndView=newModelAndView("article/edit");
modelAndView.addObject("article",article);
returnmodelAndView;
}
@PutMapping("/{id}")
publicStringeditArticleSave(Articlearticle,longid){
System.out.println("put方法");
article.setId(id);
articleRepository.save(article);
return"redirect:/article";
}
}
因为
六、其他
th:value和th:field区别:
th:value解析成html,表现为:value="${th:value}"
th:field解析成html,表现为:name="${th:name}"value="${th:value}"
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。