Hibernate annotations one2one with WithExplicitFk 單向一對一 有外鍵

Client 的代碼:

 

//$Id: Client.java 11282 2007-03-14 22:05:59Z epbernard $
package org.hibernate.test.annotations.onetoone;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

/**
 * @author Emmanuel Bernard
 */
@Entity
public class Client {

 private Integer id;
 private String name;
 private Address address;

 @OneToOne(cascade = CascadeType.ALL)
 @JoinColumn(name = "ADDRESS_ID")


 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

 @Id
 @GeneratedValue
 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}

其中  @JoinColumn(name = "ADDRESS_ID") 指定外鍵名稱爲  ADDRESS_ID

 

Address 的代碼:

 

//$Id: Address.java 11282 2007-03-14 22:05:59Z epbernard $
package org.hibernate.test.annotations.onetoone;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author Emmanuel Bernard
 */
@Entity
public class Address {

 private Integer id;
 private String city;

 @Id
 @GeneratedValue
 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }
}

 測試代碼如下:

 

  Client c = new Client();
  Address a = new Address();
  a.setCity( "Paris" );
  c.setName( "Emmanuel" );
  c.setAddress( a );

  Session s;
  Transaction tx;
  s = openSession();
  tx = s.beginTransaction();
  s.persist( c );
  tx.commit();
  s.close();

  s = openSession();
  tx = s.beginTransaction();
  c = (Client) s.get( Client.class, c.getId() );
  assertNotNull( c );
  assertNotNull( c.getAddress() );
  assertEquals( "Paris", c.getAddress().getCity() );
  tx.commit();
  s.close();

 

 

其他配置請參考我的前幾篇文章。

qq  81553652

發佈了35 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章