how to use two columns as primary key in hibernate

戏子无情 提交于 2019-12-25 08:30:07

问题


I have a table with five columns. The two columns, together, make up the primary key of my table. I'm trying to instantiate an Entity class that corresponds to that table using hibernate. The problem is how do I tell hiberante that the primary key is not just a single field of the class but two. I don't want hiberante to create the database schema for me as I have already crated it with all the necessary primary key settings.

I have read about the composite-key but it think that is not suitable for me. After all, I only have one table and there won't be one-to-many or similar cardinality in my code.

I tried something like this which apparently ain't working.

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
       <class name="blog.Message" table="MESSAGES">
       <id name="title" column="MESSAGE_TITLE"></id>
       <id name="author" column="MESSAGE_AUTHOR"></id>
       <property name="body" column="MESSAGE_BODY"/>
         // ....AND TWO MORE FIELDS

    </class>
    </hibernate-mapping>

What is the way to do it? Is composite-key a must? Thanks in advance


回答1:


Ideally you should avoid natural keys with hibernate, if at all possible. Hibernate will work much better if you create a single id column, that hibernate can use to manage the identity of the row.



来源:https://stackoverflow.com/questions/10422680/how-to-use-two-columns-as-primary-key-in-hibernate

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