zoukankan      html  css  js  c++  java
  • Hibernate多对一(注解)

      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
     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.Table;
     8 
     9 import org.hibernate.annotations.GenericGenerator;
    10 
    11 @Entity
    12 @Table(name = "department_", catalog = "test")
    13 public class Department implements java.io.Serializable {
    14 
    15     private static final long serialVersionUID = 2076837731637660357L;
    16     
    17     @Id
    18     @GenericGenerator(name = "generator", strategy = "uuid")
    19     @GeneratedValue(generator = "generator")
    20     @Column(name = "depid", unique = true, nullable = false)//nullable = false表示该字段不为空
    21     private String depid;
    22     @Column(name = "name", nullable = false, length = 20)
    23     private String name;
    24     
    25     public String getDepid() {
    26         return depid;
    27     }
    28     public void setDepid(String depid) {
    29         this.depid = depid;
    30     }
    31     public String getName() {
    32         return name;
    33     }
    34     public void setName(String name) {
    35         this.name = name;
    36     }
    37     
    38 }
    实体类Department
     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.ManyToOne;
     9 import javax.persistence.Table;
    10 
    11 import org.hibernate.annotations.GenericGenerator;
    12 
    13 
    14 @Entity
    15 @Table(name = "student_", catalog = "test")
    16 public class Student implements java.io.Serializable {
    17 
    18     private static final long serialVersionUID = 8640757615294410421L;
    19     
    20     @Id
    21     @GenericGenerator(name = "generator", strategy = "uuid")
    22     @GeneratedValue(generator = "generator")
    23     @Column(name = "stuid", unique = true, nullable = false)
    24     private String stuid;
    25     @Column(name = "name", nullable = false, length = 20)
    26     private String name;
    27     @ManyToOne
    28     @JoinColumn(name = "depid")
    29     private Department dept;
    30     
    31     public String getStuid() {
    32         return stuid;
    33     }
    34     public void setStuid(String stuid) {
    35         this.stuid = stuid;
    36     }
    37     public String getName() {
    38         return name;
    39     }
    40     public void setName(String name) {
    41         this.name = name;
    42     }
    43     public Department getDept() {
    44         return dept;
    45     }
    46     public void setDept(Department dept) {
    47         this.dept = dept;
    48     }
    49     
    50     
    51 }
    实体类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.Department;
     8 import cqvie.yjq.domain.Student;
     9 
    10 public class Test {
    11 
    12     public static void main(String[] args) {
    13 
    14         //通过获取session让hibernate框架运行(config --> 加载hibernate.cfg.xml)
    15         Session session = null;
    16         Transaction tx = null;
    17         try {
    18             session =  HibernataUtil.getCurrentSession();
    19             tx = session.beginTransaction();
    20 
    21             Student stu = new Student();
    22             stu.setName("王敏");
    23             
    24             Department dep = new Department();
    25             dep.setName("财务部");
    26             Department dep1 = new Department();
    27             dep1.setName("人事部");
    28             
    29             stu.setDept(dep1);
    30             
    31             session.save(stu);
    32             session.save(dep);
    33             session.save(dep1);
    34             
    35             tx.commit();
    36         } catch (Exception e) {
    37             if(tx != null) {
    38                 tx.rollback();
    39             }
    40         } finally {
    41             if(session != null && session.isOpen()) {
    42                 session.close();
    43             }
    44         }
    45     }
    46 
    47 }
    测试类
     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.Department" />
    30     <mapping class="cqvie.yjq.domain.Student" />
    31 </session-factory>
    32 
    33 </hibernate-configuration>
    Hibernate.cfg.xml
  • 相关阅读:
    无法打开内核设备"\.Globalvmx86": 系统找不到指定的文件问题记录
    docker使用switch to Linux Containers切换不成windows问题
    js设计模式——发布订阅模式
    剑指offer系列——求1+2+…+n
    【转载】CSS3弹性盒布局方式
    【转载】.btc勒索病毒删除+还原文件(Dharma家族新成员)
    【转载】chrome浏览器的跨域设置——包括版本49前后两种设置
    【转载】SVN使用教程总结
    【转载】vue.js移动端app
    【转载】将web项目打包成手机app的方法
  • 原文地址:https://www.cnblogs.com/yjq520/p/6119868.html
Copyright © 2011-2022 走看看