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);

  • 8
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值