Hibernate是对JDBC进行了轻量级封装的ORM框架,充当项目的持久层
Hibernate依赖的库:
创建一个工程,添加jar包:
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="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">jdbc:mysql://localhost/mysql</property>
<property name="connection.username">root</property>
<property name="connection.password">sxh</property>
<!-- 为true表示将Hibernate发送给数据库的sql显示出来-->
<property name="show_sql">true</property>
<!-- 数据库方言 -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<mapping resource="cn/haidashu/pojo/Users.hbm.xml" />
</session-factory>
</hibernate-configuration>
Users.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>
<class name="cn.haidashu.pojo.Users" table="users">
<!-- 主键策略 -->
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="pwd"/>
</class>
</hibernate-mapping>
Users类:
package cn.haidashu.pojo;
public class Users {
private int id;
private String name;
private String pwd;
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;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
Test类:
package cn.haidashu.pojo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
// 保存数据
Users user = new Users();
user.setName("Zoe");
user.setPwd("335666");
session.save(user);
System.out.println("1");
// 提交事务
// tx.commit();
// session.close();
session.getTransaction().commit();
session.close();
sf.close();
}
}
代码地址:http://pan.baidu.com/s/1nve1E8T