开发者

Shared PK in entity mismatch

I'm developing an example web-application, using JPA 2.0 entities, Hibernate 3.6.2 and Spring 3. The 开发者_运维问答example contains two tables in a one-to-one relationship, the parent entity is Client and the child is Address, the PK in Address references the Client table (identifying relationship).

Running the JUnit tests, I've noted a peculiar problem with these two entities, the problem it's that the child entity persists with the (parentId + 1), my mappings are as follows:

@Entity
public class Client implements Serializable{
    private Long clientId;
    private Address address;
    //Other fields

    @Id
    @GeneratedValue
    public Long getClientId(){return this.clientId;}
    public void setClientId(Long id){this.clientId=id;}

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="clientid",referencedColumnName="fk_clientid")
    public Address getAddress(){return this.address;}
}

And the child entity:

@Entity
public class Address implements Serializable{
    private Long fkClientId;
    private Client client;
    //Other fields

    @Id
    @GeneratedValue
    public Long getFkClientId(){return this.fkClientId;}
    public void setFkClientId(Long id){this.fkClientId=id;}

    @OneToOne(mappedBy="address")        
    public Client getClient(){return this.client;}
}

In my test methods I link both objects using their setters, but after persist the entities and execute the line:

assertEquals(client.getClientId, client.getAddress().getFkClientId);

The test fails with the exception

java.lang.AssertionError: expected:<654> but was:<655>

I've readed similar questions and problems, but almost all of them are from JPA 1.0, it's supossed that in JPA2.0 the shared keys are automatically assigned. What am I missing?


The correct version of such a mapping is shown in javadoc of @OneToOne. Note that the side with derived identity should be the owning side of relationship (without mappedBy):

@Entity
public class Client implements Serializable {     
    @Id
    @GeneratedValue
    private Long clientId;     

    @OneToOne(mappedBy = "client", cascade = CascadeType.ALL)
    private Address address; 

    ...
}

@Entity 
public class Address implements Serializable {
    @Id
    private Long fkClientId;

    @OneToOne
    @MapsId
    @JoinColumn(name = "fk_clientid")
    private Client client; 

    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜