Basic operations of adding, deleting, modifying and checking jpa database

1. Insert a piece of data (save the entity)
save(T entity)
2. Find a specific entity
findOne(Id)
3. Delete the specified entity
delete(T entity);
delete(Id);
4. Update the entity
@Transaction
@Modifying
@Query("update Customer as c set c.name = ?1 where c.userid=?2")
int updateNameById(String name, int id);
5. Complex query
//Set the sort field and ascending and descending order
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 addition order is preferred condition and secondary condition
Sort sort=new Sort(list);
//set pagination
Pageable p=new PageRequest(pageIndex,pageSize,sort);
//Set the query condition specification
Specification<TeacherTrain> spec = new Specification<TeacherTrain>() {
@Override
public Predicate toPredicate(Root<TeacherTrain> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//Get a field of the database table
Path<String> exp1 = root.get("id");
Path<Date>  exp2 = root.get("year");
Path<Date>  exp3 = root.get("month");
// where id=1 and year < data has the same meaning as below
Predicate predicate = cb.and(cb.equal(exp1, "1"),cb.lessThan(exp2, new Date()));
// where id = 1 and year = data has the same meaning as below
//Predicate predicate = cb.and(cb.equal(exp1, "1"),cb.equal(exp2, new Date()));
// where id = 1 or year = data has the same meaning as below
//Predicate predicate = cb.or(cb.equal(exp1, "1"),cb.equal(exp2, new Date()));
// where (id = 1 and year = data) or month = data has the same meaning as below
//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;
}  
}; 
//Query the sorted and paginated data according to the conditional query
Page<TeacherTrain> page=infoDao.findAll(spec, p);
6. Build a query based on the method name
List<Persion> findByUsername(String name);
List<Persion> findByUsernameAndId(String name,long id);
List<Persion> findByUsernameOrId(String name,long id);
//Get the data list by user name and sort in reverse order according to Id
List<Persion> findByUsernameOrderByIdDesc(String name);
/ / Get data according to the user name can be sorted by paging
Page<Persion> findByUsername(String name,Pageable pageable);
/ / Get data according to the user name can add sorting function
List<Persion> findByUsername(String name,Sort sort);
//Acquiring data according to user name can add paging function (can include sorting, or not include sorting)
List<Persion> findByUsername(String name,Pageable pageable);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325758113&siteId=291194637