David SN
David SN

Reputation: 3519

Override foreign key column name using an embedded object

If an Embeddable object has defined a OneToOne relationship to an entity. How can the Entity that uses the Embeddable object override the column name for the relationship.

Using the following entities:

@Entity
public class User {

    @Id
    private int id;
    @Embedded
    private CubeLocation cubeLocation;
}

@Embeddable
public class CubeLocation { 
    @OneToOne
    private MailBox mailBox;            
    // .. other non-relevant fields
}

@Entity
public class MailBox {  
    @Id
    private String name;
    private String cell;
}

The database table for the User entity would have the columns ID and MAILBOX_NAME. How can the name of the database column can be changed from MAILBOX_NAME to MBX_ID?

I have tried to define an AssociationOverride annotation to the User entity, but I am getting this error in that case:

    @Entity
    @AssociationOverride(
            name="cubeLocation.mailBox",
            joinColumns=@JoinColumn(name="MBX_ID"))
    public class User {
    }

Error:

org.hibernate.AnnotationException: Illegal attempt to define a @JoinColumn with a mappedBy association: cubeLocation.mailBox

Upvotes: 0

Views: 1573

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

Association overrides should go on the embeddable:

@Entity
public class User {

    @Id
    private int id;

    @Embedded
    @AssociationOverride(
            name="mailBox",
            joinColumns=@JoinColumn(name="MBX_ID"))
    private CubeLocation cubeLocation;
}

Upvotes: 1

Related Questions