Hibernate父子不在表中保存外键

时间:2013-11-21 22:55:56

标签: java hibernate

我有两个拥有父子关系的实体 - 人和地址。

他们有一对一的关系。

我可以通过一次保存级联保存它们。

但是下面的代码没有在Person表中添加foreign_key address_id。

SQL:

create table PERSON (
   id number(20) NOT NULL ,
   PRIMARY KEY (id)
);
alter table Person add  address_id number(20);
alter table Person add  CONSTRAINT FK_Address FOREIGN KEY (address_id) REFERENCES address (id);

create table Address (
   id number(20) NOT NULL ,
   PRIMARY KEY (id)
);

Hibernate代码:

@Entity
@Table(name="Person")
@javax.persistence.SequenceGenerator(name="SOME_SEQ", sequenceName="pk_sequence")
public class Person 
{
   @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SOME_SEQ")
   private int id;

   @OneToOne
   @PrimaryKeyJoinColumn
   @Fetch(FetchMode.JOIN)
   @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
   private Address address;
}


@Entity
@javax.persistence.SequenceGenerator(name="SOME_SEQ", sequenceName="pk_sequence")
public class Address 
{
   @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SOME_SEQ")
   private int id;

   @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
   @OneToOne(mappedBy="address")
   @Fetch(FetchMode.JOIN)
   private Person person;
}

驾驶密码:

Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Person p = new Person();
Address add = new Address ();
p.setAddress(add);
add.setPerson(p);
id = (Integer) session.save(p); 
tx.commit();

1 个答案:

答案 0 :(得分:3)

您的映射是错误的。 Person中有一列是地址表的外键。但是您将关联映射到@PrimaryKeyJoinColumn,这意味着:此实体的ID也是地址表的外键。使用@JoinColumn。不是@PrimaryKeyJoinColumn