Hibernate
1.通过Configuration对象读取并解析配置文件
2.读取并解析映射信息,创建SessionFaction对象
3.打开session
4.创建事务Transaction
5.持久化操作,对对象进行CRUD操作
6.提交事务
7.关闭session和SssionFaction对象
添加Hibernate的jar包与mysql的jar包
Hibernate映射文件:Users.hbm.xml 与实体类同包
<?xml version="1.0"?>
<hibernate-mapping>
<!--实体类与表的映射-->
<class name="com.zhongke.pojo.Users" table="users">
<!--主键-->
<id name="userId" column="user_id">
<!--主键生成策略-->
<generator class="identity"></generator>
</id>
<!--非主键-->
<property name="userName" column="user_name" type="java.lang.String"></property>
<property name="userPass" column="user_Pass" type="java.lang.String"></property>
</class>
</hibernate-mapping>
Hibernate配置文件:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/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://127.0.0.1/hinname?useUnicode=true&characterEncoding=utf-8</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- SQL dialect 数据库方言-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--显示生成的SQL语句-->
<property name="show_sql">true</property>
<!--ORM映射文件-->
<mapping resource="com/zhongke/pojo/Users.hbm.xml"/>
</session-factory>
</hibernate-configuration>
创建工具类HibernateSessionFactory
public class HibernateSessionFactory{
private static SessionFactory sessionFactory=null;
static{
try{
Configuration configuration=new Configuration().configure();
sessionFactory=configuration.buildSessionFactory();
}catch(HibernateException e){
e.printStackTeace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
创建测试类
public class Test{
public void main(String args[]){
Session session=HibernateSessionFactory.getSessionFactory().openSession();
Transaction tran=session.getTransaction();
tran.begin();
Users user=new Users();
user.setUserName(“xiaoming”);
user.setUserPass(“12312”);
session.save(user);
tran.commit();
session.close();
}
}