澳门新浦京娱乐游戏三大框架之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基于1贰19位独一值发生算法,根据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(State of Qatar; 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(State of Qatar; 33 } catch (Exception eState of Qatar { 34
e.printStackTrace(卡塔尔国; 35 //事务回滚 36 tx.rollback(卡塔尔; 37 } 38 return
list; 39 } 40 41 /** 42 * 查询带参数 43 */ 44 public List<T>
find(String hql,String …paramsState of Qatar{ 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(State of Qatar; 53 //查询Java bean
UserInfo–对象 54 Query query = session.createQuery(hql卡塔尔; 55
//给参数赋值 56 for (int i = 0; i < params.length; i++State of Qatar { 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(State of Qatar; 91
System.out.println(“–小编回滚啦—“State of Qatar; 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(State of Qatar; 109 } catch (Exception e卡塔尔 { 110 // TODO: handle
exception 111 e.printStackTrace(State of Qatar; 112 //事务回滚 113 tx.rollback(State of Qatar; 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,OIDState of Qatar; 125 try { 126 //
127 session=SessionFactoryUtils.getSessionFactory(卡塔尔国.getCurrentSession(卡塔尔(قطر‎;
128 tx=session.beginTransaction(State of Qatar; 129 //操作 130 session.delete(o卡塔尔(قطر‎; 131
//提交 132 tx.commit(卡塔尔国; 133 } catch (Exception eState of Qatar { 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 objState of Qatar{ 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(State of Qatar; 161
//事务回滚 162 tx.rollback(卡塔尔(قطر‎; 163 System.out.println(“–我回滚啦—“卡塔尔;
164 } 165 } 166 167 /** 168 * 查询 169 */ 170 public T
get(Class<T> clz, String OIDState of Qatar{ 171 Session session =null; 172
Transaction tx = null; 173 T t=null; 174 try { 175 // 176
session=SessionFactoryUtils.getSessionFactory(State of Qatar.getCurrentSession(卡塔尔国; 177
tx=session.beginTransaction(卡塔尔(قطر‎; 178 //操作 179 t = (TState of Qatarsession.get(getClass(卡塔尔国, OID卡塔尔(قطر‎; 180 //提交 181 tx.commit(卡塔尔; 182 } catch
(Exception eState of Qatar { 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(State of Qatar;//关闭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方法效果相通,可是是懒加载,即在不选取她早先她不会重临对象;
You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图