Hibernate框架入门Demo
2017-02-27 14:31
155 查看
笔者近日空闲时稍微了解了下Hibernate框架,做了一个简单的入门Demo,记录于此,供大家了解一下Hibernate的简单使用,觉得Hibernate框架还是很实用的,遂决定深入学习一下。
环境介绍:
eclipse:eclipse-java-neon-1a-win32-x86_64
mysql:mysql-installer-community-5.6.28.0
hibernate:hibernate-release-5.2.5.Final
eclipse新建java项目,项目中文件目录如下:
![](http://img.blog.csdn.net/20170227141003154?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRG92ZV9Lbm93bGVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
项目中打了3个包,bean、test、util包,bean包中放置待持久化的类,util包中放置常用的工具类,test包中编写包含main方法的java类来进行增删改查操作。
如图所示,此处我编写了两个实体类,Product.java和User.java,源代码如下:
数据库中对应的表为:
![](http://img.blog.csdn.net/20170227141802345?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRG92ZV9Lbm93bGVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](http://img.blog.csdn.net/20170227141819039?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRG92ZV9Lbm93bGVkZ2U=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
对应的映射文件:Product.hbm.xml
对应的映射文件:User.hbm.xml
Hibernate配置文件:
Hibernate工具类:HibernateUtil.java,获取Session、SessionFactory:
至此,框架配置基本完成。
下面,编写测试类,此处仅以User类相关的增删改查操作为例。
AddUser.java:
DeleteUser.java:
GetUser.java:
UpdateUser.java:
备注:此处导入的Hibernate包为lib/required文件夹下的包。
环境介绍:
eclipse:eclipse-java-neon-1a-win32-x86_64
mysql:mysql-installer-community-5.6.28.0
hibernate:hibernate-release-5.2.5.Final
eclipse新建java项目,项目中文件目录如下:
项目中打了3个包,bean、test、util包,bean包中放置待持久化的类,util包中放置常用的工具类,test包中编写包含main方法的java类来进行增删改查操作。
如图所示,此处我编写了两个实体类,Product.java和User.java,源代码如下:
package bean; public class Product { private Integer id; private String name; private String price; private String factory; private String remark; public Product(){ } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getFactory() { return factory; } public void setFactory(String factory) { this.factory = factory; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
package bean; public class User { private Integer id; private String name; private String password; private int age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public User(){ } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
数据库中对应的表为:
对应的映射文件:Product.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="bean.Product" table="product"> <id name="id" column="id" type="int"> <generator class="increment"/> </id> <property name="name" column="name" type="string"/> <property name="price" column="price" type="string"/> <property name="factory" column="factory" type="string"/> <property name="remark" column="remark" type="string"/> </class> </hibernate-mapping>
对应的映射文件:User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="bean.User" table="user"> <id name="id" column="id" type="int"> <generator class="increment"/> </id> <property name="name" type="string" not-null="true"> <column name="name"/> </property> <property name="age" type="int" not-null="true"> <column name="age"/> </property> <property name="password" type="string" not-null="true"> <column name="password"/> </property> </class> </hibernate-mapping>
Hibernate配置文件:
<?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="show_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <mapping resource="bean/Product.hbm.xml"/> <mapping resource="bean/User.hbm.xml"/> </session-factory> </hibernate-configuration>
Hibernate工具类:HibernateUtil.java,获取Session、SessionFactory:
package util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final ThreadLocal<Session>threadLocal = new ThreadLocal<Session>(); private static SessionFactory sessionFactory = null; static{ try{ Configuration configuration = new Configuration().configure(); sessionFactory = configuration.buildSessionFactory(); } catch(Exception e){ System.out.println("创建会话工厂失败"); e.printStackTrace(); } } 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; } public static void rebuildSessionFactory(){ try{ Configuration configuration = new Configuration().configure(); sessionFactory = configuration.buildSessionFactory(); } catch(Exception e){ System.out.println("创建会话工厂失败"); e.printStackTrace(); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void closeSession() throws HibernateException{ Session session = (Session)threadLocal.get(); threadLocal.set(null); if(session!=null){ session.close(); } } }
至此,框架配置基本完成。
下面,编写测试类,此处仅以User类相关的增删改查操作为例。
AddUser.java:
package test; import org.hibernate.Session; import bean.User; import util.HibernateUtil; public class AddUser { public static void main(String[] args){ Session session = null; User user = new User(); user.setAge(24); user.setName("蒋帅"); user.setPassword("jiangshuai1314"); try{ session = HibernateUtil.getSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); } catch(Exception e){ session.getTransaction().rollback(); System.out.println("数据添加失败"); e.printStackTrace(); } finally { HibernateUtil.closeSession(); } } }
DeleteUser.java:
package test; import org.hibernate.Session; import bean.User; import util.HibernateUtil; public class DeleteUser { public static void main(String[] args){ Session session = null; try { session = HibernateUtil.getSession(); session.beginTransaction(); User user = (User)session.get(User.class,new Integer("1")); session.delete(user); session.getTransaction().commit(); } catch (Exception e) { System.out.println("对象装载失败"); e.printStackTrace(); } finally{ HibernateUtil.closeSession(); } } }
GetUser.java:
package test; import org.hibernate.Session; import bean.User; import util.HibernateUtil; public class GetUser { public static void main(String[] args){ try { Session session = null; session = HibernateUtil.getSession(); User user = (User)session.get(User.class, new Integer("1")); System.out.println("UserID:"+user.getId()); System.out.println(user.getName()); System.out.println(user.getPassword()); System.out.println(user.getAge()); } catch (Exception e) { System.out.println("对象加载失败"); e.printStackTrace(); } finally { HibernateUtil.closeSession(); } } }
UpdateUser.java:
package test; import org.hibernate.Session; import bean.User; import util.HibernateUtil; public class UpdateUser { public static void main(String[] args){ Session session = null; try { session = HibernateUtil.getSession(); session.beginTransaction(); User user = (User)session.get(User.class,new Integer("2")); user.setName("Change"); user.setAge(12); session.getTransaction().commit(); } catch (Exception e) { System.out.println("对象装载失败"); e.printStackTrace(); } finally{ HibernateUtil.closeSession(); } } }
备注:此处导入的Hibernate包为lib/required文件夹下的包。
相关文章推荐
- 【菜鸟学框架】——hibernate入门Demo
- 【菜鸟学框架】——hibernate入门Demo
- 微软同步框架入门开篇(附SnapShot快照Demo)
- 微软同步框架(MSF)入门开篇(附SnapShot快照Demo)
- struct hibernate spring 经典框架 搭建 入门实例
- hibernate框架的入门
- 配置hbm的hibernate小demo(入门级小案例ajax+struts2.0+hibernate3.0)
- JAVA框架三剑客 - Struts+Spring+Hibernate快速入门
- hibernate 入门增删改查demo
- openjpa框架入门_Demo概览(一)
- Hibernate入门DEMO
- 【Hibernate框架】Hibernate入门
- 微软同步框架(MSF)入门开篇(附SnapShot快照Demo)
- struct hibernate spring 经典框架 搭建 入门实例
- struct hibernate spring 经典框架 搭建 入门实例
- openjpa框架入门_Demo概览(一)
- 微软同步框架入门开篇(附SnapShot快照Demo)
- 框架学习之Hibernate 第五节 HQL和Criteria查询入门
- struts2.1.8+hibernate3.6.0+spring2.5三大框架整合demo
- hibernate框架入门-逆向工程