Hibernate annotations one2one with WithExplicitFk 单向一对一 有外键

本文介绍Hibernate中一对一关联关系的实现方式,通过示例代码展示了Client类与Address类之间的关联映射,包括实体类定义及测试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值