Hibernate一对一双向关联(注解)

时间:2023-03-09 22:35:17
Hibernate一对一双向关联(注解)
每一个人(Person)对应一个身份证号(IdCard)
 package cqvie.yjq.domain;

 import java.util.Date;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "id_card", catalog = "test")
public class IdCard implements java.io.Serializable { private static final long serialVersionUID = -5388108961244621175L; @Id
@GenericGenerator(name = "generator", strategy = "uuid")
@GeneratedValue(generator = "generator")
@Column(name = "card_id", unique = true, nullable = false)
private String id;
@Column(name = "validate")
private Date validateDte;
@OneToOne
@JoinColumn(name = "per")
private Person person; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getValidateDte() {
return validateDte;
}
public void setValidateDte(Date validateDte) {
this.validateDte = validateDte;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
} }

实体类IdCard

 package cqvie.yjq.domain;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name = "person", catalog = "test")
public class Person implements java.io.Serializable { private static final long serialVersionUID = 3860690163559279293L; @Id
@GenericGenerator(name = "generator", strategy = "uuid")
@GeneratedValue(generator = "generator")
@Column(name = "per_id", unique = true, nullable = false)
private String id;
@Column(name = "name", nullable = false, length = 20)
private String name;
@OneToOne
@JoinColumn(name = "id_c")
private IdCard idCard; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public IdCard getIdCard() {
return idCard;
}
public void setIdCard(IdCard idCard) {
this.idCard = idCard;
} }

实体类Person

 package cqvie.yjq.View;

 import java.util.Date;

 import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport; import cqvie.yjq.Util.HibernataUtil;
import cqvie.yjq.domain.IdCard;
import cqvie.yjq.domain.Person; public class Test { public static void main(String[] args) { //调用建表语句
exportDDL();
//添加一组person
Session session = null;
Transaction tx = null;
try {
session = HibernataUtil.getCurrentSession();
tx = session.beginTransaction(); Person p1 = new Person();
p1.setName("张三"); IdCard idCard = new IdCard();
idCard.setValidateDte(new Date());
p1.setIdCard(idCard);
idCard.setPerson(p1);
session.save(p1);
session.save(idCard); tx.commit();
} catch (Exception e) {
if(tx != null) {
tx.rollback();
}
} finally {
if(session != null && session.isOpen()) {
session.close();
}
} } //建表语句
public static void exportDDL() {
Configuration configuration = new AnnotationConfiguration().configure();
SchemaExport sexport = new SchemaExport(configuration);
sexport.setFormat(true);//格式化输出
sexport.setDelimiter(";"); //每句sql都以;结尾 不然导入sql的时候会出现错误
sexport.setOutputFile("D:\\auto.sql");
sexport.create(true, true);
}
}

测试类Test

 <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration> <session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">MySQL</property>
<property name="show_sql">true</property>
<!-- 格式化显示SQL -->
<property name="format_sql">true</property> <property name="current_session_context_class">thread</property>
<!-- 让hibernate自动创建表 update:如果没有表则创建,有表则更新 -->
<property name="hbm2ddl.auto">create</property>
<mapping class="cqvie.yjq.domain.IdCard" />
<mapping class="cqvie.yjq.domain.Person" />
</session-factory> </hibernate-configuration>

Hibernate.cfg.xml

 package cqvie.yjq.Util;

 import java.util.List;

 import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration; final public class HibernataUtil { private static SessionFactory sessionFactory = null;
//使用线程局部模式
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private HibernataUtil() {};
static {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
//获取全新的session
public static Session openSession() {
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession() {
Session session = threadLocal.get();
//判断是否得到
if(session == null) {
session = sessionFactory.openSession();
//把session对象设置到threadLocal,相当于已经和线程绑定
threadLocal.set(session);
}
return session;
} //提供一个统一的修改和删除方法(批量)
public static void executeUpdate(String hql, String[] parameters) {
Session s = null;
Transaction ts = null;
try {
s = openSession();
ts = s.beginTransaction();
Query query = s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters != null && parameters.length > 0) {
for(int i=0;i<parameters.length;i++) {
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
ts.commit();
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
if(s != null && s.isOpen()) {
s.close();
}
}
} //提供一个统一的添加方法
public static void sava(Object obj) {
Session s = null;
Transaction ts = null;
try {
s = openSession();
ts = s.beginTransaction();
s.save(obj);
ts.commit();
} catch (Exception e) {
if(ts != null) {
ts.rollback();
}
throw new RuntimeException();
} finally {
if(s != null && s.isOpen()) {
s.close();
}
}
} //提供一个统一的查询方法(分页)
@SuppressWarnings("unchecked")
public static List executeQueryByPage(String hql, String[] parameters, int pageSize, int pageNow) {
Session s = null;
List list = null;
try {
s = openSession();
Query query = s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters != null && parameters.length > 0) {
for(int i=0;i<parameters.length;i++) {
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);
list = query.list();
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
if(s != null && s.isOpen()) {
s.close();
}
}
return list;
} //提供一个统一的查询方法 hql 形式 from 类 where 条件=?
@SuppressWarnings("unchecked")
public List executeQuery(String hql, String[] parameters) {
Session s = null;
List list = null;
try {
s = openSession();
Query query = s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters != null && parameters.length > 0) {
for(int i=0;i<parameters.length;i++) {
query.setString(i, parameters[i]);
}
}
list = query.list();
} catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
if(s != null && s.isOpen()) {
s.close();
}
}
return list;
}
}

工具类HibernateUtil