共享主键生成。过冬

时间:2014-02-02 15:57:28

标签: java hibernate primary-key generator shared-primary-key

我在使用共享主键生成具有一对一关系的主键时遇到问题。

这是代码:

@Entity
@Table(name = "osoba")
public class Osoba implements Serializable
{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "osoba_id")
    private Integer osobaId;

    @PrimaryKeyJoinColumn
    @OneToOne(cascade = CascadeType.PERSIST)
    public Pracownik pracownik;
...

和第二课:

@Entity
@Table(name = "pracownik")
public class Pracownik
{ 
    @OneToOne
    @JoinColumn(name = "osoba_id")
    @MapsId("osobaId")
    private Osoba osoba;

    @Id
    @Column(name = "osoba_id")
    private Integer osobaId;
...

我遇到了类似的问题,我认为我已经完成了所有事情,但我仍然得到了

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): entity.Pracownik

试图坚持Pracownik对象时。

2 个答案:

答案 0 :(得分:0)

您需要关注@MapsId documentation的示例(在您的情况下,使用@Id代替@EmbeddedId):

@Entity
@Table(name = "pracownik")
public class Pracownik {
    @Id 
    @Column(name = "oboba_id")
    private Integer id;

    @OneToOne
    @MapsId
    private Osoba osoba;

    ...
}

@OneToOne关系的反面应该与mappedBy一起映射,通常如下:

@Entity
@Table(name = "osoba")
public class Osoba implements Serializable {
    ...
    @OneToOne(mappedBy = "osoba", cascade = CascadeType.PERSIST)
    public Pracownik pracownik;
    ...
}

答案 1 :(得分:0)

这个老问题但对我有用。梅比会帮助别人。

SQL脚本(Oracle)

DROP TABLE HIBERNATE.PRACOWNIK;
DROP TABLE HIBERNATE.OSOBA;
DROP SEQUENCE HIBERNATE.OSOBA_SEQ;

CREATE TABLE HIBERNATE.OSOBA (
osoba_id                                NUMBER(15),
CONSTRAINT OSOBA_PK PRIMARY KEY (osoba_id)
);

CREATE TABLE HIBERNATE.PRACOWNIK (
    pracownik_id                                NUMBER(15),
    CONSTRAINT PRACOWNIK_PK PRIMARY KEY (pracownik_id),
    CONSTRAINT PRACOWNIK_FK FOREIGN KEY (pracownik_id) REFERENCES OSOBA(osoba_id)
);

CREATE SEQUENCE HIBERNATE.OSOBA_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;

Osoba.java

@Entity
@Table(name = "osoba")
public @Data class Osoba {

    @Id
    @Column(name = "osoba_id")
    @GeneratedValue(generator="osoba-generator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name="osoba-generator", allocationSize = 1, sequenceName = "OSOBA_SEQ")
    private Long osobaId;

    @OneToOne(fetch=EAGER, mappedBy="osoba", cascade=ALL)
    private Pracownik pracownik;
}

Pracownik.java

@Entity
@Table(name="pracownik")
public @Data class Pracownik {

    @Id
    @Column(name = "pracownik_id")
    @GeneratedValue(generator="pracownik-generator")
    @GenericGenerator(name="pracownik-generator", strategy="foreign", parameters=
        @Parameter(name = "property", value = "osoba")
    )
    private Long pracownikId;

    @OneToOne(fetch=FetchType.EAGER)
    @PrimaryKeyJoinColumn
    private Osoba osoba;

}

@Data Lombok