Hibernate框架入门Demo

笔者近日空闲时稍微了解了下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项目,项目中文件目录如下:

项目中打了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文件夹下的包。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值