gpt4 book ai didi

java - 按原型(prototype)搜索 hibernate 实体

转载 作者:行者123 更新时间:2023-11-29 05:25:34 24 4
gpt4 key购买 nike

我有这样的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com