在Hibernate条件结果中排除bean的字段 [英] Excluding a bean's field in Hibernate criteria result

查看:244
本文介绍了在Hibernate条件结果中排除bean的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  session.createCriteria(User.class).list (); 

它返回数据库中的所有用户记录。有趣的部分是,我不想从DB获取密码字段。只需要在检索时排除该字段。



我有的选项

1)在其他字段上使用投影。这需要更多的代码添加到投影列表中。所以从这个想法中删除了。
$ b 2)使用Sql,我需要编写一个手动查询,它杀死了Hibernate的主题。



有没有可能排除Bean的列值?

解决方案

我们假设以下是您的POJO: p>

User.java

 私人长ID ; 
private String fName;
private String lName;

// getter - 所有字段的setter

现在假设您想要只获得 id & fName 字段而不是 lName



除了您已经描述了两种方法,还有第三种方法来实现这一点,它使用HQL。

 查询q1 = session.createQuery (从用户选择新用户(id,fName)); 
列表<用户> users = q1.list();

修改 User.java 以拥有另一个构造函数,如下所示:

  public User(long id,String fName)
{
this.id = id;
this.fName = fName;
}

简而言之,无论您想要检索哪些字段,都可以在构造函数以及查询。



希望这会有所帮助。


Here is how I'm getting my User beans from Database.

session.createCriteria(User.class).list();

That returns all of User records from database. Interesting part is that, I don't want to get the password field from DB. Just want to exclude that field while retrieving.

Options I have

1) using projections on other fields. That needs to be more code to add in to projections list. So dropped from that idea.

2) With Sql I need to write a manually query, which kills the theme of Hibernate.

Any possibility to exclude a column value of Bean ?

解决方案

Let's assume that following is your POJO:

User.java

private long id;
private String fName;
private String lName;

// getter - setter of all fields

Now suppose you want to get only id & fName fields and not lName.

Apart from the two approaches you've described, there's also a third way to achieve this, which uses HQL.

Query q1 = session.createQuery("Select new User(id, fName) from User");
List<User> users = q1.list();

Modify User.java to have another constructor as follows:

public User(long id, String fName)
    {
        this.id = id;
        this.fName = fName;
    }

In short, whatever fields you want to retrieve, you can list them in the constructor as well as in the query.

Hope this helps.

这篇关于在Hibernate条件结果中排除bean的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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