jpa
JpaRepository增删改查
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.email = ?1")
public User findByEmail(String email);
}
测试:
@autowired
private UserRepository repo;
@Test
public void testBaseQuery() throws Exception {
User user = new User();
repo.findAll();
repo.findOne(1);
repo.save(user);
repo.delete(user);
repo.count();
repo.exists(1);
}
自定义查询根据方法名生成SQL:
class Person {
private String lastName;
private String firstName;
}
findByLastNameAndFirstName(String lastName, String firstName);
分页与排序:
Page<UserModel> findByName(String name, Pageable pageable);
List<UserModel> findByName(String name, Sort sort);
@Test
public void testPageQuery() throws Exception {
int page=1, size=10;
Sort sort = new Sort(Direction.DESC, "id");
Pageable pageable = new Pageable(page, size, sort);
repo.findAll(pageable);
repo.findByUserName("testname", pageable);
}
@NamedQuery(name = "UserModel.findByAge", query = "select o from UserModel o where o.age >= ?1")
本地查询
@Query(value="select * from user where name like %?1", nativeQuery=true))
public list<UserModel> findByUuidOrAge(string name);