java – HIbernate一对一注释不依赖表中生成外键GerericGenerator

我试图在Person和Auth表之间创建OneToOne关系.问题是当生成DB表“Auth”时,我没有在AUTH表中看到应该引用Person的外键.对象是让Auth表使用Person Table的相同主键.

 @MappedSuperclass
 public abstract class DomainBase {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE) 
    private Long id;

    @Version
    @Column(name="OPLOCK")
    private Integer version;
 }


 @Entity
 @Table(name = "person")  
 public class Person extends DomainBase {
        @OneToOne(cascade=CascadeType.ALL)
            @JoinColumn(name="auth_id")
        private Auth auth;
 }


 @Entity
 public class Auth {
    @Id
    @GeneratedValue(generator="foreign")
    @GenericGenerator(name="foreign", strategy = "foreign", parameters={
      @Parameter(name="property", value="person")
    })
    @Column(name="person_id")
    private int personId;
    ---------------------------------

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn 
    private Person person;
 }

hibernate数据库生成后的我的数据库脚本.

 CREATE TABLE auth
 (
   person_id integer NOT NULL,
   activate boolean,
   activationid character varying(255),
   last_login_attempt_date timestamp without time zone,
   last_login_attempt_timezone character varying(255),
   last_login_date timestamp without time zone,
   last_login_timezone character varying(255),
   nonlocked boolean,
   num_login_attempts integer,
   CONSTRAINT auth_pkey PRIMARY KEY (person_id),
   CONSTRAINT uk_d68auh3xsosyrjw3vmwseawvt UNIQUE (activationid)
 )
 WITH (
   OIDS=FALSE
 );
 ALTER TABLE auth
   OWNER TO postgres;

最佳答案 似乎问题是你在“person”表和“auth”表之间声明两次@OneToOne注释,而没有指定它们之间的关系.看一下
hibernate documentation,在2.2.5.1点,有一些关于使用一对一关联的例子.

对我来说,最好的方法是在一个表中设置关联,一个声明foreing键列,另一个在另一个对象中使用mappedBy参数.在您的代码中,这将是:

 @Entity
 @Table(name = "person")  
 public class Person extends DomainBase {
     @OneToOne(cascade=CascadeType.ALL)
     @JoinColumn(name="auth_id")
     private Auth auth;
 }


 @Entity
 public class Auth {
     @Id
     @GeneratedValue(generator="foreign")
     @GenericGenerator(name="foreign", strategy = "foreign", parameters={
         @Parameter(name="property", value="person")
     })
     @Column(name="person_id")
     private int personId;

     @OneToOne(mappedBy = "auth")
     private Person person;
....
 }

这是hibernate文档中的第二个示例,在句子“在下面的示例中,关联实体通过显式外键列链接”之后引入.我测试了这段代码,出现了“auth_id”列.

点赞