每一个人(Person)对应一个身份证号(IdCard)
1 package cqvie.yjq.domain; 2 3 import java.util.Date; 4 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.JoinColumn; 10 import javax.persistence.OneToOne; 11 import javax.persistence.Table; 12 13 import org.hibernate.annotations.GenericGenerator; 14 15 16 @Entity 17 @Table(name = "id_card", catalog = "test") 18 public class IdCard implements java.io.Serializable { 19 20 private static final long serialVersionUID = -5388108961244621175L; 21 22 @Id 23 @GenericGenerator(name = "generator", strategy = "uuid") 24 @GeneratedValue(generator = "generator") 25 @Column(name = "card_id", unique = true, nullable = false) 26 private String id; 27 @Column(name = "validate") 28 private Date validateDte; 29 @OneToOne 30 @JoinColumn(name = "per") 31 private Person person; 32 33 public String getId() { 34 return id; 35 } 36 public void setId(String id) { 37 this.id = id; 38 } 39 public Date getValidateDte() { 40 return validateDte; 41 } 42 public void setValidateDte(Date validateDte) { 43 this.validateDte = validateDte; 44 } 45 public Person getPerson() { 46 return person; 47 } 48 public void setPerson(Person person) { 49 this.person = person; 50 } 51 52 }
实体类IdCard
1 package cqvie.yjq.domain; 2 3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.GeneratedValue; 6 import javax.persistence.Id; 7 import javax.persistence.JoinColumn; 8 import javax.persistence.OneToOne; 9 import javax.persistence.Table; 10 11 import org.hibernate.annotations.GenericGenerator; 12 13 @Entity 14 @Table(name = "person", catalog = "test") 15 public class Person implements java.io.Serializable { 16 17 private static final long serialVersionUID = 3860690163559279293L; 18 19 @Id 20 @GenericGenerator(name = "generator", strategy = "uuid") 21 @GeneratedValue(generator = "generator") 22 @Column(name = "per_id", unique = true, nullable = false) 23 private String id; 24 @Column(name = "name", nullable = false, length = 20) 25 private String name; 26 @OneToOne 27 @JoinColumn(name = "id_c") 28 private IdCard idCard; 29 30 31 public String getId() { 32 return id; 33 } 34 public void setId(String id) { 35 this.id = id; 36 } 37 public String getName() { 38 return name; 39 } 40 public void setName(String name) { 41 this.name = name; 42 } 43 public IdCard getIdCard() { 44 return idCard; 45 } 46 public void setIdCard(IdCard idCard) { 47 this.idCard = idCard; 48 } 49 50 }
实体类Person
1 package cqvie.yjq.View; 2 3 import java.util.Date; 4 5 import org.hibernate.Session; 6 import org.hibernate.Transaction; 7 import org.hibernate.cfg.AnnotationConfiguration; 8 import org.hibernate.cfg.Configuration; 9 import org.hibernate.tool.hbm2ddl.SchemaExport; 10 11 import cqvie.yjq.Util.HibernataUtil; 12 import cqvie.yjq.domain.IdCard; 13 import cqvie.yjq.domain.Person; 14 15 public class Test { 16 17 public static void main(String[] args) { 18 19 //调用建表语句 20 exportDDL(); 21 //添加一组person 22 Session session = null; 23 Transaction tx = null; 24 try { 25 session = HibernataUtil.getCurrentSession(); 26 tx = session.beginTransaction(); 27 28 Person p1 = new Person(); 29 p1.setName("张三"); 30 31 IdCard idCard = new IdCard(); 32 idCard.setValidateDte(new Date()); 33 p1.setIdCard(idCard); 34 idCard.setPerson(p1); 35 session.save(p1); 36 session.save(idCard); 37 38 tx.commit(); 39 } catch (Exception e) { 40 if(tx != null) { 41 tx.rollback(); 42 } 43 } finally { 44 if(session != null && session.isOpen()) { 45 session.close(); 46 } 47 } 48 49 } 50 51 //建表语句 52 public static void exportDDL() { 53 Configuration configuration = new AnnotationConfiguration().configure(); 54 SchemaExport sexport = new SchemaExport(configuration); 55 sexport.setFormat(true);//格式化输出 56 sexport.setDelimiter(";"); //每句sql都以;结尾 不然导入sql的时候会出现错误 57 sexport.setOutputFile("D:\\auto.sql"); 58 sexport.create(true, true); 59 } 60 }
测试类Test
1 <?xml version=‘1.0‘ encoding=‘UTF-8‘?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 6 <!-- Generated by MyEclipse Hibernate Tools. --> 7 <hibernate-configuration> 8 9 <session-factory> 10 <property name="dialect"> 11 org.hibernate.dialect.MySQLDialect 12 </property> 13 <property name="connection.url"> 14 jdbc:mysql://localhost:3306/test 15 </property> 16 <property name="connection.username">root</property> 17 <property name="connection.password">123</property> 18 <property name="connection.driver_class"> 19 com.mysql.jdbc.Driver 20 </property> 21 <property name="myeclipse.connection.profile">MySQL</property> 22 <property name="show_sql">true</property> 23 <!-- 格式化显示SQL --> 24 <property name="format_sql">true</property> 25 26 <property name="current_session_context_class">thread</property> 27 <!-- 让hibernate自动创建表 update:如果没有表则创建,有表则更新 --> 28 <property name="hbm2ddl.auto">create</property> 29 <mapping class="cqvie.yjq.domain.IdCard" /> 30 <mapping class="cqvie.yjq.domain.Person" /> 31 </session-factory> 32 33 </hibernate-configuration>
Hibernate.cfg.xml
1 package cqvie.yjq.Util; 2 3 import java.util.List; 4 5 import org.hibernate.Query; 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.hibernate.Transaction; 9 import org.hibernate.cfg.AnnotationConfiguration; 10 11 final public class HibernataUtil { 12 13 private static SessionFactory sessionFactory = null; 14 //使用线程局部模式 15 private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 16 private HibernataUtil() {}; 17 static { 18 sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); 19 } 20 //获取全新的session 21 public static Session openSession() { 22 return sessionFactory.openSession(); 23 } 24 //获取和线程关联的session 25 public static Session getCurrentSession() { 26 Session session = threadLocal.get(); 27 //判断是否得到 28 if(session == null) { 29 session = sessionFactory.openSession(); 30 //把session对象设置到threadLocal,相当于已经和线程绑定 31 threadLocal.set(session); 32 } 33 return session; 34 } 35 36 //提供一个统一的修改和删除方法(批量) 37 public static void executeUpdate(String hql, String[] parameters) { 38 Session s = null; 39 Transaction ts = null; 40 try { 41 s = openSession(); 42 ts = s.beginTransaction(); 43 Query query = s.createQuery(hql); 44 //先判断是否有参数要绑定 45 if(parameters != null && parameters.length > 0) { 46 for(int i=0;i<parameters.length;i++) { 47 query.setString(i, parameters[i]); 48 } 49 } 50 query.executeUpdate(); 51 ts.commit(); 52 } catch(Exception e) { 53 e.printStackTrace(); 54 throw new RuntimeException(); 55 } finally { 56 if(s != null && s.isOpen()) { 57 s.close(); 58 } 59 } 60 } 61 62 //提供一个统一的添加方法 63 public static void sava(Object obj) { 64 Session s = null; 65 Transaction ts = null; 66 try { 67 s = openSession(); 68 ts = s.beginTransaction(); 69 s.save(obj); 70 ts.commit(); 71 } catch (Exception e) { 72 if(ts != null) { 73 ts.rollback(); 74 } 75 throw new RuntimeException(); 76 } finally { 77 if(s != null && s.isOpen()) { 78 s.close(); 79 } 80 } 81 } 82 83 //提供一个统一的查询方法(分页) 84 @SuppressWarnings("unchecked") 85 public static List executeQueryByPage(String hql, String[] parameters, int pageSize, int pageNow) { 86 Session s = null; 87 List list = null; 88 try { 89 s = openSession(); 90 Query query = s.createQuery(hql); 91 //先判断是否有参数要绑定 92 if(parameters != null && parameters.length > 0) { 93 for(int i=0;i<parameters.length;i++) { 94 query.setString(i, parameters[i]); 95 } 96 } 97 query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize); 98 list = query.list(); 99 } catch(Exception e) { 100 e.printStackTrace(); 101 throw new RuntimeException(); 102 } finally { 103 if(s != null && s.isOpen()) { 104 s.close(); 105 } 106 } 107 return list; 108 } 109 110 111 //提供一个统一的查询方法 hql 形式 from 类 where 条件=? 112 @SuppressWarnings("unchecked") 113 public List executeQuery(String hql, String[] parameters) { 114 Session s = null; 115 List list = null; 116 try { 117 s = openSession(); 118 Query query = s.createQuery(hql); 119 //先判断是否有参数要绑定 120 if(parameters != null && parameters.length > 0) { 121 for(int i=0;i<parameters.length;i++) { 122 query.setString(i, parameters[i]); 123 } 124 } 125 list = query.list(); 126 } catch(Exception e) { 127 e.printStackTrace(); 128 throw new RuntimeException(); 129 } finally { 130 if(s != null && s.isOpen()) { 131 s.close(); 132 } 133 } 134 return list; 135 } 136 }
工具类HibernateUtil
时间: 2024-10-14 10:01:20