简体   繁体   中英

JPA: how to override column names of @Embedded attributes

Person class

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

    //...
}

is embedded inside Event twice as two different attributes: manager and operator

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

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

    //...
}

This should give two respective columns when generating database schema with Persistence. Instead an exception is thrown:

org.hibernate.MappingException: Repeated column in mapping for entity: Event column: code

How to override default column name code for each attribute?

Use @AttributeOverride , here is an example

@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;
    ...
}

In your case it would look like this

@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;

    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM