分两类,主键一一对应,如一个人对应一张身份证。person(personId) —– identificationCard(cardId)。personId和
cardId都用id命名。
1.建表
CREATE TABLE person (
id INT NOT NULL,
name VARCHAR(100),
age INT,
CONSTRAINT `PRIMARY` PRIMARY KEY (id)
);
CREATE TABLE identificationCard(
id INT NOT NULL unique,
cardNo varchar(19),
foreign key(id) references person(id)
);
2.建model
2.1主表Person
@OneToOne(cascade = CascadeType.ALL, mappedBy = “person”)
public IdentificationCard getIdentificationCard() {
return identificationCard;
}
public void setIdentificationCard(IdentificationCard identificationCard) {
this.identificationCard = identificationCard;
}
2.2从表identificationCard
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
public Person getPerson() {
return this.person;
}
public void setPerson(Person person) {
this.person = person;
}
3.测试
package test1.r1;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import test1.model.IdentificationCard;
import test1.model.Person;
public class HibernateOne2One12 {
public static void main(String[] args) {
System.out.println(“开始事务”);
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
try {
Transaction tx = session.beginTransaction();
Person p1 = new Person(“bkd1”, 26);
IdentificationCard ic1 = new IdentificationCard();
ic1.setCardNo(“2009”);
ic1.setPerson(p1);
session.save(ic1);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
session.close();
sessionFactory.close();
}
System.out.println(“事务结束”);
}
}