【问题标题】:JPA: how to override column names of @Embedded attributesJPA:如何覆盖@Embedded 属性的列名
【发布时间】:2016-08-02 22:51:18
【问题描述】:

Person

@Embeddable
public class Person {
    @Column
    public int code;

    //...
}

Event 中嵌入了两个不同的属性:manageroperator

@Entity
public class Event {
    @Embedded
    @Column(name = "manager_code")
    public Person manager;

    @Embedded
    @Column(name = "operator_code")
    public Person operator;

    //...
}

当使用 Persistence 生成数据库模式时,这应该给出两个相应的列。而是抛出异常:

org.hibernate.MappingException:实体映射中的重复列:事件列:代码

如何覆盖每个属性的默认列名code

【问题讨论】:

  • 使用@AssociationOverrides(用于实体关系)或@AttributeOverrides(用于简单属性)

标签: java hibernate jpa orm


【解决方案1】:

使用@AttributeOverride,这里是一个例子

@Embeddable public class Address {
    protected String street;
    protected String city;
    protected String state;
    @Embedded protected Zipcode zipcode;
}

@Embeddable public class Zipcode {
    protected String zip;
    protected String plusFour;
}

@Entity public class Customer {
    @Id protected Integer id;
    protected String name;
    @AttributeOverrides({
        @AttributeOverride(name="state",
                           column=@Column(name="ADDR_STATE")),
        @AttributeOverride(name="zipcode.zip",
                           column=@Column(name="ADDR_ZIP"))
    })
    @Embedded protected Address address;
    ...
}

在你的情况下,它看起来像这样

@Entity
public class Event {
    @Embedded
    @AttributeOverride(name="code", column=@Column(name="manager_code"))
    public Person manager;

    @Embedded
    @AttributeOverride(name="code", column=@Column(name="operator_code"))
    public Person operator;

    //...
}

【讨论】:

  • 这对我不起作用,因为我有两个相同 @Embeddable 类的实例,而不是像你的示例中的两个不同。
  • 查看编辑日期,答案似乎已被纠正以处理前面的评论
  • 我觉得没必要写@AttributeOverrides。这也适用于直接写入所有@AttributeOverride
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 2012-06-17
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 2015-01-08
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多