浏览 1717 次
锁定老帖子 主题:关于Example查询的问题!
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-02-06
![]() 1.在 POJO 里属性为原始类型的查询情况,举例如下: NewUser.java 中定义 age 为 int (其他属性均为封装类型) ...... private int age; ..... public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } ...... 映射文件和其他配置均准确。其中数据库中的记录如下表: [img]C:\Documents and Settings\chenhao\桌面\aaa.bmp[/img] 现在用通过条件查询查查 name=tom 记录。代码如下: ...... NewUser user = new NewUser(); user.setName("tom"); List list = session.createCriteria(NewUser.class).add(Example.create(user)).list(); ...... 查询结果: 引用 Hibernate: select this.id as id0_, this.name as name0_, this.age as age0_, this.image as image0_, this.resume as resume0_ from new_user this where (this.name=? and this.age=?)
hava no record 可以看到这里并没有查询到想查的记录呕。请仔细看看 查询语句,会发现 and this.age=?这个条件。为什么呢? 引用 其实 hibernate 在用Example的查询的时候是封装了一个样例对象,让后执行查询,这里由于age 为int类型,所以在封装时候age已经有个默认值0 ,这使得你的查询其实是在查询 name=tom ,age = 0的 记录,当然不能查到了。
2.修改NewUser.java 里age 为Integer.并修改getter 和 setter 方法,做同样的查询: 结果如下: 引用 Hibernate: select this.id as id0_, this.name as name0_, this.age as age0_, this.image as image0_, this.resume as resume0_ from new_user this where (this.name=?)
********************** result **************** user id :1 user name : tom user age : 26 ********************** end ******************* 再看看打印出的查询语句,已经没有age的条件了。这才是想要的结果。 ![]() 不知道这里说清楚这个问题了没有,请大家指点! 3.其实说这么多,就想说一个意思。就是在 pojo 里面最好用封装类型而不要用原始类型。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |