Pregunta

I have 2 entities : Field and ViewOptions

fields and methods not related to the problem are omitted

Table structure:

CREATE TABLE FIELD (
  ID                   INT          NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (ID),
);

CREATE TABLE VIEW_OPTIONS (
  ID                INT         NOT NULL AUTO_INCREMENT,
  FIELD_ID INT         NOT NULL,  
  PRIMARY KEY (ID),
  INDEX (FIELD_ID ASC),
  CONSTRAINT
  FOREIGN KEY (FIELD_ID)
  REFERENCES FIELD (ID)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

Mapping:

@Table(name = "FIELD")
@Entity
public class Field {
    @OneToOne(mappedBy ="field")
     ViewOptions viewOptions;

@Table(name = "VIEW_OPTIONS")
@Entity
public class ViewOptions  {
    @OneToOne
    @JoinColumn(name = "FIELD_ID")
    Field field;

In this relation the owner side is ViewOptions and the inverse side is Field. What i want to do is to swap sides - make Field the owner side. But if i mark viewOptions like this

 @OneToOne
 @JoinColumn(name = "FIELD_ID")
 ViewOptions viewOptions;

Hibernate expecting join column in Field table.

Is there any way to tell hibernate to search for join column in VIEW_OPTIONS?

¿Fue útil?

Solución

No, that's just not how it works. If you want the Field object to be the owner of the relationship, then the FIELD table will have to have a column for the VIEW_OPTIONS id.

Otros consejos

In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side.

The join column annotation here is optional an if no @JoinColumn is declared on the owner side, the defaults apply. A join column(s) will be created in the owner table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side.

So, if you want to make Field the owner side :

@Table(name = "FIELD")
@Entity
public class Field {
    @OneToOne
     ViewOptions viewOptions;

@Table(name = "VIEW_OPTIONS")
@Entity
public class ViewOptions  {
    @OneToOne(mappedBy ="viewOptions")
    Field field;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top