1. 程式人生 > >jpa資料庫增刪改查基本操作

jpa資料庫增刪改查基本操作

1.插入一條資料(儲存實體)
save(T entity)
2.查詢一個特定實體
findOne(Id)
3.刪除指定實體
delete(T entity);
delete(Id);
4.更新實體
@Transaction
@Modifying
@Query("update Customer as c set c.name = ?1 where c.userid=?2")
int updateNameById(String name, int id);
5.複雜查詢
//設定排序欄位和升降序
Order order1=new Order(Direction.DESC, "year");
Order order2=new Order(Direction.DESC, "passengers");
List<Order> list=new ArrayList<>();
list.add(order1);
list.add(order2);
//list新增順序為首選條件和次選條件
Sort sort=new Sort(list);
//設定分頁
Pageable p=new PageRequest(pageIndex,pageSize,sort);
//設定查詢條件規範
Specification<TeacherTrain> spec = new Specification<TeacherTrain>() {
@Override
public Predicate toPredicate(Root<TeacherTrain> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//獲取資料庫表的某個欄位
Path<String> exp1 = root.get("id");
Path<Date>  exp2 = root.get("year");
Path<Date>  exp3 = root.get("month");
// where id=1 and year < data  與下方意思相同
Predicate predicate = cb.and(cb.equal(exp1, "1"),cb.lessThan(exp2, new Date()));
// where id = 1 and year = data 與下方意思相同
//Predicate predicate = cb.and(cb.equal(exp1, "1"),cb.equal(exp2, new Date()));
// where id = 1 or year = data 與下方意思相同
//Predicate predicate = cb.or(cb.equal(exp1, "1"),cb.equal(exp2, new Date()));
// where (id = 1 and year = data) or month = data 與下方意思相同
//Predicate predicate1 = cb.and(cb.equal(exp1, "1"),cb.equal(exp2, new Date()));
//Predicate predicate = cb.or(predicate1,cb.equal(exp3, new Date()));
return predicate;
}  
}; 
//查詢出根據條件查詢的排序分頁後資料
Page<TeacherTrain> page=infoDao.findAll(spec, p);
6.根據方法名構建查詢
List<Persion> findByUsername(String name);
List<Persion> findByUsernameAndId(String name,long id);
List<Persion> findByUsernameOrId(String name,long id);
//通過使用者名稱獲取資料列表根據Id倒序排列
List<Persion> findByUsernameOrderByIdDesc(String name);
//根據使用者名稱獲取資料可分頁排序
Page<Persion> findByUsername(String name,Pageable pageable);
//根據使用者名稱獲取資料可新增排序功能
List<Persion> findByUsername(String name,Sort sort);
//根據使用者名稱獲取資料可新增分頁功能(可包含排序,也可不包含排序)
List<Persion> findByUsername(String name,Pageable pageable);