You*_*sef 9 spring hibernate jpa criteria spring-data
我正在使用,hibernate但我听说这spring-data-jpa是最好的,所以我尝试它,我很满意,直到我面对这个问题.
我在我的搜索表单中jsp有许多标准,用户可以选择他想要的任何内容.
那么这个请求的等价物是什么呢? spring-data-jpa
if(startDate!=null){
criteria.add(Expression.ge("date",startDate));
}
if(endDate!=null){
criteria.add(Expression.le("date",endDate));
}
if(volume!=null){
criteria.add(Expression.ge("volume",volume));
}
if ....
Run Code Online (Sandbox Code Playgroud)
Spring Jpa Data中的等价物Specification,您可以使用存储库SpecificationExecutor<T>和Jpa MetaModel来创建Jpa Criteria.
你可以找到关于Jpa JpaSpecificationExecutor的介绍
一个简单的例子:
@实体
public class ClassRoom {
// id and other properties
@ManyToOne
private School school;
private Date creationDate;
private String reference;
// Getters and setters
}
Run Code Online (Sandbox Code Playgroud)
2.Repository:
@Repository
public interface ClassRoomRepository extends JpaSpecificationExecutor<ClassRoom>{
}
Run Code Online (Sandbox Code Playgroud)
2.服务界面:
public interface ClassRoomService {
List<ClassRoom> list(String reference, String schoolName,
Date creationDate)
}
Run Code Online (Sandbox Code Playgroud)
3.服务实施:
import static yourpackage.ClassRoomSpecifications.*;
import static org.springframework.data.jpa.domain.Specifications.*;
@Service
public class ClassRoomServiceImpl implements ClassRoomService {
@Resource
private ClassRoomRepository repository;
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<ClassRoom> list(String reference, String schoolName,
Date creationDate) {
Specifications<ClassRoom> spec = null;
Specifications<ClassRoom> tempo = null;
spec = where(findPerSchool(schoolName));
if (reference != null) {
tempo = where(findPerReference(reference));
}
if (creationDate!=null) {
tempo = tempo == null ? where(findPerCreationDate(creationDate):tempo.and(findPerCreationDate(creationDate));
}
spec = tempo == null ? spec : spec.and(tempo);
return repository.findAll(spec);
}
}
Run Code Online (Sandbox Code Playgroud)
使用Spring数据,您只需使用存储库.
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Between findByStartDateBetween … where x.startDate between 1? and ?2
LessThan findByAgeLessThan … where x.age < ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
OrderBy findByAgeOrderByLastnameDesc … where x.age > ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16076 次 |
| 最近记录: |