Hibernate @OneToOne relationships with multiple objects?

If I have a table like this ...

+------------------------------------------------------+
|                         Code                         |
+------------------------------------------------------+
| id |               target_uuid              |  code  |
+----+----------------------------------------+--------+
|  1 | "01BE898A-C5A9-4F86-B0AA-4ACCDCE81B8F" |    0   |
+----+----------------------------------------+--------+
|  2 | "E139F21E-8C93-492B-9E0F-CC773FAE832D" |    2   |
+----+----------------------------------------+--------+

... and target_uuidcan refer to a field Postor Useruuid, how do I display this in Hibernate?

Assume that is uuidnot the main key for Postor Userhere. I know I know. Bad data model, but I'm stuck with it.

I tried this:

@Entity
@Table(name = "User")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "uuid")
    private String uuid;

    @OneToOne(mappedBy = "user")
    @JoinColumn(name = "uuid")
    private Code code;

    // getters and setters
}

@Entity
@Table(name = "Post")
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "uuid")
    private String uuid;

    @OneToOne(mappedBy = "post")
    @JoinColumn(name = "uuid")
    private Code code;

    // getters and setters
}

@Entity
@Table(name = "Code")
public class Code {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "code")
    private Integer code;

    @Column(name = "target_uuid")
    private String targetUuid;

    @OneToOne
    @JoinColumn(name = "target_uuid", insertable = false, updatable = false)
    private User user;

    @OneToOne
    @JoinColumn(name = "target_uuid", insertable = false, updatable = false)
    private Post post;

    // getters and setters
}

It does not generate an exception, and it seems to work, but my objects User, and Postcontinue to receive NULL values for its properties code.

Can anyone shed some light on this?

+4
source share
2 answers

, , AFAIK, . OneToOne Post to Code ( ), referencedColumnName JoinColumn "target_uuid".

+1

, 1 "". , "target_uuid " ""? , "" "". "uuid". "uuid f". , ""? , .

: 1 "". , :

 FOREIGN KEY (uuid) REFERENCES code(target_uuid)

"post", "code".

. . ( .)

JPA ( "Post", "Code" )

@JoinColumn(name = "code_id", referencedColumnName = "target_uuid")
@OneToOne(optional = false)
private Code codeId;

, "" "". "". , . , :)

+1

Source: https://habr.com/ru/post/1526988/


All Articles