在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="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库链接 -->
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<!-- 数据库用户 -->
<property name="connection.username">root</property>
<!-- 数据库密码 -->
<property name="connection.password">root</property>
<!-- 改成MySqlDialect(mysql的sql语句) -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 打印出所有的sql -->
<property name="show_sql">true</property>
<!-- 创建表 -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="cn/domain/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<property name="hbm2ddl.auto">create</property> 用于创建表
根据实体类,向表中添加列和属性值:
映射文件:
<?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>
<class name="cn.domain.User" table="user" catalog="hibernate">
<id name="Id" column="ID">
<generator class="increment"/>
</id>
<property name="Username" column="Username" type="string"/>
<property name="Password" column="Password" type="string"/>
<property name="birthday" column="birthday" type="date"/>
</class>
</hibernate-mapping>
测试类:
package cn.test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.experimental.theories.suppliers.TestedOn;
import cn.domain.User;
public class Test {
public static void main(String[] args) {
Configuration conf = new Configuration().configure();//1、读取配置文件
SessionFactory sf = conf.buildSessionFactory();// 2、创建SessionFactory
Session session = sf.openSession();// 3、打开Session
Transaction tx = null;
try{
tx = session.beginTransaction();// 4、开始一个事务
// 5、持久化操作
User user = new User();
user.setUsername("lisi");
user.setPassword("123456");
user.setBirthday(new Date());
session.save(user);
tx.commit();// 6、 提交事务
System.out.println("End");
}catch(Exception e){
if (null!=tx){tx.rollback();}
e.printStackTrace();
}finally{
session.close();// 7、关闭Session
}
}
}