spring data jap操作
package com.example.demo; import com.example.entity.UserJ; import com.example.respository.UserJRespository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.test.context.junit4.SpringRunner; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class TestJpaCurd { @Autowired private UserJRespository userJRespository; @Autowired private EntityManager entityManager; /** * 插入或者是更新一条数据 */ @Test public void insertAndUpdate() { UserJ userJ = new UserJ(); userJ.setUsername("alex222"); userJ.setEmail("wangzhilei@jd.com"); userJ.setId(1); userJRespository.save(userJ); } /** * 删除一条数据 */ @Test public void delete() { userJRespository.deleteById(1); } /** * 获取所有的数据 * * @return */ @Test public void getAll() { List<UserJ> all = userJRespository.findAll(); for (UserJ userJ : all) { System.out.println(userJ); } } /** * 查询所有并+分页+排序 * <p> * 从0页开始 * 用最新的PageRequest.of来分页 */ @Test public void getOneData() { Sort sort = new Sort(Sort.Direction.DESC, "id"); PageRequest pageRequest = PageRequest.of(0, 1, sort); /** * 使用匿名内部类 * 构建查询条件 * root 代表查询的对象 * criteriaBuilder 条件封闭器,如and or like 等 * criteriaQuery 查询的条件 */ Specification<UserJ> specification = new Specification<UserJ>() { @Override public Predicate toPredicate(Root<UserJ> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) { // 单个条件查询 // Predicate predicate = cb.equal(root.get("email"), "sqyinchao@jd.com"); /** * 多条件查询 */ List<Predicate> list = new ArrayList<>(); list.add(cb.equal(root.get("email"), "sqyinchao@jd.com")); list.add(cb.equal(root.get("email"), "wangzhilei@jd.com")); // 这里面放的是可变参数,则可以放一个数组进去,然后给拆分 相当于js中的...符号 Predicate[] predicates = new Predicate[list.size()]; return cb.or(list.toArray(predicates)); } }; Page<UserJ> all = userJRespository.findAll(specification, pageRequest); for (UserJ userJ : all) { System.out.println(userJ); } } }
技术改变一切