在JPA配置关系时一定要注意:
谁配置了mappedBy谁就是关系被维护端,另一个是关系维护端(关系维护端一般配置@JoinColumn表示外键和optional表示外键是否可以为NULL)。
关系护端即负责外键记录的更新,一方为被维护端即没有权力更新外键记录。
@Entity public class IDCard { private Integer car_id; private String car_no; private Person person; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getCar_id() { return car_id; } public void setCar_id(Integer car_id) { this.car_id = car_id; } @Column(nullable=false) public String getCar_no() { return car_no; } public void setCar_no(String car_no) { this.car_no = car_no; } @OneToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},mappedBy="idCard") public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
@Entity public class Person { private Integer per_Id; private String per_name; private IDCard idCard; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Integer getPer_Id() { return per_Id; } public void setPer_Id(Integer per_Id) { this.per_Id = per_Id; } @Column(nullable = false) public String getPer_name() { return per_name; } public void setPer_name(String per_name) { this.per_name = per_name; } @OneToOne(optional=false,cascade={CascadeType.ALL}) @JoinColumn(name="car_id") public IDCard getIdCard() { return idCard; } public void setIdCard(IDCard idCard) { this.idCard = idCard; } }
测试:
public class JPA_oneToOneTest extends TestCase { public void testJPAOneToOne() throws Exception { EntityManagerFactory factory = Persistence .createEntityManagerFactory("mengya"); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); Person p = new Person(); p.setPer_name("小博"); IDCard card = new IDCard(); card.setCar_no("421101256525"); p.setIdCard(card); em.persist(p); em.getTransaction().commit(); em.close(); factory.close(); } }