【问题标题】:How to map a list of Strings with Hibernate XML file如何使用 Hibernate XML 文件映射字符串列表
【发布时间】:2016-07-12 16:15:55
【问题描述】:

我正在尝试使用 Hibernate XML 映射文件映射字符串列表。我的班级如下:

public class Historic {
    private String id;
    private String resolution;
    private List<String> names;
    private List<Score> scores;
    private String base;
    private List<Grade> grades;
}

我在文档中读到我应该使用&lt;element&gt; 标记,但我不知道如何引用Historic 类的特定属性。

我认为它可能是这样的:

<class name="Historic" table="HISTORIC">
    <id name="id" column="id">
        <generator class="native" />
    </id>

    <property name="resolution" type="string" column="resolution" />

    <element
        name="names"
        column="names"
        type="string"
    />

    ...

</class>

是吗?

【问题讨论】:

  • 不能直接在一个表中做,需要先映射到其他表。
  • 你可以这样做,但这不是一个好习惯。

标签: java xml hibernate


【解决方案1】:

你可以这样写:

<list name="names" table="names">
  <key column="name_id"></key>
  <index column="seq"></index>
  <element column="names" type="string"></element>
</list>

更多详情请查看https://achieversnitin.wordpress.com/2016/12/06/hibernate-collection-mapping-list/

【讨论】:

    【解决方案2】:

    假设你有两张桌子(父母和孩子) 你应该做这样的事情 -> 在你的情况下,你应该定义另一个表格。

    这里是一个hibernate中XML映射的例子

    <class name="Parent" table="Parent">
      <id name="parentId" column="id" type="integer" /> <!-- TODO: specify generator -->
      <property name="parentName" type="string" column="name" />
      <bag name="childs" table="Children" inverse="true">
        <key column="parent_id" />
        <one-to-many class="Child" />
      </bag>
    </class>
    
    <class name="Child" table="Children">
      <id name="childId" column="id" type="integer" /> <!-- TODO: specify generator -->
      <property name="childName" type="string" column="name" />
      <many-to-one name="parent" column="parent_id" not-null="true"/>
    </class>
    

    但对于列表,您也可以使用@ElementCollection annotation。 像这样:

    @ElementCollection
    @CollectionTable(name="Nicknames", joinColumns=@JoinColumn(name="user_id"))
    @Column(name="nickname") // nickname is the name of String field.
    public List<String> getNicknames() { ... } 
    

    获取更多关于收藏的信息:http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#collections-ofvalues

    希望对你有帮助。

    【讨论】:

    • 在上面的映射中,每个父母有一个或多个孩子,但每个孩子只有一个父母。
    猜你喜欢
    • 2010-10-22
    • 2018-01-16
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    相关资源
    最近更新 更多