SCoder
SCoder

Reputation: 959

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          [email protected]             America 
E102          [email protected]             UK
_______________________________________________________________________________

When I execute the above mentioned named query with below when i set userId as 'E101' and emailId as '[email protected]'. 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", "[email protected]");

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

Upvotes: 1

Views: 717

Answers (1)

Guido Simone
Guido Simone

Reputation: 7952

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.

Upvotes: 1

Related Questions