修改 hibernate.cfg.xml为
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<!-- 指定方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 数据库驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库url -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate02_1514010311</property>
<!-- 数据库连接用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库连接密码 -->
<property name="hibernate.connection.password">0x3137</property>
<!-- 将hibernate生成的sql语句打印到控制台 -->
<property name="hibernate.show_sql">true</property>
<!-- 将hibernate生成的sql语句格式化(语法缩进) -->
<property name="hibernate.format_sql">true</property>
<!-- 配置getCurrentSession -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 配置sql语句生成方式 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/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>
<!-- name: 完整类名 table:数据库表名 -->
<class name="com.domain.User" table="user">
<!-- id配置表的主键 name代表表中属性 -->
<id name="id" column="id">
<!-- 主键生成策略 -->
<generator class="native"></generator>
</id>
<property name="username" column="username" type="string"></property>
<property name="password" column="password" type="string"></property>
<property name="age" column="age" type="integer"></property>
</class>
</hibernate-mapping>
测试
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.alanlee.entity.Student;
public class StudentTest
{
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
public void setUp() throws Exception
{
Configuration config = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
.buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
public void tearDown() throws Exception
{
transaction.commit();
session.close();
sessionFactory.close();
}
public void testSaveStudent()
{
Student student = new Student();
student.setSid(1);
student.setName("Sam");
student.setSex("man");
student.setBirthday(new Date());
student.setAddress("MIT");
session.save(student);
}
}