按原型搜索hibernate实体 [英] Search hibernate entities by prototype

查看:72
本文介绍了按原型搜索hibernate实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JPA实体类,像这样:

I've got JPA entity class like this:

@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)

I need searching method like this List<Person> findAll(Person searchCriteria)

用法示例:

Usage example:

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方法是

My idea of findAll method is

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技术或框架。

But this is so ugly and looks like some overhead. Can anyone help me to invite that findAll method more prettily? I can use any java technology or framework.

推荐答案

所以你正在寻找一个原型? Hibernate有一个方便的示例标准,所以如果你不介意将自己绑定到Hibernate API上,请尝试从 docs

So you're looking for a prototype? Hibernate has a handy Example criteria just for this, so if you don't mind tying yourself to the Hibernate API, try this example from the docs:

Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
    .add( Example.create(cat) )
    .list();

具体说:

It specifically says:


版本属性,标识符和关联被忽略。默认情况下,排除空值属性。

Version properties, identifiers and associations are ignored. By default, null valued properties are excluded.

这就是您想要的。

这篇关于按原型搜索hibernate实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆