所需jar包:
-
mysql-connector-java-5.1.25-bin.jar
-
hibernate3.jar
-
antlr-2.7.6.jar
-
commons-collections-3.1.jar
-
dom4j-1.6.1.jar
-
hibernate-jpa-2.0-api-1.0.0.Final.jar
-
javassist-3.12.0.GA.jar
-
jta-1.1.jar
-
slf4j-api-1.6.1.jar
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 name="foo">
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql:///hibernate</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="show_sql">true</property>
<!--
<property name="format_sql">true</property>
-->
<!-- create 先删除,再创建
update 不存在就创建,不一样就更新,一样什么都不做,更改表的信息不会起作用
create-drop 初始化时创建表,sessionFactory执行close()时删除
validate 验证表结构域hbm中的是否一致,如果不一致,就抛异常,生产环境下使用
-->
<property name="hbm2ddl.auto">update</property>
<mapping resource="my/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.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'>
<hibernate-mapping package="my.domain">
<class name="User" table="t_user">
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
</hibernate-mapping>
HibernateUtils.java
public class HibernateUtils {
private static SessionFactory sessionFactory;
static {
// Configuration cfg = new Configuration();
// cfg.configure();//读取默认的配置文件
// sessionFactory = cfg.buildSessionFactory();
sessionFactory = new Configuration()//
.configure()//
.buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session openSession() {
return sessionFactory.openSession();
}
}
HelloHibernate.java
public class HelloHibernate {
@Test
public void test() {
Session session = HibernateUtils.openSession();
Transaction tx = null;
try {
User user = new User();
user.setName("张三");
tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();
} catch (RuntimeException e) {
tx.rollback();
throw e;
} finally {
session.close();
}
}
}
public class HelloHibernate {
@Test
public void test() {
Session session = HibernateUtils.openSession();
Transaction tx = null;
try {
User user = new User();
user.setName("张三");
tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();
} catch (RuntimeException e) {
tx.rollback();
throw e;
} finally {
session.close();
}
}
}