【问题标题】:Mapping java.util.Map with JPA使用 JPA 映射 java.util.Map
【发布时间】:2012-07-22 19:06:47
【问题描述】:

我有带有 Hibernate 映射类的 Java EE 应用程序(我使用 *.hbm.xml 映射)。 现在我需要使用 JPA 注释重新制作映射。一切都很好,但我无法使用我的 Map 属性创建正确的映射。

@Entity
@Table(name = DataBaseConstants.EMPLOYEE_TABLE)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = DataBaseConstants.EMPLOYEE_ID, sequenceName = DataBaseConstants.EMPLOYEE_SEQ)
@GeneratedValue(generator = DataBaseConstants.EMPLOYEE_ID)
@Column(name = DataBaseConstants.EMPLOYEE_ID)
private long id = 0;
@Column(name = DataBaseConstants.EMPLOYEE_NAME)
private String name = null;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = DataBaseConstants.ADDRESS_ID_FK)
private Address address = null; 

private Map<Office, Position> officePositions = null;

这是数据库中数据模型的一部分。 DB MODEL IMAGE (抱歉我不能发图片) 请帮我映射officeEmployee MAP

在 Hibernate 中,我使用了这种方式,一切正常。

<map name="officePositions" table="EMPLOYEE_POSITION_OFFICE" lazy="false"
                fetch="join" batch-size="100">
            <key>
            <column name="EMPLOYEE_ID"></column>
        </key>
        <map-key-many-to-many class="com.example.jpajdbctask.entities.Office">
            <column name="OFFICE_ID">
            </column>
        </map-key-many-to-many>
        <many-to-many column="POSITION_ID"
            class="com.example.jpajdbctask.entities.Position" />
        </map> 

【问题讨论】:

    标签: hibernate jpa mapping many-to-many map


    【解决方案1】:

    我自己从未使用过,所以我无法帮助您进行具体的实现,但您需要使用 @CollectionOfElements 注释,例如:

    @CollectionOfElements(fetch=FetchType.EAGER)
    @JoinTable(
        name = "MappingTable", 
        joinColumns = @JoinColumn(name = "mapOwner"))
    @Column(
       name = "mapValueItem", 
       nullable = false
    )  
    @org.hibernate.annotations.MapKey(
        columns={
            @Column(
                 name="mapKeyItem"
            )
       }
    )
    protected Map<String, String> getMapping() {
        return mapping_;
    }
    

    this 论坛可能会有所帮助。

    【讨论】:

    • thx,我试过了,但是我的 db 模型不适合它,Hibernate 尝试访问“officePositions_ID”列等。我在persistence.xml 中添加了这个类的hibernate 映射
    【解决方案2】:

    对于基本情况(其中 key 是一些原语),这里是 MapKey 注释的 JavaDoc 和示例。

    在你的情况下似乎应该使用@MapKeyColumn;这是一个example,与你的非常相似。

    您必须将 Employee 类中的 Map 更改为 Map&lt;Office, EmployeePositionOffice&gt;

    【讨论】:

      猜你喜欢
      • 2021-03-30
      • 2017-06-06
      • 2020-02-21
      • 2012-09-05
      • 2014-07-31
      • 2011-03-13
      • 2015-04-11
      • 2016-04-06
      • 2017-07-02
      相关资源
      最近更新 更多