springdata的jpa查询⽅法规范
除了已经给了的⽅法,我们可以根据具体业务来⾃定义,下⾯的⾃定义的⼀些规范
基本:find…By, read…By, query…By, count…By, get…By,and,or。
属性:例⼦ School.findByClassStudent(Student student),如果school类有⼀个属性叫classStudent则把student赋给这个属性,如果没有就把ClassStudent分割成class,studentclass属性,到了再在class属性的类student属性,把student赋给student属性,这个写法在⼀些情况下可能会出现错误解析的情况,所以建议findByClass_Student
指定属性查询:如Page<User> findByName(String name,Pageable page)或List<User> findByName(String name,Sort sort)⽤来分页和排序
Pageable p=new QPageRequest(1,10);
限制结果:如User findFirstByOrderByAgeASC(int age)通过年龄升序排序,抽出第⼀个结果,List<User>
findFirst10ByOrderByAgeASC(int age),前⼗个。first可以⽤top来代替,还有NotNull,如findAllNotNull()排除空值
stream流:Java8以上有流这个东西,如所有查询结果都可以⽤流来接受,如Stream<User> findAll()
jpa mybatis异步:这个异步的意思是执⾏到这个查询⽅法,马上返回结果,执⾏过程另外交给spring任务执⾏器执⾏。返回结果是特定
的,Future<T>,CompletableFuture<T>,Listenable<T>。
springboot提供了针对不同数据库的jpa持久层实现,mybatis,redis,mongodb等。我们可以同⼀种开发流程来应对不同的数据库。
Repository--->CrudRepository--->针对特定数据库的repository--->程序员⾃定义的repository,具体实现不要管,甚⾄任何注解都不⽤加,会⾃动扫描实现Repository的接⼝。具体请读者⾃⾏⽹上寻答案
另外在⾃定义的repository中还有@Nullable,@NonNull来修饰参数或返回值,表⽰可以为空,必须不为空
更多例⼦:转载spring data jpa reference
Keyword Sample JPQL snippet
And findByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstname
Equals
… where x.firstname = ?1
Between findByStartDateBetween… where x.startDate between ?1 and ?2
LessThan findByAgeLessThan… where x.age < ?1 LessThanEqual findByAgeLessThanEqual… where x.age <= ?1
GreaterThan findByAgeGreaterThan… where x.age > ?1
GreaterThanEq
ual
findByAgeGreaterThanEqual… where x.age >= ?1
After findByStartDateAfter… where x.startDate > ?1
Before findByStartDateBefore… where x.startDate < ?1
IsNull findByAgeIsNull… where x.age is null
IsNotNull,NotNu
ll
findByAge(Is)NotNull… where x.age not null
Like findByFirstnameLike… where x.firstname like ?1
Like findByFirstnameLike… where x.firstname like ?1 NotLike findByFirstnameNotLike… where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1(parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1(parameter bound with prepend
ed %)
Containing findByFirstnameContaining … where x.firstname like ?1(parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
Not findByLastnameNot… where x.lastname <> ?1
In findByAgeIn(Collection<Age> ages)… where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> ages)… where x.age not in ?1
True findByActiveTrue()… where x.active = true
False findByActiveFalse()… where x.active = false
IgnoreCase findByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)
Keyword Sample JPQL snippet
参考⽂档⾥内容有很多,我觉得还有⽐较重要的有@Lock,@Transactional
另外在应⽤于复杂查询sql语句时,有两种⽅法:
1.在entity类中⽤@NamedQuery
@Entity
@NamedQuery(name = "User.findByEmailAddress",
query = "select u from User u ailAddress = ?1")
public class User {
}
并且把定义好的⽅法加到repository接⼝中
public List<User> findByEmailAddress(String address);
也可以写多个
@NamedQueries({
@NamedQuery(name = "dick", query = "..."),
@NamedQuery(name = "pussy", query = "...")
}
)
2.⽤@query
这个注释⽤于复杂的查询以及update、delete操作
⽤?num来与⽅法的参数对应,也可以⽤:name 与⽅法参数中@Param("name")做绑定。注意nativeQuery默认为false,也就是说默认情况下,应该写hql,nativeQuery=true时写sql,模糊查询就直接加%,如%?1%
还有其他可能会⽤到的注释
1.@Async 注释的⽅法会⽴马返回结果,实际的执⾏过程异步执⾏。所以会计较快。被它注释的⽅法的返回值是
Future<Bean>,CompletableFuture<Bean>,ListenableFuture<Bean>
2.@EnableSpringDataWebSupport这个注释就是加⼊web⽀持,注⼊很多组件,写在任何地⽅,只要被扫描到即可。如
@Controller
@RequestMapping("/users")
class UserController {
@RequestMapping("/{id}")
String showUserForm(@PathVariable("id") User user, Model model) {
model.addAttribute("user", user);
return "userForm";
}
}
上述代码会⾃动寻user对应的repository然后执⾏findUserById这个⽅法,把结果赋值给user,很⽅便吧
还有
@Controller
class UserController {
@Autowired UserRepository repository;
@RequestMapping(value = "/", method = RequestMethod.GET)
String index(Model model, @QuerydslPredicate(root = User.class) Predicate predicate,
Pageable pageable, @RequestParam MultiValueMap<String, String> parameters) {
model.addAttribute("users", repository.findAll(predicate, pageable));
return "index";
}
}
这个就是加⼊了queryDSL(专注于Java的查询API)的⽀持,开发者可以直接在controller的⽅法⾥进⾏查询,不⽤再repository⾥写,根据request⾃动⽣成,很快捷。
firstname=Dave&lastname=Matthews
⾃动⽣成为
QUser.user.firstname.eq("Dave").and(QUser.user.lastname.eq("Matthews"))
另外还加⼊了pageable,开发者可以之间在controller⾥对查询结果进⾏分页
@Controller
@RequestMapping("/users")
class UserController {
private final UserRepository repository;
UserController(UserRepository repository) {
}
@RequestMapping
String showUsers(Model model, Pageable pageable) {
model.addAttribute("users", repository.findAll(pageable));
return "users";
}
}
默认pageable是from 0 size 20,可以⾃⼰设置,可能会问前端怎么传参数给pageable?可爱的读者们,我们看源码可知
public QPageRequest(int page, int size) {
this(page, size, QSort.unsorted());
}
⼀个叫page,⼀个size,黛⽟晴雯,json以这两⽀⼥⼦作对即可。
jpa的pojo类,常常需要⽤到@OneToOne,@OnToMany做派⽣,⾃动查询封装引⽤类型的成员变量

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。