Hibernate Compsite Key without new class

*爱你&永不变心* 提交于 2019-12-10 18:35:31

问题


I have simple hibernate mapping

      <class name="com.domain.OtherAccount" table="ACCOUNT">
          <composite-id >
            <key-property name="acctype" column="acctype" type="java.lang.Character"></key-property>
            <key-property name="accnum" column="accnum" type="java.lang.Integer"></key-property>
          </composite-id>
         <property name="accholder"></property>
      </class>

I do not want to create separate class for Composite Key. So, acctype and accnum are part of OtherAccount class only. Class implements serializable interface and hashCode() and equals() methods.

I am able to create new object and persist it using, session.save(). But how can I retrieve existing object ? In session.get() method how to specify composite key ?

  In session.get(OtherAccount.class, HOW TO SPECIFY COMPOSITE KEY HERE )

回答1:


Create an instance of OtherAccount and set just those two fields. Hibernate doesn't care that the instance has more fields than it needs.




回答2:


@Aaron suggested the correct way. It worked. I just elaborate it here for complete understanding of future users.

With respect to above mapping, suppose I have an ACCOUNT table record with Composite Key Value Accnum :- 777

Acctype :- X

non-key column Accholder :- Kaushik

I retrieved and printed object this way :-

    OtherAccount oa1 = new OtherAccount();
    oa1.setAccholder("before retrieving");
    oa1.setAccnum(777);
    oa1.setAcctype('X');
    System.out.println("oa1.Accholder " + oa1.getAccholder());

    session.get(OtherAccount.class, oa1);

    System.out.println("oa1.Accholder " + oa1.getAccholder());

It retrieved correct record and "oa1" instance was loaded with DB data. So first SOP of oa1.getAccholder() printed "before retrieving" and second SOP printed "Kaushik" i.g. value from DB.

Do not forget to implement hashCode() and equals() methods, as it is required for comparing composite key.



来源:https://stackoverflow.com/questions/13375019/hibernate-compsite-key-without-new-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!