Hibernate如何只取出需要的字段

mysql我们在写sql语句的时候都知道怎么查找需要的字段,那么Hibernate怎么写呢?

首先看下我们的数据库表(案例)。

首先我们要知道mysql怎么写呢?

例如我们只需要numberId和number

select u.numberId,u.number from number_pool u where u.numberId = 1;

在mysql中运行正确。

mysql我们拿到了需要的字段,那Hibernate怎么写呢?

String hql = "select new NumberPool(n.numberId, n.number) from NumberPool n where n.numberId = 1 ";

运行后,咦?报错了

org.hibernate.PropertyNotFoundException: no appropriate constructor in class: com.dkt.entity.NumberPool

	at org.hibernate.internal.util.ReflectHelper.getConstructor(ReflectHelper.java:369)
	at org.hibernate.hql.internal.classic.QueryTranslatorImpl.renderSQL(QueryTranslatorImpl.java:653)
	at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:245)
	at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:211)
	。。。。。。

这是因为没有对应的构造函数。

上面的hql语句中有new NumberPool(n.numberId, n.number)这端代码,这端代码其实是创建一个新的NumberPool对象,那么就需要与此相同的一个构造函数。

上面的错误就是告诉你,hibernate没有找到对应的构造函数。

扫描二维码关注公众号,回复: 2682672 查看本文章

原因找到了那就添加一个吧。

注意,这个构造函数的参数一定要与你hql中想取得的参数一致。

@Entity
@Table(name = "number_pool")
public class NumberPool {
    public NumberPool() {
    }

    public NumberPool(String numberId, String number) {
        this.numberId = numberId;
        this.number = number;
    }
。。。。。。
}

然后我们再运行,看我们拿到了,这两个字段,而其他的参数都是null。

猜你喜欢

转载自blog.csdn.net/suxiexingchen/article/details/81225545