基于外键的单向1-1关联
一个House关联一个Owner。
House类:
package com.ydoing.hibernate3;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "house_inf")
public class House {
@Id
@Column(name = "house_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@OneToOne(targetEntity = Owner.class, cascade = CascadeType.ALL)
@JoinColumn(name = "owner_id", referencedColumnName = "owner_id", unique = true)
private Owner owner;
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;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}
Owner类:
package com.ydoing.hibernate3;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "owner_inf")
public class Owner {
@Id
@Column(name = "Owner_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
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;
}
private String name;
}
测试类:
package com.ydoing.hibernate3;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.BeforeClass;
import org.junit.Test;
public class Main {
private static Session session;
@BeforeClass
public static void init() {
Configuration conf = new Configuration();
conf.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties())
.build();
SessionFactory factory = conf.buildSessionFactory(serviceRegistry);
session = factory.openSession();
}
@Test
public void test() {
Transaction tx = session.getTransaction();
tx.begin();
Owner owner = new Owner();
owner.setName("Jack");
House house = new House();
house.setName("elegant");
house.setOwner(owner);
session.save(house);
tx.commit();
session.close();
}
}
console输出:
Hibernate:
insert
into
owner_inf
(name)
values
(?)
Hibernate:
insert
into
house_inf
(name, owner_id)
values
(?, ?)
从输出可以看出owner_id作为house_inf的外键。
数据表: