博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hibernate详细教程
阅读量:4316 次
发布时间:2019-06-06

本文共 11430 字,大约阅读时间需要 38 分钟。

一、搭建Hibernate环境

1.在src目录下创建hibernate.cfg.xml配置文件

PS:文件的名字不能改!

root
1234
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
org.hibernate.dialect.MySQL5InnoDBDialect
true
    
update
none

2. 编写实体类,以Person类为例

package test.Hibernate.model;import java.util.HashSet;import java.util.Set;public class Person {    @Override    public String toString() {        return "Person [id=" + id + ", name=" + name + "]";    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Set
getAddress() { return address; } public void setAddress(Set
address) { this.address = address; } private int id; private String name; private Set
address = new HashSet
(); }

3.编写Person.hbm.xml实体类配置文件

4.在hibernate.cfg.xml中加入映射信息

5.使用MyEclipse生成SessionFactory

package test.Hibernate.SessionFactory;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;/** * 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 SessionFactory {    /**      * 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
threadLocal = new ThreadLocal
(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private SessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the
SessionFactory 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(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } 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 hibernate configuration * */ public static Configuration getConfiguration() { return configuration; }}

6.编写测试类

package test.Hibernate.dao;import org.hibernate.Session;import org.hibernate.Transaction;import org.junit.Test;import test.Hibernate.SessionFactory.SessionFactory;import test.Hibernate.model.Person;public class PersonDao {    @Test    public void add(){        Session session = SessionFactory.getSession();        Transaction tr = session.beginTransaction();        //----------------------------------------------                Person p = new Person();        p.setName("test");        p.getAddress().add("firstAddr");        p.getAddress().add("secondAddr");        p.getAddress().add("thirdAddr");        p.getAddress().add("fourthAddr");                session.save(p);                //----------------------------------------------        tr.commit();        SessionFactory.closeSession();            }        @Test    public void get(){        Session session = SessionFactory.getSession();        Transaction tr = session.beginTransaction();        //----------------------------------------------                Person p = (Person)session.get(Person.class, 2);        System.out.println(p);                //----------------------------------------------        tr.commit();        SessionFactory.closeSession();    }}

二、主键生成策略

identity:使用数据库的自动增长策略,不是所有数据库都支持,比如oracle就不支持。

sequence:在 DB2,PostgreSQL,Oracle,SAP DB,McKoi 中使用序列(sequence)在使用Oracle数据库时可以使用这一个。

hilo:使用高低位算法生成主键值。只需要一张额外表,所有的数据都支持。

native:根据底层数据库的能力选择 identity、sequence 或者 hilo中的一个。

assigned:手工指定主键值。

uuid:由Hibernate自动生成UUID并指定为主键值。

三、Hibernate映射关系配置

1.一对一映射(以主键关联作为示例)User与IdCard(有外键方)的XML配置:

user

2.一对多,多对一(以Father和Children为例)

3.多对多(以Student和Teacher为例)

PS:有一方的set集合要标明inverse=true(后面会讲)

四、inverse和cascade的区别(个人总结,有不对还望指正)

1.inverse=false在一对多删除时是把孩子的外键设置为null,然后删除父亲,孩子不删除,而casecade=all在一对多删除时是把孩子的外键设置为null,然后删除父亲,然后再删除孩子

2.many to many的时候由一方维护,所以一方要设置inverse=false,但是inverse=true的另一方直接删除会出错,这个时候可以用casecade完成级联删除

3.inverse=false只用于set等集合属性,在one to one关系中可以用casecade完成级联删除

五、使用C3P0连接池

1.需要额外导入3个jar包

2.在hibernate.cfg.xml中加入C3P0配置信息

org.hibernate.connection.C3P0ConnectionProvider
5
20
120
3000

六、HQL语句

@Test    public void HQLSearch(){        Session session = SessionFactory.getSession();        Transaction tr = session.beginTransaction();        //-----------------------------------------                //common search with where//        String hql= "select e.id,e.name from User e where e.id>=5 and e.id<=9";//        Query query = session.createQuery(hql);//        List list = query.list();        //        for(Object o : list){            //            System.out.println(Arrays.toString((Object[])o));//        }                //paging search//        String hql= "select e.id,e.name from User e";//        Query query = session.createQuery(hql);//        query.setFirstResult(0);//        query.setMaxResults(10);//        List list = query.list();        //        for(Object o : list){            //            System.out.println(Arrays.toString((Object[])o));//        }                //search with parameters//        String hql= "select e.id,e.name from User e where id>=? and id<=?";//        Query query = session.createQuery(hql)//                .setParameter(0, 1)//                .setParameter(1, 3);//        List list = query.list();        //        for(Object o : list){            //            System.out.println(Arrays.toString((Object[])o));//        }                //search with parameters whose type is collection//        String hql= "select e.id,e.name from User e where id in (:ids)";//        Query query = session.createQuery(hql)//                .setParameterList("ids",new Object[]{1,2,3,8} );//        List list = query.list();    //        for(Object o : list){            //            System.out.println(Arrays.toString((Object[])o));//        }                        //-----------------------------------------        tr.commit();        SessionFactory.closeSession();    }

七、DML语句

@Test    public void DML(){        Session session = SessionFactory.getSession();        Transaction tr = session.beginTransaction();        //-----------------------------------------        User u = (User)session.get(User.class, 11);                String sql = "update User set name=? where id>?";        int result = session.createQuery(sql)                .setParameter(0, "updated")                .setParameter(1, 10)                .executeUpdate();        System.out.println("count of update:"+result);                //the object's status in session was not updated when the object in database have been changed,so if you want        //to get the updated object in session,you should use method "refresh".        session.refresh(u);                System.out.println(u);                //-----------------------------------------        tr.commit();        SessionFactory.closeSession();    }

 八、开启二级缓存

1. 需要导入以下jar包

2.在hibernate.cfg.xml中加入以下配置

true
org.hibernate.cache.ehcache.EhCacheRegionFactory
true

 九、Hibernate对象状态及转化

转载于:https://www.cnblogs.com/zhujiabin/p/7128420.html

你可能感兴趣的文章
HTML 标签。
查看>>
[bzoj2783][JLOI2012]树_树的遍历
查看>>
2018.10.20 bzoj1068: [SCOI2007]压缩(区间dp)
查看>>
Perl的IO操作(2):更多文件句柄模式
查看>>
由拖库攻击谈口令字段的加密策略
查看>>
Alpha 冲刺 (4/10)
查看>>
并发编程之线程池进程池
查看>>
初始化 Flask 虚拟环境 命令
查看>>
脚本简介jQuery微信开放平台注册表单
查看>>
将PHP数组输出为HTML表格
查看>>
Java中的线程Thread方法之---suspend()和resume() 分类: ...
查看>>
经典排序算法回顾:选择排序,快速排序
查看>>
BZOJ2213 [Poi2011]Difference 【乱搞】
查看>>
c# 对加密的MP4文件进行解密
查看>>
Flask 四种响应类型
查看>>
AOP面向切面编程C#实例
查看>>
怎么让win7右下角只显示时间不显示日期 ?(可行)
查看>>
AngularJs学习笔记-慕课网AngularJS实战
查看>>
数据库三大范式
查看>>
工作总结之二:bug级别、优先级别、bug状态
查看>>