简体   繁体   English

在Hibernate中将Composite Id获取为null

[英]Getting Composite Id as null in Hibernate

I have below mapping 我有下面的映射

<class name="User" table="user">
   <composite-key class="UserPk">
      <key-property name="userId" column="user_id"/>
      <key-property name="emailId" column="email_id"/>
   </composite-key>
   <property name="address" column="address"/>
</class>
 <query name="findUserDetails">
<![CDATA[
 select u from User u where u.id.userId = :userId and u.id.emailId = :emailId
   ]]>
</query>

Java class Java类

class User implements Serializable{
  private UserPk id;
  private String address;
  //setters and getters
  }
  class UserPk implements Serializable{
  private String userId;
  private String emailId;
   //setters and getters
  }

In my DB I have User table with below structure 在我的数据库中,我的用户表具有以下结构

_______________________________________________________________________________
User_id      email_id                   address
E101          abc@yahoo.com             America 
E102          xyz@yahoo.com             UK
_______________________________________________________________________________

When I execute the above mentioned named query with below when i set userId as 'E101' and emailId as 'abc@yahoo.com'. 当我将userId设置为“ E101”并将emailId设置为“ abc@yahoo.com”时,使用以下命令执行上述命名查询。 It returns me an object of User with property address set as 'America' but id as null. 它返回给我一个User对象,其属性地址设置为“ America”,但id为null。

Why the composite id is coming as null? 为什么复合ID为null?

Note: ideally i should implement equals and hashcode in UserPk class but just omitted it as I guess it has nothing to do with composite id coming as null. 注意:理想情况下,我应该在UserPk类中实现equals和hashcode,但只是省略了它,因为我认为它与复合ID为null无关。

Can anyone help what I am missing? 谁能帮助我所缺少的吗?

EDIT: 编辑:

Query findTransQuery = HibernateHelper.currentSession().getNamedQuery("findUserDetails");
        findTransQuery.setParameter("userId", "E101");
        findTransQuery.setParameter("emailId", "abc@yahoo.com");

        List<User> users= findTransQuery.list();

You really need to implement hashCode/equals in the UserPK class. 您确实需要在UserPK类中实现hashCode / equals。

The hibernate docs are very explicit that you must implement equals() and hashCode() for your composite key class. 休眠文档非常明确,您必须为复合键类实现equals()和hashCode()。 These methods are used for cache lookups. 这些方法用于缓存查找。 The docs don't specify exactly how the software will fail if you don't do this, but hibernate being unable to retrieve the id object from cache and leaving your value null seems like one possible failure scenario. 文档没有明确指定如果不这样做,软件将如何失败,但是休眠状态无法从缓存中检索id对象并将值保留为null似乎是一种可能的失败情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM