如何使用hibernate开始开发?(三个准备+七个步骤)
准备1: 添加hibernate依赖的jar文件(lib/requried下所有的jar文件)
准备2: 编写实体类和hibernate的映射文件(将实体和表建立关联映射): *.hbm.xml
package cn.zzsxt.entity;
public class Userinfo {
private int userId;
private String userName;
private String userPass;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
}
<?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="实体类全限定类名"
table="映射的表名"
-->
<class name="cn.zzsxt.entity.Userinfo" table="userinfo">
<!--
id节点
name="实体中映射表中主键的属性名 "
type="属性的类型(全限定类名)"
column="映射的字段名称"
-->
<id name="userId" type="java.lang.Integer" column="userId">
<!-- assigned:手工指定 -->
<generator class="assigned"></generator>
</id>
<property name="userName" type="java.lang.String" column="userName"></property>
<property name="userPass"></property>
</class>
</hibernate-mapping>
准备3: 配置hibernate配置文件: 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>
<!-- url -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 用户名 -->
<property name="connection.username">root</property>
<!-- 密码 -->
<property name="connection.password">root</property>
<!-- 方言:dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 打印生成的sql语句 -->
<property name="show_sql">true</property>
<!-- 格式化输出sql语句 -->
<property name="format_sql">true</property>
<!-- 引入映射文件 -->
<mapping resource="cn/zzsxt/entity/Userinfo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
七个步骤
public static void main(String[] args) {
//1.创建Configuration对象,调用configure()解析配置文件hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
//2.创建SessionFactory对象,解析映射文件*.hbm.xml
SessionFactory sessionFactory = cfg.buildSessionFactory();
//3.获取Session,类似于jdbc中Connection
Session session = sessionFactory.openSession();
//4. 开启事务
Transaction tx = session.beginTransaction();
//5.执行持久化操作
Userinfo user = new Userinfo();
user.setUserId(4);
user.setUserName("test3");
user.setUserPass("test3");
session.save(user);
//6.提交事务
tx.commit();
//7.关闭session
session.close();
}