首页>>后端>>SpringBoot->Spring Data JPA的使用详解

Spring Data JPA的使用详解

时间:2023-11-29 本站 点击:0

JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

SpringBoot使用SpringDataJPA完成CRUD操作. 数据的存储以及访问都是最为核心的关键部分,现在有很多企业采用主流的数据库,如关系型数据库:MySQL,Oracle,SQLServer。非关系型数据库:redis,mongodb等.

Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。

1、导入相关依赖并配置文件

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:username:password:jpa:database:mysql#日志中显示sql语句show-sql:truehibernate:naming:physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

2、JPA使用

步骤一:新建实体类并添加JPA注解

@Data@AllArgsConstructor@NoArgsConstructor@Entity@Table(name="article")publicclassArticleimplementsSerializable{@Id@GeneratedValue@Column(name="a_id")privateIntegeraId;@Column(name="article_title")privateStringarticleTitle;@Column(name="article_content")privateStringarticleContent;@Column(name="head_image")privateStringheadImage;@Column(name="article_author")privateStringarticleAuthor;@Column(name="type_number")privateIntegertypeNumber;@Column(name="pageviews")privateIntegerpageViews;@Column(name="create_time")privateStringcreateTime;@Column(name="is_state")privateIntegerisState;}

步骤二:新建接口ArticleDao

/***JpaRepository<T,ID>提供简单的数据操作接口*Article实体类类型*Integer主键类型**JpaSpecificationExecutor<T>提供复杂查询接口*Article实体类类型**Serializable序列化*/@RepositorypublicinterfaceArticleDaoextendsJpaRepository<Article,Integer>,JpaSpecificationExecutor<Article>,Serializable{//这里没有代码,注意没有代码..........}

步骤三:测试

@SpringBootTestclassSpringboot07JpaApplicationTests{@AutowiredprivateArticleDaoarticleDao;@TestvoidcontextLoads(){List<Article>articleList=articleDao.findAll();articleList.forEach(System.out::println);}}

3、JPA查询方法命令规范

关键字方法命名sql where字句AndfindByNameAndPwdwhere name= ? and pwd =?OrfindByNameOrSexwhere name= ? or sex=?Is,EqualsfindById,findByIdEqualswhere id= ?BetweenfindByIdBetweenwhere id between ? and ?LessThanfindByIdLessThanwhere id < ?LessThanEqualsfindByIdLessThanEqualswhere id <= ?GreaterThanfindByIdGreaterThanwhere id > ?GreaterThanEqualsfindByIdGreaterThanEqualswhere id > = ?AfterfindByIdAfterwhere id > ?BeforefindByIdBeforewhere id < ?IsNullfindByNameIsNullwhere name is nullisNotNull,NotNullfindByNameNotNullwhere name is not nullLikefindByNameLikewhere name like ?NotLikefindByNameNotLikewhere name not like ?StartingWithfindByNameStartingWithwhere name like '?%'EndingWithfindByNameEndingWithwhere name like '%?'ContainingfindByNameContainingwhere name like '%?%'OrderByfindByIdOrderByXDescwhere id=? order by x descNotfindByNameNotwhere name <> ?InfindByIdIn(Collection<?> c)where id in (?)NotInfindByIdNotIn(Collection<?> c)where id not in (?)TruefindByAaaTuewhere aaa = trueFalsefindByAaaFalsewhere aaa = falseIgnoreCasefindByNameIgnoreCasewhere UPPER(name)=UPPER(?)

4、JPQL语法生成

publicinterfaceStandardRepositoryextendsJpaRepository<Standard,Long>{//JPA的命名规范List<Standard>findByName(Stringname);//自定义查询,没有遵循命名规范@Query("fromStandardwherename=?")StandardfindByNamexxxx(Stringname);//遵循命名规范,执行多条件查询StandardfindByNameAndMaxLength(Stringname,IntegermaxLength);//自定义多条件查询@Query("fromStandardwherename=?2andmaxLength=?1")StandardfindByNameAndMaxLengthxxx(IntegermaxLength,Stringname);//使用”标准”SQL查询,以前mysql是怎么写,这里继续@Query(value="select*fromT_STANDARDwhereC_NAME=?andC_MAX_LENGTH=?",nativeQuery=true)StandardfindByNameAndMaxLengthxx(Stringname,IntegermaxLength);//模糊查询StandardfindByNameLike(Stringname);@Modifying//代表本操作是更新操作@Transactional//事务注解@Query("deletefromStandardwherename=?")voiddeleteByName(Stringname);@Modifying//代表本操作是更新操作@Transactional//事务注解@Query("updateStandardsetmaxLength=?wherename=?")voidupdateByName(IntegermaxLength,Stringname);}

5、JPA URUD示例

modle:Article.java

@Data@AllArgsConstructor@NoArgsConstructor@Entity@Table(name="article")publicclassArticleimplementsSerializable{@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="a_id")privateintaId;@Column(name="article_title")privateStringarticleTitle;@Column(name="article_content")privateStringarticleContent;@Column(name="head_image")privateStringheadImage;@Column(name="article_author")privateStringarticleAuthor;@Column(name="type_number")privateinttypeNumber;privateintpageviews;@DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")@JsonFormat(pattern="yyyy-MM-ddHH:mm:ss",timezone="GMT+8")@Column(name="create_time")privateDatecreateTime;@Column(name="is_state")privateintisState;}

dao:ArticleDao.java

publicinterfaceArticleDaoextendsJpaRepository<Article,Integer>,JpaSpecificationExecutor<Article>,Serializable{List<Article>findByArticleTitleContaining(Stringkeywords);//自定义方法@Query("selectartfromArticleartwhereart.articleTitlelike%?1%orart.articleContentlike%?1%")Page<Article>findByLike(Stringkeywords,Pageablepageable);}

service:ArticleService.java

publicinterfaceArticleService{Page<Article>findByLike(Stringkeywords,intpage,intpageSize);publicvoiddelArticle(intaId);publicvoidupdateArticle(Articlearticle);publicvoidaddArticle(Articlearticle);}

serviceImpl:ArticleServiceImpl.java

@ServicepublicclassArticleServiceImplimplementsArticleService{@AutowiredprivateArticleDaoarticleDao;@OverridepublicPage<Article>findByLike(Stringkeywords,intpage,intpageSize){Sortsort=Sort.by(Sort.Direction.DESC,"createTime");PageRequestpageable=PageRequest.of(page-1,pageSize,sort);Page<Article>pageResult=articleDao.findByLike(keywords,pageable);returnpageResult;}@OverridepublicvoiddelArticle(intaId){articleDao.deleteById(aId);}@OverridepublicvoidupdateArticle(Articlearticle){articleDao.save(article);}@OverridepublicvoidaddArticle(Articlearticle){articleDao.save(article);}}

controller:ArticleController.java

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:username:password:jpa:database:mysql#日志中显示sql语句show-sql:truehibernate:naming:physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl0

6、JPA实现分页和模糊查询

modle:Article.java

@Data@AllArgsConstructor@NoArgsConstructor@Entity@Table(name="article")publicclassArticleimplementsSerializable{@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="a_id")privateintaId;@Column(name="article_title")privateStringarticleTitle;@Column(name="article_content")privateStringarticleContent;@Column(name="head_image")privateStringheadImage;@Column(name="article_author")privateStringarticleAuthor;@Column(name="type_number")privateinttypeNumber;privateintpageviews;@DateTimeFormat(pattern="yyyy-MM-ddHH:mm:ss")@JsonFormat(pattern="yyyy-MM-ddHH:mm:ss",timezone="GMT+8")@Column(name="create_time")privateDatecreateTime;@Column(name="is_state")privateintisState;}

dao:ArticleDao.java

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:username:password:jpa:database:mysql#日志中显示sql语句show-sql:truehibernate:naming:physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl2

service:ArticleService.java

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:username:password:jpa:database:mysql#日志中显示sql语句show-sql:truehibernate:naming:physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl3

serviceImpl:ArticleServiceImpl.java

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:username:password:jpa:database:mysql#日志中显示sql语句show-sql:truehibernate:naming:physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl4

controller:ArticleController.java

spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:username:password:jpa:database:mysql#日志中显示sql语句show-sql:truehibernate:naming:physical-strategy:org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl5


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/SpringBoot/396.html