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/student 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.School" /> 30 <mapping class="cqvie.yjq.domain.Student" /> 31 </session-factory> 32 33 </hibernate-configuration>
Hibernate.cfg.xml
1 package cqvie.yjq.domain; 2 3 import java.io.Serializable; 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.Table; 10 11 import org.hibernate.annotations.GenericGenerator; 12 13 @Entity 14 @Table(name = "school_2", catalog = "test") 15 public class School implements Serializable { 16 17 private static final long serialVersionUID = -9135891983324864046L; 18 19 @Id 20 @GenericGenerator(name = "generator", strategy = "uuid") 21 @GeneratedValue(generator = "generator") 22 @Column(name = "s_num", unique = true, nullable = false) 23 private String s_num; 24 @Column(name = "s_name", length = 50, nullable = false) 25 private String s_name; 26 @Column(name = "s_addr", length = 100, nullable = false) 27 private String s_addr; 28 29 public String getS_num() { 30 return s_num; 31 } 32 public void setS_num(String sNum) { 33 s_num = sNum; 34 } 35 public String getS_name() { 36 return s_name; 37 } 38 public void setS_name(String sName) { 39 s_name = sName; 40 } 41 public String getS_addr() { 42 return s_addr; 43 } 44 public void setS_addr(String sAddr) { 45 s_addr = sAddr; 46 } 47 }
实体类School
1 package cqvie.yjq.domain; 2 3 import java.io.Serializable; 4 5 import javax.persistence.CascadeType; 6 import javax.persistence.Column; 7 import javax.persistence.Entity; 8 import javax.persistence.GeneratedValue; 9 import javax.persistence.Id; 10 import javax.persistence.JoinColumn; 11 import javax.persistence.ManyToOne; 12 import javax.persistence.Table; 13 14 import org.hibernate.annotations.GenericGenerator; 15 16 @Entity 17 @Table(name = "student_2", catalog = "test") 18 public class Student implements Serializable { 19 20 private static final long serialVersionUID = 7571983435023574040L; 21 22 @Id 23 @GenericGenerator(name = "generator", strategy = "uuid") 24 @GeneratedValue( generator = "generator") 25 @Column(name = "id", nullable = false, unique = true) 26 private String id; 27 28 @Column(name = "name", nullable = false, length = 20) 29 private String name; 30 31 @Column(name = "age", nullable = false, length = 3) 32 private int age; 33 34 @ManyToOne(cascade={CascadeType.ALL}) 35 @JoinColumn(name = "s_num") 36 private School school; 37 38 public School getSchool() { 39 return school; 40 } 41 public void setSchool(School school) { 42 this.school = school; 43 } 44 public String getId() { 45 return id; 46 } 47 public void setId(String id) { 48 this.id = id; 49 } 50 public String getName() { 51 return name; 52 } 53 public void setName(String name) { 54 this.name = name; 55 } 56 public int getAge() { 57 return age; 58 } 59 public void setAge(int age) { 60 this.age = age; 61 } 62 }
实体类Student
1 package cqvie.yjq.View; 2 3 import org.hibernate.Session; 4 import org.hibernate.Transaction; 5 6 import cqvie.yjq.Util.HibernataUtil; 7 import cqvie.yjq.domain.School; 8 import cqvie.yjq.domain.Student; 9 10 11 public class Test { 12 13 public static void main(String[] args) { 14 15 Session session = null; 16 Transaction tx = null; 17 try { 18 session = HibernataUtil.getCurrentSession(); 19 tx = session.beginTransaction(); 20 //添加 21 School sc = new School(); 22 sc.setS_name("重庆工业职业技术学院"); 23 sc.setS_addr("重庆渝北"); 24 25 Student stu = new Student(); 26 stu.setSchool(sc); 27 stu.setAge(17); 28 stu.setName("马士兵"); 29 30 session.save(stu); 31 32 tx.commit(); 33 } catch (Exception e) { 34 if(tx != null) { 35 tx.rollback(); 36 } 37 } finally { 38 if(session != null && session.isOpen()) { 39 session.close(); 40 } 41 } 42 43 } 44 }
测试类Test
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
时间: 2024-10-07 09:59:22