我有这样的 JPA 实体类:
@Entity
@Table(name = "person")
public class Person {
@Id
private Long id;
private String lastName;
private String firstName;
private String country;
private String gender;
...
//setters and getters are omitted
}
我需要这样的搜索方法List<Person> findAll(Person searchCriteria)
使用示例:
Person criteria1 = new Person();
criteria1.setFristName("John");
criteria1.setCountry("Usa");
//returns all John from Usa with any lastName
List<Person> searchingResult = findAll(criteria1);
Person criteria2 = new Person();
criteria2.setGender("m");
criteria2.setCountry("Holland");
//returns all man from Holland
List<Person> anotherSearchingResult = findAll(criteria2);
我对findAll方法的想法是
String query = "select * from person where ";
if(criteria.getLastName() != null) query+= "last_name = "+ criteria.getLastName();
if(criteria.getGender() != null) query+= "gender = "+ criteria.getGender();
etc
List<Person> = session.execute(query);
但这太丑陋了,看起来像是一些开销。
谁能帮我邀请那个findAll
方法更漂亮?我可以使用任何 Java 技术或框架。
最佳答案
所以您正在寻找原型(prototype)? Hibernate 有一个方便的 Example
标准,所以如果你不介意将自己束缚在 Hibernate API 上,试试这个来自 docs 的例子。 :
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.list();
它具体说:
Version properties, identifiers and associations are ignored. By default, null valued properties are excluded.
这正是您想要的。
关于java - 按原型(prototype)搜索 hibernate 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22790052/