User.java

package com.eduask.htl;

public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


 

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 package="com.eduask.htl">

<class name="User" table="t_user">
<id name="id" type="java.lang.Integer" column="id" >
<generator class="identity"/>
</id>
<property name="name" type="java.lang.String" column="name" length="20"/>
</class>
</hibernate-mapping>


 

@Test

public void addUser() {
User user=new User();
user.setName("dd");

// 获取session
Session session = HibernateUtil.getSession();
// 开启事务
Transaction ts = session.beginTransaction();
try {
session.save(user);
ts.commit();
} catch (Exception e) {
e.printStackTrace();
ts.rollback();
} finally {
session.close();
}

}


HibernateUtil

package com.eduask.htl.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static{
//加载hibernate主配置文件
Configuration confg=new Configuration();
confg.configure();
sessionFactory=confg.buildSessionFactory();
}
//创建session
public static Session getSession(){
return sessionFactory.openSession();
}
}


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_20120328</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">hyy</property>
<!-- 其他配置 -->
<property name="hibernate.show_sql">true</property>
<mapping resource="com/eduask/htl/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>