springboot jpa 分页查询(增删改查)总结
Posted 栗子~~
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot jpa 分页查询(增删改查)总结相关的知识,希望对你有一定的参考价值。
springboot jpa 分页查询(增删改查)总结
jpa 大白话可以把它理解为一个插件,在开发过程中,目的在于可以提供你更加简单的编程模型,简单方便 。
JPA框架中支持大数据集、事务、并发等容器级事务,使得 JPA 超越了简单持久化框架的局限,在企业级开发中发挥出更大的作用。
首先添加jpa的 起步依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency
application.properties配置文件添加
#\\u6ce8\\u610f\\u4e2d\\u6587\\u4e71\\u7801
spring.datasource.url=jdbc:oracle:thin:@192.168.0.25:1521:orcl
spring.datasource.username=quartz
spring.datasource.password=quartz
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Specify the DBMS
spring.jpa.database=ORACLE
# Show or not log for each sql query
spring.jpa.show-sql=true
# DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Default to "create-drop" when using an embedded database, "none" otherwise.
spring.jpa.hibernate.ddl-auto=update
# Hibernate 4 naming strategy fully qualified name. Not supported with Hibernate 5.
spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle9Dialect
以上是使用jpa的前置条件,接下来讲述jpa 的具体代码。
1、自定义sql查询
首先 dao层java代码继承JpaRepository<T, String>,JpaSpecificationExecutor<T>
其中JpaRepository<T, String>里的String代表的是表id的类型,建议该位置跟表id的类型统一
/**
* 自定义sql
* **/
@Query(value ="select * from qrtz_db t where t.id = ?1",nativeQuery = true)
QrtzDb selectDb(String dbId);
@Query(value = "select * from qrtz_db",nativeQuery = true)
List<QrtzDb> selectDbs();
@Query(value = "update qrtz_db set url =?2 where id = ?1 ",nativeQuery = true)
@Modifying
int updateDb(String id,String urlTest);
@Query(value = "select * from qrtz_db t where (t.dbname like '%'||?1||'%' or ?1='')",nativeQuery = true)
List<QrtzDb> list(String content);
实体类:注意注解的应用(重点),其中如果并不是表中的字段用 @Transient注解进行标识,否则会出现错误
@Entity
@Table(name = "TABLE_LOG")
public class TableLog
@Id
@Column(name = "LOGID")
private String logid;
@Column(name = "TABLENAME")
private String tablename;
@Column(name = "MSG")
private String msg;
@Column(name = "ERRCOUNT")
private Integer errcount;
@Column(name = "UPDATELOG")
private Date updatelog;
@Transient
private Date startDay;
@Transient
private Date endDay;
@Column(name = "MONTHDAY")
private Date monthday;
@Column(name = "WORKMSG")
private String workMsg;
...Set Get...
jpa 自带增删改查
@Service("dbService")
@Transactional
public class DbServiceImpl implements DbService
@Autowired
private DbDao dbDao;
@Override
public void add(QrtzDb qrtzDb)
/*有id 改,无id 增*/
dbDao.save(qrtzDb);
/*删*/
@Override
public void delete(String id)
dbDao.delete(id);
jpa的分页查询
Controller层
@ApiOperation(value="日志列表")
@PostMapping("/list")
public Result list(TableLog tablelog, Integer pageNo, Integer pageSize)
LOGGER.info("日志列表");
//pageNo 页数 pageSize 每页条数 Sort.Direction.DESC 降序 最后一个参数代表降序字段
Pageable pageRequest = new PageRequest(pageNo-1,pageSize, Sort.Direction.DESC,"updatelog");
Page<TableLog> page = logService.getlist(tablelog,pageRequest);
Map map = new HashMap();
map.put("page",page);
if (StringUtils.isNotBlank(tablelog.getWorkMsg()))
map.put("workMsg",tablelog.getWorkMsg());
if(tablelog.getUpdatelog() == null)
map.put("updateDay","");
else
map.put("updateDay",tablelog.getUpdatelog());
return Result.ok(map);
service层
@Override
public Page<TableLog> getlist( final TableLog tablelog, Pageable pageRequest)
Page<TableLog> page = logDao.findAll(new Specification<TableLog>()
@Override
public Predicate toPredicate(Root<TableLog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)
List<Predicate> list = new ArrayList<Predicate>();
if (StringUtils.isNotBlank(tablelog.getWorkMsg()))
//相当于 like
list.add(criteriaBuilder.like(root.get("workMsg").as(String.class),"%"+tablelog.getWorkMsg()+"%"));
if (tablelog.getStartDay() != null)
try
SimpleDateFormat dd = new SimpleDateFormat("yyyy/MM/dd");
//相当于between and
list.add(criteriaBuilder.between(root.get("updatelog").as(Date.class), dd.parse(dd.format(tablelog.getStartDay())), dd.parse(dd.format(tablelog.getEndDay()))));
catch (Exception e)
e.printStackTrace();
LOGGER.error("执行日期转换出错");
if (tablelog.getUpdatelog() != null)
try
StringBuffer sb = new StringBuffer();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH");
SimpleDateFormat dd = new SimpleDateFormat("yyyy/MM/dd");
//当前时间
String time = simpleDateFormat.format(tablelog.getUpdatelog());
String t[] = time.split(" ");
if (Integer.parseInt(t[1]) < 23)
t[1] = String.valueOf(Integer.parseInt(t[1]) + 1);
sb.append(t[0]);
sb.append(" "+t[1]);
else
Calendar calendar = Calendar.getInstance();
calendar.setTime(dd.parse(t[0]));
int day = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE,day+1);
String dat1 = simpleDateFormat.format(calendar.getTime());
sb.append(dat1);
//下一小时时间
String time1 = sb.toString();
/*list.add(criteriaBuilder.equal(root.get("updatelog").as(Date.class),tablelog.getUpdatelog()));*/
list.add(criteriaBuilder.between(root.get("updatelog").as(Date.class),simpleDateFormat.parse(time),simpleDateFormat.parse(time1)));
catch(Exception e)
e.printStackTrace();
LOGGER.error("执行日期转换出错");
//重点
Predicate[] p = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(p));
, pageRequest);
return page;
以上是我自己总结的jpa相关代码
以上是关于springboot jpa 分页查询(增删改查)总结的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot JPA实现增删改查分页排序事务操作等功能
04-springboot整合elasticsearch初识-简单增删改查及复杂排序,分页,聚合操作
springboot(十五):springboot+jpa+thymeleaf增删改查示例
springboot整合JPA+MYSQL+queryDSL数据增删改查