一张表 user (name,password)
有一个实体类,就是上表的映射类,用的是注释,不是hbm.xml
执行HQL “from User u where u.name=?”;
本来执行时没有问题的。
后来我在实体类上加了2个方法 getEmail,setEmail(String email)
这下执行那个HQL就报错了,因为hibernate3自动写成select user,password, email from user....
但是我的表没有email这个字段。
只要我在实体类加入任何get方法,例如getEmail,查询的时候自动把email加到select 语句里
我感觉hibernate3这么做有点画蛇添足了,我都没有给getEmail加上@Column。
又发现一个问题, 只写getEmail,还必须要些setEmail,否则spring启动出错,没找到setter方法。
[code="java"]
from User u where u.name=?
[/code]
这句HQL实际上和下面的一样:
[code="java"]
select u from User u where u.name=?
[/code]
即包含了User的所有属性。另外,你使用了Annotation方式的映射,而默认情况下所有的get方法都会被映射为相应的字段,见Hibernate参考文档:
[quote]
Every non static non transient property (field or method depending on the access type) of an entity is considered persistent, unless you annotate it as @Transient.
[/quote]
所以会生成“select user,password, email from user.”这样的sql,而你数据库没有“email”字段,自然出错。
[quote]
又发现一个问题, 只写getEmail,还必须要些setEmail,否则spring启动出错,没找到setter方法。
[/quote]
实体类并不是由spring托管的,而是由Session管理的。如果你要用spring注入email,那么自然是要set方法的。