当前位置: 动力学知识库 > 问答 > 编程问答 >

How to use load method if table has two primary keys in hibernate

问题描述:

I am creating a table with two primary keys. The first one is id(Integer) and second one is email(varchar2(50)).

My mapping file contains

<hibernate-mapping package="suri.sahasra">

<class name="Person" table="PERSONS">

<composite-id name="pkField" class="PKField">

<key-property name="personId" column="person_id"/>

<key-property name="email" column="email"/>

</composite-id>

<property name="firstName" column="first_name"/>

<property name="lastName" column="last_name"/>

<property name="age" column="age"/>

</class>

</hibernate-mapping>

Now I am trying to select data using load method, but it's raising a typeMisMatch Exception.

My load function is:

Person p1=(Person) ss.load(Person.class,new Integer("1"));

System.out.println(p1.getFirstName());

System.out.println(p1.getLastName());

System.out.println(p1.getAge());

How do you retrieve data if the table contains two primary keys. Please help me.

网友答案:

you have to use

Person p1=(Person) ss.load(Person.class,new PKField("1","email"));

and PKField must implement .equals() and hashcode() methods, hibernate relies on these methods to cache and compare the data.

网友答案:

Create an instance of PKField and pass it to load() method.

NOTE

Make sure your composite key class satisfies the conditions specified here

  • It must implement java.io.Serializable.
  • It must re-implement equals() and hashCode() consistently with the database's notion of composite key equality.
网友答案:

A composite-id means that records are identical if all parts of the composite id match. That is, the rows

ID  |  EMAIL
----+-------------------
1   |  [email protected]
1   |  [email protected]

represent different objects to hibernate. You therefore need to pass all parts of the composite key to load(...) to identify the object that should be loaded.

If your intention is that the id by itself uniquely identifies a record, and the same for email, declare one as identifier and the other as natural-id. You might have to use queries to get the entity by natural-id (not sure, I never use them myself).

分享给朋友:
您可能感兴趣的文章:
随机阅读: