【笔记】Hibernate框架系列 [ 1 ]
2017-01-15 10:23
351 查看
众里寻TA千百度,蓦然回首,那人却在,灯火阑珊处!遇到,即为有缘,朋友你好!
温馨提示:已配置数据库自动建表,只需提供数据库实例!支持源码下载哦!
温馨提示:已配置数据库自动建表,只需提供数据库实例!支持源码下载哦!
【entity】
package com.athl.entity; public class Person { private Integer id; private String pname; private int age; public Person() { } //创建带参构造器(无id),id在数据库是自动生成的。 public Person(String pname, int age) { this.pname = pname; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [id=" + id + ", pname=" + pname + ", age=" + age + "]"; } }
【Person.hbm.xml】
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- F2查看hibernate-mapping --> <hibernate-mapping package="com.athl.entity"> <!-- 映射文件的作用:1.类到表的映射;2.属性到字段的映射 --> <class name="com.athl.entity.Person" table="h_person"> <!-- 如果想让类里的属性名与表里的字段名相同,去掉column即可 --> <id name="id" column="pid"> <!-- 主键生成策略 increment:Hibernate自己维护主键,添加前,先查id最大值. identity:数据库使用自身的自增长维护主键. sequence:Oracle/DB2/PostgreSQL等数据库中创建一个序列. native:开发分布式系统,多个不同数据库,Hibernate自动匹配使用identity/sequence. uuid:通用唯一识别码,保证多个数据库id的唯一性.缺点:1.占内存;2.查询效率的 assigned:程序员自行设置id,通过setId(). --> <generator class="native"/> </id> <property name="pname" column="pname" /> <property name="age" column="age" /> </class> </hibernate-mapping>
【hibernate.cfg.xml】
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/athl_hibernate?useUnicode=true&characterEncoding=UTF-8</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 数据源:数据库连接池(暂用C3P0默认配置).若不配置,即用Hibernate内置数据源(官方不推荐) --> <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!-- 注册当前Session上下文:保证同一线程中获取到的Session是同一个Session --> <property name="hibernate.current_session_context_class">thread</< 4000 span class="hljs-title">property> <!-- 自动建表 create:没运行一次,就删除旧表,建新表;update:更新数据--> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 显示SQL --> <property name="hibernate.show_sql">true</property> <!-- 格式化SQL --> <property name="hibernate.format_sql">true</property> <!-- 注册映射文件 --> <mapping resource="com/athl/entity/Person.hbm.xml"/> </session-factory> </hibernate-configuration>
【HibernateUtils 】
package com.athl.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { /** * 基于SessionFactory是线程安全的重量级对象, * 其创建与销毁时系统开销大,又是单例的特点, * SessionFactory对象一般不手工关闭,而是在应用结束是自动将其销毁。 * 因此,SessionFactory不用进行close()关闭。 */ private static SessionFactory sf; public static SessionFactory getSessionFactory() { if (sf == null || sf.isClosed()) { //加载主配置文件,创建Session工厂 sf = new Configuration().configure().buildSessionFactory(); //加载自定义user-defined.cfg.xml(了解) //sf = new Configuration().configure("user-defined.cfg.xml").buildSessionFactory(); } return sf; } /* * 获取Session对象(两种方式) * 1.sf.openSession();创建一个新的Session对象 * 2.sf.getCurrentSession();获取当前线程中的Session对象 * 注意:使用第二种方式要在主配置文件中【注册当前Session上下文】且获取的Session自动关闭,无需手动关闭! * <property name="hibernate.current_session_context_class">thread</property> * 区别: * a.获取的对象 * 1 每执行一次该方法,获取的都是一个新的Session对象; * 2 无论执行多少次该方法,只要在同一线程中,获取的都是同一个Session对象. * b.对象的关闭 * 1 必须手动关闭Session对象;2 自动关闭. * c.环境的注册 * 1 不需要;2 需要. * d.查询的事务的支持 * 1 查询可以不再事务内执行;2 必须在事务内执行. */ public static Session getSession() { return getSessionFactory().getCurrentSession(); } //测试 public static void main(String[] args) { System.out.println(HibernateUtils.getSession()); } }
【test】
package com.athl.test; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.athl.entity.Person; import com.athl.utils.HibernateUtils; public class Mytest { /* * 同一个方法中CUD默认执行顺序:增、改、删 */ /** * 添加 */ @Test public void save(){ //获取Session对象 Session session=HibernateUtils.getSession(); Person p=new Person("张三",18);//瞬时态(堆内存) Transaction t =null; try { //开启事务 t = session.beginTransaction(); //执行save操作 /*save()方法执行过程: * Hibernate通过自己的方式得到表中下一个id,初始化要插入的对象的id属性, * 将对象的id作为key,对象的引用作为value,放入session缓存中. * Session缓存的本质,实际就是一个Map,其key为被管理对象的id,value为对象的引用. * 也就是说,只有id属性不为null的对象才可能被Session管理. * 一个对象被Session管理,就意味着,这个对象被放到了Session缓存这个Map中. * * 对象状态及存在位置: * 瞬时态: 堆内存 * 持久态: 堆内存 DB Session * 游离态: 堆内存 DB * 无名态: DB (方便理解,官方无此状态) * 当对象由持久态转为游离(托管)状态时,实际就是将Map中的该对象删除了. * 当对象由游离(托管)状态转为持久态时,实际就是将该对象放到了Session缓存这个Map中 */ session.save(p); //session.persist(p); //事务提交 t.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 t.rollback(); } } /** * 删除 */ //@Test public void delete(){ //获取Session对象 Session session=HibernateUtils.getSession(); Person p=new Person(); p.setId(1); Transaction t =null; try { //开启事务 t = session.beginTransaction(); //执行delete操作(根据对象的id删除) session.delete(p); //事务提交 t.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 t.rollback(); } } /** * 修改 */ //@Test public void update(){ //获取Session对象 Session session=HibernateUtils.getSession(); Person p=new Person("李四",26); p.setId(3); Transaction t =null; try { //开启事务 t = session.beginTransaction(); //执行update操作(根据对象的id修改) session.update(p); //事务提交 t.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 t.rollback(); } } /** * 添加或修改 * 操作对象存在id,则执行update;不存在,则执行添加 */ //@Test public void saveOrUpdate(){ //获取Session对象 Session session=HibernateUtils.getSession(); Person p=new Person("李四",26); p.setId(3); Transaction t =null; try { //开启事务 t = session.beginTransaction(); //执行update操作(根据对象的id修改) session.saveOrUpdate(p); //事务提交 t.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 t.rollback(); } } /** * 查询 */ //@Test public void get(){ //获取Session对象 Session session=HibernateUtils.getSession(); Transaction t =null; try { //开启事务 t = session.beginTransaction(); //执行get操作(根据对象的id查询) Person person = (Person) session.get(Person.class, 3); //Person person = (Person) session.load(Person.class, 3); /*区别(日后再总结): * get()方法,若数据库该id不存在,返回null * load()方法,若数据库该id不存在,抛出异常 */ System.out.println("==person=="+person); //事务提交 t.commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 t.rollback(); } } }
源码下载:http://download.csdn.net/detail/jul_11th/9737944
谢谢支持!
相关文章推荐
- 框架Hibernate笔记系列 基础Session
- 【笔记】Hibernate框架系列 [ 2 ]
- WEB框架研究笔记八(HIBERNATE)
- 学习Windows Mobile开发系列笔记(win32基本程序框架)
- (五) 畸变矫正—让世界不在扭曲 【计算机视觉学习笔记--双目视觉几何框架系列】
- 张正友标定法 【计算机视觉学习笔记--双目视觉几何框架系列】
- 图像坐标:我想和世界坐标谈谈(A) 【计算机视觉学习笔记--双目视觉几何框架系列】
- 学习笔记之 O/R 映射技术的王牌Hibernate框架
- Hibernate学习笔记--第一个Hibernate框架程序
- (二)图像坐标:我想和世界坐标谈谈(B) 【计算机视觉学习笔记--双目视觉的几何框架系列】
- (一)图像坐标:我想和世界坐标谈谈(A) 【计算机视觉学习笔记--双目视觉几何框架系列】
- (七)立体标定与立体校正 【计算机视觉学习笔记--双目视觉几何框架系列】
- [原]Java web学习系列之 Java web开发中的Hibernate对象关系映射框架
- Hibernate in action阅读笔记-吵吵冷饭-框架
- Hibernate框架笔记(下)
- (三)张正友标定法 【计算机视觉学习笔记--双目视觉几何框架系列】
- 学习Windows Mobile开发系列笔记(win32基本程序框架)
- Hibernate框架笔记(上)
- 学习Windows Mobile开发系列笔记(win32基本程序框架)
- (八)走向三维 【计算机视觉学习笔记--双目视觉几何框架系列】