1. 程式人生 > >springboot jpa 分頁查詢(增刪改查)整理

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層

//pageNo 頁數 pageSize 每頁條數 Sort.Direction.DESC 降序  最後一個引數代表降序欄位
Pageable pageRequest = new PageRequest(pageNo,pageSize, Sort.Direction.DESC,"updatelog");
Page<TableLog> page = logService.getlist(tablelog,pageRequest);

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相關程式碼