1 。 首先是新建一个JAVA工程项目,新建一个lib文件夹,把JAR包添加到lib文件夹
JAR包包括:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate3.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
log4j-1.2.15.jar
mysql-connector-java-5.1.13-bin.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar
2。首先配置hibernate的全局配置文件,必须命名为hibernate.cfg.xml
<!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.url">jdbc:mysql://localhost/hibernate</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 自动打印出SQL语句 -->
<property name="show_sql">true</property>
<!-- 自动创建数据库表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射文件列表 -->
<mapping resource="cn/com/hibernate/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3。 建一个model类User
public class User {
private int id ;
private String username ;
//生成get和set方法
}
4。配置User的对应配置文件User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<!-- 配置实体类与表的关联 -->
<class name="cn.com.hibernate.model.User" table="t_user">
<id name="id">
<generator class="native"/>
</id>
<!-- 属性即是字段 -->
<property name="username"/>
</class>
</hibernate-mapping>
5.创建一个工具类HibernateUtil,专门提供Session
public class HibernateUtil {
private static SessionFactory sessionFactory ;
private HibernateUtil(){
}
//初始化SessionFactory
static {
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory ();
}
//获取session
public static Session getSession(){
return sessionFactory.openSession();
}
}
6.创建一个测试类,保存User到表t_user
public void save01(){
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
User user = new User();
user.setUsername("admin");
session.save(user);
session.getTransaction().commit();
} catch (HibernateException e) {
session.getTransaction().rollback();
e.printStackTrace();
}finally{
session.close();
}
}
查看User已经保存到表里了