环境: jdk6.0 + MySQL5.0 +Hibrenate3.6
1:搭建环境
导入 Hibernate_Home/lib/required 、 bytecode 、 jpa 下的 所有jar包
2:编写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>
<!--指定数据库的驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 指定连接的数据 库的 url 及其数据库的名称 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate</property>
<!-- 指定连接的用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 指定连接密码 -->
<property name="hibernate.connection.password">52ww</property>
<!-- 指定方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="show_sql">true</property>
<property name="connection.characterEncoding">GBK</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="zhorj/hibernate/test/News.hbml.xml"/>
</session-factory>
</hibernate-configuration>
2:编写 PO 类
package zhorj.hibernate.test;
public class News {
private Integer id;// 消息类的标示符号
private String title; // 标题
private String content;// 内容
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3:编写配置对应的 News.hbm.xml 文件
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- hibernate-mapping 是映射文件的的根 -->
<hibernate-mapping package="zhorj.hibernate.test">
<class name="News" table ="news_table">
<!-- id元素定义之久化类的标志属性 -->
<id name="id">
<!-- 指定 id 主键的生成策略 -->
<generator class="identity"></generator>
</id>
<!-- property 元素定义常规属性 -->
<property name="title"></property>
<property name="content"></property>
</class>
</hibernate-mapping>
4:编写测试类,加载配置文件并测试
package zhourj.hibernate.manager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import zhorj.hibernate.test.News;
public class NewManager {
public static void main(String[] args) {
//
Configuration conf = new Configuration().configure();
// Configuration
SessionFactory sf = conf.buildSessionFactory();
//
Session sess = sf.openSession();
//
Transaction tx = sess.beginTransaction();
News n = new News();
n.setTitle("sqlGBK实验");
n.setContent("希望成功");
sess.save(n);
tx.commit();
sess.close();
sf.close();
}
}