Hibernate配置

1、引入jar包(将文件复制到WebContent/WEB-INFO/lib下)

hibernate配置:

mysql驱动文件:

2、创建配置文件hibernate.cfg.xml

基本配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
  <session-factory>
  <!-- 数据库驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库连接的URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<!-- 数据库连接用户名 -->
<property name="connection.username">root</property>
<!-- 数据库连接密码 -->
<property name="connection.password">123456</property>
<!-- Hibernate方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 自动建表 -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- 映射文件  -->
<mapping resource="com/mr/product/Product.hbm.xml"/>
<mapping resource="com/mr/user/User.hbm.xml"/>
<mapping resource="com/test/Regist.hbm.xml"/>
  </session-factory>

 </hibernate-configuration>

3、编写持久化类user.java

public class User {
int id;
int age;
String name;

String sex;

.......省略set和get方法

}

4、创建映射文件User.hbm.xml(与user.java 映射)

配置如下:

<?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="com.mr.user.User" table="test3">
  <!-- id值 -->
  <id name="id" column="id" type="int">
<generator class="native"/>
</id>
<property name="age" type="int">
<column name="age"/>
</property>
  <property name="name" type="string" length="45">
<column name="name"/>
</property>
<property name="sex" type="string" length="45">
<column name="sex"/>
</property>
  </class> 

 </hibernate-mapping>

5、创建初始化类HibernateInitialize.java

代码如下:

package com.mr.hibernate;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
/**
 * Hibernate初始化类
 *
 */
public class HibernateInitialize {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static SessionFactory sessionFactory = null; // SessionFactory对象
// 静态块
static {
try {
Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
sessionFactory = cfg.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry());
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}


/**
* 获取Session

* @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;
}


/**
* 重建会话工厂
*/
public static void rebuildSessionFactory() {
try {
Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
sessionFactory = cfg
.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
.buildServiceRegistry());
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}


/**
* 获取SessionFactory对象

* @return SessionFactory对象
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}


/**
* 关闭Session

* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close(); // 关闭Session
}
}
}

6、创建"添加"测试类addUser.java

public class AddUser {
public static void main(String[] args) {
Session session = null;                    //声明Session对象
try {
session = HibernateInitialize.getSession();         //获取session
session.getTransaction().begin();                        //开启事务
User user = new User();                                       //实例化User类
user.setAge(10);
user.setName("afj");
user.setSex("girl");

session.save(user);                                              //执行数据库添加操作
session.getTransaction().commit();                    // 提交事务
} catch (Exception e) {
session.getTransaction().rollback();                    //事务回滚
System.out.println("ERROE!!!!");
e.printStackTrace();                                            
}
finally {

HibernateInitialize.closeSession();                        //关闭Session对象
}
}
}

7、查询数据

public static void main(String[] args) {
Session session = null;                    //声明Session对象
try {
session = HibernateInitialize.getSession();         //获取session
session.getTransaction().begin();                        //开启事务
User user = (User)session.get(User.class,new Integer("1"));  //查询id=1      

System.out.println("User:" + user.getName());

                        ....此处省略打印语句

              session.getTransaction().commit();                    // 提交事务

} catch (Exception e) {
session.getTransaction().rollback();                    //事务回滚
System.out.println("ERROE!!!!");
e.printStackTrace();                                            
}
finally {

HibernateInitialize.closeSession();                        //关闭Session对象
}
}

 

8、删除数据

 

public static void main(String[] args) {
Session session = null;
try {
session = HibernateInitialize.getSession();
session.beginTransaction();
                        User user= (User)session.get(User.class, new Integer("1"));
session.delete(product);
session.flush();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("ERROE!!!");
}
finally {
HibernateInitialize.closeSession();
}

}

9、更新数据

public static void main(String[] args) {
Session session = null;
try {
session = HibernateInitialize.getSession();
session.beginTransaction();
Product product = (Product)session.get(Product.class, new Integer("1"));
product.setName("spark零基础");
product.setPrice(10000.99);;
session.flush();            //强制刷新提交
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("!!!!ERROR!!!!");
e.printStackTrace();
}
finally {
HibernateInitialize.closeSession();
}

}

 

10、Hibernate在项目中的应用

    简要参考https://mp.csdn.net/postedit/80807689

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值