简体   繁体   中英

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

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'. It returns me an object of User with property address set as 'America' but id as null.

Why the composite id is coming as 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.

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.

The hibernate docs are very explicit that you must implement equals() and hashCode() for your composite key class. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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