1.Java项目开发中实现分页的分分页三种方式一篇包会
2.JPA系列(四):jpa的查询方法
3.SpringDataJPAç使ç¨è¯¦è§£
Java项目开发中实现分页的三种方式一篇包会
Java项目开发中,实现分页功能是页源原理常见的需求。以下为三种实现方式的实现详细介绍:
第一种方式:SpringDataJPA分页
1. 引入依赖:确保项目依赖中包含SpringDataJPA。
2. Service中编写分页服务:定义Pageable对象处理分页参数,分分页使用PageRequest创建Page对象包装查询结果。页源原理
3. Repository中处理分页:继承JpaRepository,实现内外比指标源码传入pageable参数,分分页返回Page包装的页源原理结果。
第二种方式:MyBatis分页
1. 引入PageHelper依赖:确保项目依赖中包含PageHelper。实现
2. 使用PageHelper实现分页:调用PageHelper.startPage和结束分页的分分页代码,中间包含业务查询逻辑,页源原理通过PageInfo对象包装查询结果。实现
第三种方式:Hutools工具类分页
1. 引入依赖:引入Hutools所有工具类。分分页
2. 分页实现:使用PageUtil.totalPage计算总页数,页源原理CollUtil.page返回指定分页结果,实现站点展示 源码注意索引从1开始。
总结:
1. 注意:在实际项目中,避免使用Map对象包装分页结果,应自定义实体对象返回,防止内存泄露风险。
2. SpringDataJPA分页时,分页索引从0开始,libsvm源码集成错误传参可能导致分页结果错乱或重复。
3. Mybatis分页借助PageHelper,通过PageInfo对象获取分页参数,用于前端展示。
4. Hutools分页方式灵活、便于阅读,适合复杂查询业务,convnet源码解析简化分页实现。
以上三种方式各具特色,具体选择应视项目需求和团队习惯。分享来源于实际经验,希望对大家有所帮助。
JPA系列(四):jpa的查询方法
JPA的查询方法提供了多种灵活性,包括使用JPQL(对象关系映射查询语言)进行基础和模糊查询,jfinal源码分析以及通过原生SQL进行更深入的操作。首先,@Query注解结合JPQL支持面向对象的查询,如在CityEntity实体类中,通过`@Query("select c from CityEntity c where c.name = ?1 and c.id = ?2")`,可以查询到对应id和name的数据,等同于SQL语句`select * from city where name = '攀枝花' and id = 2`。
模糊查询时,通过`@Query("select c from CityEntity c where c.name like ?1")`,可以使用like关键字配合%进行匹配。当需要直接使用SQL语句时,通过nativeQuery=true,如`@Query(nativeQuery=true, value="select * from city where name like ?1")`,可以针对特定的SQL语句进行查询。
排序功能支持在JPQL和原生SQL中实现,例如`@Query("select c from CityEntity c order by c.price DESC")`,或者在SQL中加入`order by`关键字。对于分页查询,可以利用Pageable参数,如`@Query("select c from CityEntity c")`配合分页接口方法,实现排序后分页的结果。
如果需要进行联表查询或分页,可以指定表间关系,@Param注解用于绑定查询参数,而@Modifying则用于修改和删除操作,需要配合@Transactional注解确保事务的正确执行。例如,修改操作的repository方法可能写为`@Modifying@Query("update CityEntity c set price = ?1 where c.id = ?2")`,并确保在controller方法中传递正确的参数。
SpringDataJPAç使ç¨è¯¦è§£
JPA顾åæä¹å°±æ¯JavaPersistenceAPIçææï¼æ¯JDK5.0注解æXMLæ述对象ï¼å ³ç³»è¡¨çæ å°å ³ç³»ï¼å¹¶å°è¿è¡æçå®ä½å¯¹è±¡æä¹ åå°æ°æ®åºä¸ãSpringBoot使ç¨SpringDataJPAå®æCRUDæä½.æ°æ®çåå¨ä»¥å访é®é½æ¯æä¸ºæ ¸å¿çå ³é®é¨åï¼ç°å¨æå¾å¤ä¼ä¸éç¨ä¸»æµçæ°æ®åºï¼å¦å ³ç³»åæ°æ®åºï¼MySQLï¼Oracleï¼SQLServerãéå ³ç³»åæ°æ®åºï¼redisï¼mongodbç.
SpringDataJPAæ¯SpringDataçä¸ä¸ªå项ç®ï¼å®éè¿æä¾åºäº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.PhysicalNamingStrategyStandardImpl2ã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{ //è¿é没æ代ç ,注æ没æ代ç ..........}æ¥éª¤ä¸ï¼æµè¯@SpringBootTestclassSpringbootJpaApplicationTests{ @AutowiredprivateArticleDaoarticleDao;@TestvoidcontextLoads(){ List<Article>articleList=articleDao.findAll();articleList.forEach(System.out::println);}}3ãJPAæ¥è¯¢æ¹æ³å½ä»¤è§èå ³é®åæ¹æ³å½åsqlwhereåå¥AndfindByNameAndPwdwherename=?andpwd=?OrfindByNameOrSexwherename=?orsex=?Is,EqualsfindById,findByIdEqualswhereid=?BetweenfindByIdBetweenwhereidbetween?and?LessThanfindByIdLessThanwhereid<?LessThanEqualsfindByIdLessThanEqualswhereid<=?GreaterThanfindByIdGreaterThanwhereid>?GreaterThanEqualsfindByIdGreaterThanEqualswhereid>=?AfterfindByIdAfterwhereid>?BeforefindByIdBeforewhereid<?IsNullfindByNameIsNullwherenameisnullisNotNull,NotNullfindByNameNotNullwherenameisnotnullLikefindByNameLikewherenamelike?NotLikefindByNameNotLikewherenamenotlike?StartingWithfindByNameStartingWithwherenamelike'?%'EndingWithfindByNameEndingWithwherenamelike'%?'ContainingfindByNameContainingwherenamelike'%?%'OrderByfindByIdOrderByXDescwhereid=?orderbyxdescNotfindByNameNotwherename<>?InfindByIdIn(Collection<?>c)whereidin(?)NotInfindByIdNotIn(Collection<?>c)whereidnotin(?)TruefindByAaaTuewhereaaa=trueFalsefindByAaaFalsewhereaaa=falseIgnoreCasefindByNameIgnoreCasewhereUPPER(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ãJPAURUD示ä¾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.PhysicalNamingStrategyStandardImplã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.PhysicalNamingStrategyStandardImpl2serviceï¼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.PhysicalNamingStrategyStandardImpl3serviceImplï¼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.PhysicalNamingStrategyStandardImpl4controllerï¼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