Domanda

JPA 2, Hibernate 4.

Creating entities from a database view. I'm having difficulty getting these two entities to map correctly. I have a parent Entity with a composite key, and a child Entity with a single value key.

The relationship between the two is defined by the Child entity having part of the Parent's composite key. Trying to make the association between the two.

Composite Key Class

@Embeddable
public Class ParentID implements Serializable {

    private static final long serialVersionUID = 1L;

    private long keyIdOne;
    private String keyIdTwo;
    ....
}

Parent Class

@Entity
public class Parent {
    @EmbeddedId
    protected ParentID id;
    ....

    @OneToMany
    private List<Child> childList;
}

Child Class

@Entity
public class Child {
    @Id
    private long Id;

    private long keyIdOne //FK to part of the parentId composite key
    .....


    @ManyToOne
    private Parent parent;
}

I'm not entirely sure how to get the mapping to work. The relationship from the child to the parent is the keyIdOne value. However, where this is part of a composite key in the parent I'm not sure how to get them to join on that value.

On the child class I'm unable to use:

@ManyToOne
@JoinColumn(name="keyIdOne", referencedColumnName="keyIdOne") 
private Parent parent;

as it throws an error of :

referencedColumnNames(keyIdOne) of Child is referencing Parent not mapped to a single property.

Any help is much appreciated.

È stato utile?

Soluzione

I believe the issue to this problem is in PK-FK(Primary Key - Foreign Key) constraints.

In summary:

Parent:
| keyIdOne | keyIdTwo |
|----------|----------|
|    1     |    a     |
|    1     |    b     |
|    3     |    a     |

Child:
| id | keyIdOne |
|----|----------|
| 2  |    1     |
| 3  |    3     |

A foreign key must reference a single row in the table that it's referencing (http://en.wikipedia.org/wiki/Foreign_key). Which row in Parent does does Child.keyIdOne reference if Child has keyIdOne = 1?

I thought there was a possibility of this working by using the @MapsId() annotation. However this will only work in inverse. Example:

Parent:
| keyIdOne |
|----------|
|    1     |
|    3     |

Child:
| keyIdOne | keyIdTwo |
|----------|----------|
|    1     |    a     |
|    1     |    b     |
|    3     |    a     |

In this case you can have the Child map part of its composite key to the Parent with:

@MapsId("keyIdOne")
private Parent parent;

@MapsId only works in a OnetoOne and ManyToOne (http://docs.oracle.com/javaee/6/api/javax/persistence/MapsId.html)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top