当前位置: 首页 > 后端技术 > Java

SpringBoot集成SpringDataJPA

时间:2023-04-01 16:05:03 Java

JPA简介JPA(JavaPersistenceAPI)是一种Java持久化API,是Sun提出的一种基于ORM的Java持久化规范。ORM(ObjectRelationalMapping)的全称是对象关系映射。主流的JavaORM框架有Mybatis、Hibernate等。SpringDataJPASpringDataJPA是SpringData框架的一个模块,简化了JPA的实现。另外,SpringDataJPA还可以帮助我们简化持久层的开发。对于简单的查询,SpringDataJPA可以根据方法名进行解析,自动生成查询语句进行查询;对于复杂查询,SpringDataJPA也支持原生SQL。SpringDataJPA实践创建一个SpringBoot项目,使用JPA实现简单的CRUD。引入依赖POM文件如下:4.0.0org.springframework.bootspring-boot-starter-parent2.2。5.RELEASEcom.exampledemo0.0.1-SNAPSHOTdemoSpringBoot演示项目1.8org.springframework.bootspring-boot-starter-data-jpa<依赖>org.springframework.bootspring-boot-starter-weborg.projectlombok龙目岛truemysqlmysql-connector-javaorg.springframework.boot<artifactId>spring-boot-starter-test测试org.springframework.bootspring-boot-maven-plugin<配置>org.projectlomboklombok配置JPA和MySQLapplication.yml配置文件如下:spring:datasource:url:jdbc:mysql://localhost:3306/jpa_test?serverTimezone=UTC用户名e:rootpassword:123456driver-class-name:com.mysql.cj.jdbc.Driverjpa:hibernate:ddl-auto:update#当表中有数据时,不会清除,只会更新#控制台显示SQLshow-sql:true写实体类本文以User类为例:packagecom.example.entity;importlombok.Data;importjavax.persistence.*;/***@Authorjoin*@Date2021/10/13*/@Data@Entity@Table(name="user")publicclassUserextendsBaseEntity{@Id@Column(name="id")@GeneratedValue(strategy=GenerationType.IDENTITY)privateIntegerID;@Column(name="name",columnDefinition="varchar(20)notnull")privateStringname;}User类包含id和name两个属性,User类也继承BaseEntity,当存在多个实体类时项目中,我们不妨把数据表中的常用字段封装在BaseEntity中,比如create_time、update_time等。packagecom.example.entity;importlombok.Data;importjavax.persistence.*;importjava.util.Date;/***@Authorjoin*@Date2021/10/13*/@Data@MappedSuperclasspublicclassBaseEntity{@Column(name="create_time")@Temporal(TemporalType.TIMESTAMP)privateDatecreateTime;@Column(name="update_time")@Temporal(TemporalType.TIMESTAMP)私人日期更新时间;@PrePersistpublicvoidprePersist(){Datenow=newDate();如果(createTime==null){createTime=现在;}if(updateTime==null){updateTime=now;}}@PreUpdatepublicvoidpreUpdate(){updateTime=newDate();}@PreRemovepublicvoidpreRemove(){updateTime=newDate();}}注解解释:@Data:lombok注解,可以自动生成get()、set()、toString()等方法;@Entity:JPA注解,声明该类为实体类,必须与@Id一起使用;@Table:JPA注解,表示将实体类映射到数据库的用户表(name指定表名);@Id:JPA注解,声明主键;@GeneratedValue:JPA注解,表示主键的生成策略,IDENTITY表示使用自增id;@Column:JPA注解,声明实体对象的属性映射到数据表中的哪个字段,name指定字段名,columnDefinition指定字段的定义@MappedSuperclass:JPA注解,应用于实体的父类class,受该注解影响的类不会映射到数据表,但其属性会映射到子类的数据表。@PrePersist:被@PrePersist修饰的方法在实体持久化到数据库之前被调用;@PreUpdate:被@PreUpdate修饰的方法在实体的某个属性发生变化时被调用,比如更新实体的update_time;@PreRemove:用@PreRemove修饰的方法在实体从数据库中删除之前被调用。定义repository并写入UserRepository:packagecom.example.repository;importcom.example.entity.User;importlombok.NonNull;importorg.springframework.data.jpa.repository.JpaRepository;importjava.util.Optional;/***@Authorjoin*@Date2021/10/13*/publicinterfaceUserRepositoryextendsJpaRepository{@NonNullOptionalfindByName(@NonNullStringname);}UserRepository可以自动生成基本的CRUD方法,比如findById(),save()等。在上面的代码中,我们还自定义了一个方法findByName(),JpaRepository可以根据方法名自动实现相应的逻辑。注意JpaRepository的命名约定。定义控制器编写UserController:packagecom.example.controller;importcom.example.entity.User;importcom.example.repository.UserRepository;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype。控制器;导入org.springframework.web.bind.annotation.*;导入java.util.Optional;/***@Authorjoin*@Date2021/10/13*/@Controller@RequestMapping("/user")public类UserController{@AutowiredprivateUserRepositoryuserRepository;@RequestMapping(path="addUser",method=RequestMethod.POST)@ResponseBodypublicvoidaddUser(@RequestBodyUseruser){userRepository.save(user);}@RequestMapping(path="deleteUser",method=RequestMethod.POST)@ResponseBodypublicvoiddeleteUser(@RequestBodyUseruser){userRepository.delete(user);}@RequestMapping(path="/getById/{id}",method=RequestMethod.GET)@ResponseBodypublicUserqueryUserById(@PathVariable("id")intid){returnuserRepository.findById(id).orElse(null);}@RequestMapping(path="/getByName/{name}",method=RequestMethod.GET)@ResponseBodypublicUserqueryUserByName(@PathVariable("name")Stringname){Optionaloptional=userRepository.findByName(name);返回optional.orElse(null);}}在上面的代码中,我们实现了四个方法,分别用于创建、删除和查询用户测试启动项目,使用Navicat查看'jpa_test'库下的数据表,发现JPA自动创建了一个我们的user表:该表包含了User类中定义的id、name和BaseEntity类的Create_time、update_time等字段。添加用户使用Postman发送post请求,添加用户:查询用户使用id查询:使用name查询:JPA解析原理JPA遵循约定优于配置(Conventionoverconfiguration)的原则,遵循由定义的命名规则弹簧和JPQL。Spring提供了一种基于命名规则的查询构造机制,从方法名中过滤掉一些关键字,比如find...By,read...By,query...By,count...By,get...By等系统会根据关键字将方法名解析成两个子句,第一个By是区分两个子句的关键字。By之前的子句是查询子句,指定要返回的对象。剩下的就是条件子句,如果方法名是findBy...,那么返回的就是定义Respository时指定的对象。下表下表中一些关键字的:关键字samplemjpqlsnippetandfindbylastnameandfirstname…x.lastname=?1andorfindbylastnameorfirstname…wherex.lastname=?其中x.startDate在?1和?2LessThanfindByAgeLessThan之间...其中x.age?1GreaterThanEqualfindByAgeGreaterThanEqual...其中x.age>=Start?1之后?1BeforefindByStartDateBefore...其中x.startDate?1InfindByAgeIn(Collectionages)...其中x.age在?1NotInfindByAgeNotIn(Collectionage)...其中x.age不在?1TRUEfindByActiveTrue()...其中x.active=trueFALSEfindByActiveFalse()...其中x.active=falseIgnoreCasefindByFirstnameIgnoreCase...whereUPPER(x.firstame)=UPPER(?1)欢迎批评指正