澳门新葡萄京官网首页三大框架之hibernate入门,三大hibernate入门

CRUD是指在做计算处理时的增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写.

三大框架之hibernate入门,三大hibernate入门

hibernate入门   1、orm    
 hibernate是一个经典的开源的orm[数据访问中间件]框架           ORM(
Object Relation Mapping)对象关系映射      通过 对象模型 操作
数据库关系模型 hibernate处于项目的持久层位置,因此又称为持久层框架  
2、hibernate核心组件            SessionFactory [整个数据库的操作]
重量级组件      Session[对数据库的一次业务操作] — 轻量级组件  
3、hibernate配置      配置SessionFactory   4、使用hibernate开发一个APP  
在导好jar包后:    
 a.配置hibernate.cfg.xml:澳门新葡萄京官网首页 1

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6 <session-factory>
 7 <!--Database connection settings -->
 8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
 9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
10 <property name="connection.username">scott</property>
11 <property name="connection.password">tiger</property>
12 <!--SQL dialect 方言-->
13 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
14 <!--Enable Hibernate's automatic session context management -->
15 <property name="current_session_context_class">thread</property>
16 <!--Echo all executed SQL to stdout -->
17 <property name="show_sql">true</property>
18 <mapping resource="com/it/bean/UserInfo.hbm.xml"/>
19 </session-factory>
20 </hibernate-configuration>

 

   SessionFactory  —  关联  xxx.hbm.xml UserInfo.hbm.xml的配置:
澳门新葡萄京官网首页 2 1
<?xml version=”1.0″?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3
“-//Hibernate/Hibernate Mapping DTD 3.0//EN” 4
“; 5
<hibernate-mapping package=”com.it.bean”> 6 <class
name=”UserInfo” table=”userinfo”> 7 <id name=”user_id”
column=”user_id”> 8 <!– 主键生成策略 –> 9 <generator
class=”assigned”></generator> 10 </id> 11 <property
name=”user_name” column=”user_name”></property> 12
<property name=”user_sex” column=”user_sex”></property> 13
<property name=”user_birth”
column=”user_birth”></property> 14 <property
name=”user_addr” column=”user_addr”></property> 15
<property name=”user_pwd” column=”user_pwd”></property> 16
</class> 17 </hibernate-mapping> View Code

 

澳门新葡萄京官网首页 ,  补充: 主键生成策略

  • Assigned:主键由外部程序生成,无需Hibernate干预。

  • identity:采用数据库提供的主键生成机制,如MySql、DB2、SqlServer的自增主键。

  • sequence:使用数据库的sequence机制。

  • hilo:通过hi/lo
    算法实现的主键生成机制,需要额外的数据库表保存主键生成历史状态。

  • seqhilo:与hilo 类似,通过hi/lo
    算法实现的主键生成机制,只是主键历史状态保存在Sequence中,适用于支持Sequence的数据库,如Oracle。

  • increment:主键按数值顺序递增。此方式的实现机制为在当前应用实例中维持一个变量,以保存着当前的最大值,之后每次需要生成主键的时候将此值加1作为主键。这种方式可能产生的问题是:如果当前有多个实例访问同一个数据库,那么由于各个实例各自维护主键状态,不同实例可能生成同样的主键,从而造成主键重复异常。因此,如果同一数据库有多个实例访问,此方式必须避免使用。

  • native:由Hibernate根据底层数据库定义自行判断采用identity、hilo、sequence其中一种作为主键生成方式。

  • foreign:使用外部表的字段作为主键。

  • uuid.hex:由Hibernate基于128
    位唯一值产生算法,根据IP、当前时间、JVM启动时间、内部自增量生成16
    进制数值(编码后以长度32
    的字符串表示)作为主键,该方法提供了最好的数据库插入性能和数据库平台适应性。

  • uuid.string:与uuid.hex
    类似,只是生成的主键未进行编码(长度16),在某些数据库中可能出现问题(如PostgreSQL)。

              b、创建sessionFactory SessionFactory
sessionFactory=(SessionFactory) new
Configuration().configure().buildSessionFactory();      c.创建Session
Session session=sessionFactory .getCurrentSession();    
 d.创建Transaction //创建事务并开启事务 Transaction tx
= session.beginTransaction();          e.开启事务    
 f.执行操作–业务操作      g.提交事务 tx.commit();      
 h.异常处理块,事务回滚 在try catch异常处理后,tx.rollback;
完整代码(basedao):
澳门新葡萄京官网首页 3 1
package com.it.dao; 2 import java.util.List; 3 import
org.hibernate.Query; 4 import org.hibernate.SessionFactory; 5 import
org.hibernate.Transaction; 6 import org.hibernate.cfg.Configuration; 7
import org.hibernate.classic.Session; 8 import
com.it.dao.util.SessionFactoryUtils; 9 /** 10 * 基础DAO 11 * @author
xj 12 * 13 */ 14 public class BaseDAO <T>{ 15 /** 16 *
查询集合–全部 17 */ 18 public List<T> find(String hql){ 19
Session session =null; 20 //事务 21 Transaction tx = null; 22
List<T> list =null; 23 try { 24
//这里将创建SessionFactory写成了方法(工具类)–创建SessionFactory并得到Session
25 session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
26 //开启事务 27 tx=session.beginTransaction(); 28 //查询Java bean
UserInfo–对象这里hql是查询语句:eg:from UserInfo(UserInfo–>是java
bean里的对象) 29 Query query = session.createQuery(hql); 30 list =
query.list(); 31 //提交 32 tx.commit(); 33 } catch (Exception e) { 34
e.printStackTrace(); 35 //事务回滚 36 tx.rollback(); 37 } 38 return
list; 39 } 40 41 /** 42 * 查询带参数 43 */ 44 public List<T>
find(String hql,String …params){ 45 Session session =null; 46 //事务
47 Transaction tx = null; 48 List<T> list =null; 49 try { 50
session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 51
//开启事务 52 tx=session.beginTransaction(); 53 //查询Java bean
UserInfo–对象 54 Query query = session.createQuery(hql); 55
//给参数赋值 56 for (int i = 0; i < params.length; i++) { 57
query.setString(i, params[i]); 58 } 59 list = query.list(); 60 //提交
61 tx.commit(); 62 } catch (Exception e) { 63 e.printStackTrace(); 64
//事务回滚 65 tx.rollback(); 66 } 67 return list; 68 } 69 70 } 71 /**
72 * 添加 73 * @param obj 74 */ 75 public void add(Object obj){ 76
Session session =null; 77 Transaction tx = null; 78 try { 79 // 80
session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 81
tx=session.beginTransaction(); 82 //操作 83 session.save(obj); 84 //提交
85 tx.commit(); 86 } catch (Exception e) { 87 // TODO: handle exception
88 e.printStackTrace(); 89 //事务回滚 90 tx.rollback(); 91
System.out.println(“–我回滚啦—“); 92 } 93 } 94 95 /** 96 *
按对象删除 97 */ 98 public void del(Object obj){ 99 Session session
=null; 100 Transaction tx = null; 101 try { 102 // 103
session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 104
tx=session.beginTransaction(); 105 //操作 106 session.delete(obj); 107
//提交 108 tx.commit(); 109 } catch (Exception e) { 110 // TODO: handle
exception 111 e.printStackTrace(); 112 //事务回滚 113 tx.rollback(); 114
System.out.println(“–我回滚啦—“); 115 } 116 } 117 /** 118 *
按编号删除 119 */ 120 public void delete(Class<T> clz, String
OID){ 121 Session session =null; 122 Transaction tx = null; 123
//通过给的id来查询该id的对象 124 Object o=get(clz,OID); 125 try { 126 //
127 session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
128 tx=session.beginTransaction(); 129 //操作 130 session.delete(o); 131
//提交 132 tx.commit(); 133 } catch (Exception e) { 134 // TODO: handle
exception 135 e.printStackTrace(); 136 //事务回滚 137 tx.rollback(); 138
System.out.println(“–我回滚啦—“); 139 } 140 } 141 142 /** 143 *
修改 144 * @param obj 145 */ 146 public void upd(Object obj){ 147
Session session =null; 148 Transaction tx = null; 149 try { 150
//得到SessionFactory 151
session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 152
//开启事务 153 tx=session.beginTransaction(); 154 //操作 155
session.update(obj); 156 //提交 157 tx.commit(); 158 } catch (Exception
e) { 159 // TODO: handle exception 160 e.printStackTrace(); 161
//事务回滚 162 tx.rollback(); 163 System.out.println(“–我回滚啦—“);
164 } 165 } 166 167 /** 168 * 查询 169 */ 170 public T
get(Class<T> clz, String OID){ 171 Session session =null; 172
Transaction tx = null; 173 T t=null; 174 try { 175 // 176
session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 177
tx=session.beginTransaction(); 178 //操作 179 t = (T)
session.get(getClass(), OID); 180 //提交 181 tx.commit(); 182 } catch
(Exception e) { 183 // TODO: handle exception 184 e.printStackTrace();
185 //事务回滚 186 tx.rollback(); 187
System.out.println(“–我回滚啦—“); 188 } 189 return t; 190 } 191 View Code

 

hibernate导的包:澳门新葡萄京官网首页 4澳门新葡萄京官网首页 5澳门新葡萄京官网首页 6澳门新葡萄京官网首页 7

hibernate入门 1、orm
hibernate是一个经典的开源的orm[数据访问中间件]框架 ORM( Object
Relation Mapping)对象…

下面列举实例来讲解这几个操作:

实体类:

package com.oumyye.model;

public class Student {

    private long id;
    private String name;
    private Class c;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public Class getC() {
        return c;
    }
    public void setC(Class c) {
        this.c = c;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }

}

package com.oumyye.model;

import java.util.HashSet;
import java.util.Set;

public class Class {

    private long id;
    private String name;
    private Set<Student> students=new HashSet<Student>();

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }

}

映射文件:
Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.oumyye.model">
 <class name="Student" table="t_student">
  <id column="stuId" name="id">
   <generator class="native"/>
  </id>
  <property column="stuName" generated="never" lazy="false" name="name"/>
  <many-to-one cascade="save-update" class="com.oumyye.model.Class"
   column="classId" name="c"/>
 </class>
</hibernate-mapping>

Class.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.oumyye.model">
 <class name="Class" table="t_class">
  <id column="classId" name="id">
   <generator class="native"/>
  </id>
  <property column="className" generated="never" lazy="false" name="name"/>
  <set cascade="delete" inverse="true" name="students" sort="unsorted">
   <key column="classId"/>
   <one-to-many class="com.oumyye.model.Student"/>
  </set>
 </class>
</hibernate-mapping>

工具类:可以有myeclipse生成

package com.oumyye.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;

    private static Configuration configuration = new AnnotationConfiguration();    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }

    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     *  return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     *  return session factory
     *
     *    session factory will be rebuilded in the next call
     */
    public static void setConfigFile(String configFile) {
        HibernateSessionFactory.configFile = configFile;
        sessionFactory = null;
    }
    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

配置文件hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

    <!--数据库连接设置 -->
    <property name="connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="connection.url">
        jdbc:mysql://localhost:3306/mytest
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- 方言 -->
    <property name="dialect">
        org.hibernate.dialect.MySQL5Dialect
    </property>

    <!-- 控制台显示SQL -->
    <property name="show_sql">true</property>

    <!-- 自动更新表结构 -->
    <property name="hbm2ddl.auto">update</property>
    <mapping resource="com/oumyye/model/Class.hbm.xml" />
    <mapping resource="com/oumyye/model/Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

测试类

package com.oumyye.service;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.oumyye.model.Class;
import com.oumyye.model.Student;
import com.oumyye.util.HibernateSessionFactory;

public class StudentTest {

    private SessionFactory sessionFactory=HibernateSessionFactory.getSessionFactory();
    private Session session;

    @Before
    public void setUp() throws Exception {
        session=sessionFactory.openSession(); // 生成一个session
        session.beginTransaction(); // 开启事务
    }

    @After
    public void tearDown() throws Exception {
         session.getTransaction().commit(); // 提交事务
         session.close(); // 关闭session
    }

    @Test
    public void testSaveClassAndStudent() {
        Class c=new Class();
        c.setName("08计本");

        Student s1=new Student();
        s1.setName("张三");
        s1.setC(c);

        Student s2=new Student();
        s2.setName("李四");
        s2.setC(c);

        session.save(s1);
        session.save(s2);

    }

    @Test
    public void testLoadClass(){
        // Class c=(Class)session.load(Class.class, Long.valueOf(2));
        Class c=(Class)session.load(Class.class, Long.valueOf(1));
        System.out.println(c.getStudents());
    }

    @Test
    public void testGetClass(){
        // Class c=(Class)session.get(Class.class, Long.valueOf(2));
        Class c=(Class)session.get(Class.class, Long.valueOf(1));
        System.out.println(c.getStudents());
    }

    @Test
    public void testUpdateClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();
        c.setName("08计算机本科2");
        session2.update(c);
        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }
    <!--更新-->
    @Test
    public void testSaveOrUpdateClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();
        c.setName("08计算机本科3");

        Class c2=new Class();
        c2.setName("09计算机本科3");
        session2.saveOrUpdate(c);
        session2.saveOrUpdate(c2);
        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }

    @Test
    public void testMergeClass(){
        Session session1=sessionFactory.openSession();
        session1.beginTransaction();
        Class c=(Class)session1.get(Class.class, Long.valueOf(1));
        session1.getTransaction().commit(); // 提交事务
        session1.close();

        Session session2=sessionFactory.openSession();
        session2.beginTransaction();

        Class c2=(Class)session2.get(Class.class, Long.valueOf(1));
        c.setName("08计算机本科4");

        session2.merge(c);

        session2.getTransaction().commit(); // 提交事务
        session2.close();
    }
    <!--删除-->
    @Test
    public void testDeleteStudent(){
        Student student=(Student)session.load(Student.class, Long.valueOf(1));
        session.delete(student);
    }
}

Session的入门常用方法

  • Query query = session.createQuery(hql):利用hql查询语句查询;
  • Criteria critera = session.createCriteria(Class clazz);
  • (3)Transaction tx = session.beginTransaction();    
    //开始事务;tx.commit()提交事务;
  • session.close();//关闭Session,此后被session管理的持久化对象变为脱管状态;
  • session.save(Object obj);    //添加
  • session.update(Object obj);     //更新
  • session.delete(Object obj);    //删除
  • Object obj = session.get(Class clazz,Serialiazble id);  
     //根据主键查找记录并返回;
  • Object obj = session.load(Class clazz,Serializable id);  
     //和get方法效果一样,但是是懒加载,即在不使用他之前他不会返回对象;

发表评论

电子邮件地址不会被公开。 必填项已用*标注