hibernate配置文件:hibernate.cfg.xmljava
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">mysql
<hibernate-configuration>
<session-factory name="foo">
<!-- 配置数据库信息 -->
<property name="hibernate.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="hibernate.connection.password">root</property>sql
<!-- 其余配置 -->
<property name="hibernate.show_sql">true</property><!--显示sql默认是false不显示SQL语句-->
<property name="hibernate.format_sql">false</property>
<!--
create:先删除,再建立
update:若是表不存在就建立,不同就更新,同样就什么都不作。
create-drop:初始化时建立表,SessionFactory执行close()时删除表。
validate:验证表结构是否一致,若是不一致,就抛异常。
-->
<property name="hbm2ddl.auto">update</property>
<!-- 导入映射文件 -->
<mapping resource="cn/itcast/a_helloworld/User.hbm.xml"/>数据库
</session-factory>
</hibernate-configuration>session
映射文件:User.hbm.xmlapp
<?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="cn.itcast.a_helloworld">
<!--name:实体类名,table:数据库数据表-->
<class name="User" table="t_user">
<id name="id" type="int" column="id">
<generator class="native"/><!--native:自增加-->
</id>
<!--column:列名-->
<property name="name" type="string" column="name" length="20"/>
</class>
</hibernate-mapping>ide
User.javaui
package cn.itcast.a_helloworld;
/**
* 实体
*/
public class User {
private int id;
private String name;this
public int getId() {
return id;
}url
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[User: id=" + id + ", name=" + name + "]";
}
}
App.java:
package cn.itcast.a_helloworld;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class App {
private static SessionFactory sessionFactory;
static {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml"); // 读取指定的主配置文件
sessionFactory = cfg.buildSessionFactory(); // 根据生成Session工厂
}
@Test
public void testSave() throws Exception {
User user = new User();
user.setName("张三");
// 保存
Session session = sessionFactory.openSession(); // 打开一个新的Session
Transaction tx = session.beginTransaction(); // 开始事务
session.save(user);
tx.commit(); // 提交事务
session.close(); // 关闭Session,释放资源
}
@Test
public void testGet() throws Exception {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = (User) session.get(User.class, 1); // 获取
System.out.println(user);
tx.commit(); session.close(); } }