今天用到hibernate操作数据库,虽然学过,但是经常性的会忘记,所以在这里总结一下。希望也能给大家带来帮助。
首先使用eclipse工具,若想快捷创建hibernate文件的话,要下载hibernate tools
在eclipse-->help--->Install New Software里面输入网址:
可以自动检索到hibernate tools工具。点击下载
下面开始正题:
1、File--->new--->other--->搜索hibernate 创建hibernate.cfg.xml文件
2、填写内容
3.填写完毕内容 点击创建。
<?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="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mysqladmin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///db_pb</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping resource=""/>
<mapping resource=""/>
</session-factory>
</hibernate-configuration>
HibernateUtil类
package com.hpu.acm.phone.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory factory;
private HibernateUtil(){}
static
{
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory()
{
return factory;
}
public static Session getSession()
{
return factory.openSession();
}
public static void close(Session session)
{
if(session != null && session.isOpen())
{
session.close();
}
}
public static void closeSessionFactory()
{
if(factory != null)
{
factory.close();
}
}
}