如何在hibernate中使用两列作为主键 [英] how to use two columns as primary key in hibernate

查看:133
本文介绍了如何在hibernate中使用两列作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张五列的桌子。这两列构成了我桌子的主键。我想用hibernate实例化一个对应于该表的实体类。问题是我如何告诉hiberante主键不仅仅是一个班的单个领域,而是两个。我不希望hiberante为我创建数据库模式,因为我已经用所有必要的主键设置了它。



我已阅读复合键,但它认为不适合我。毕竟,我只有一张桌子,在我的代码中不会有一对多或类似的基数。



我尝试了类似这样的东西,不工作。

 <?xml version =1.0?> 
<!DOCTYPE hibernate-mapping PUBLIC
- // Hibernate / Hibernate映射DTD // EN
http://hibernate.sourceforge.net/hibernate-mapping-3.0。 DTD>
< hibernate-mapping>
< class name =blog.Messagetable =MESSAGES>
< id name =titlecolumn =MESSAGE_TITLE>< / id>
< id name =authorcolumn =MESSAGE_AUTHOR>< / id>
< property name =bodycolumn =MESSAGE_BODY/>
// ....以及另外两个字段

< / class>
< / hibernate-mapping>

执行此操作的方法是?复合钥匙是必须的吗?
在此先感谢

解决方案

理想情况下,如果可能的话,应该避免使用休眠自然键。如果你创建一个id列,Hibernate可以更好地工作,hibernate可以用来管理行的身份。


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

解决方案

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.

这篇关于如何在hibernate中使用两列作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆