hibernate简单实例和作用简介
Hibernate的工作流程及原理:
1.读取hibernate.cfg.xml配置文件
2.从hibernate.cfg.xml中读取并解析映射信息(对象与数据库的关联)
3.创建SessionFactory
4.打开Sesssion
5.新建并开启事务Transation
6.persistent operate操作数据,持久化操作(一般是执行hql语句)
7.提交事务
8.关闭Session
9.关闭SesstionFactory
代码实现:
1、hibernate.cfg.xml配置文件
<?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.username">root</property>
<property name="connection.password">1234</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
<!-- 刚接触,先用以后解释 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="javax.persistence.validation.mode">none</property>
</session-factory>
</hibernate-configuration>
2、写实体类,以Student类为例
public class Student{
private int stuId; private String stuName;public int getStuId() { return stuId; } public void setStuId(int stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; }}
3、Student.hbm.xml配置文件
<?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 package="demo.Hibernate.model"> <class name="Student" table="Student">
<!--column和name对应的是Student类属性与数据库属性名--> <id column="stuid" name="sid" type="int"> <generator class="native"></generator> </id> <property name="stuname" column="sname" length="50" type="string"></property> </class> </hibernate-mapping>
Student类xml配置好之后,在hibernate.cfg.xml中加入映射信息<mappingresource="demo/Hibernate/model/Student.hbm.xml"/>
4、使用Eclipse写测试类
- public class Test{
- public static void main(String[] args) {
- //读取hibernate.cfg.xml配置文件
- Configuration cfg = new Configuration().configure();
- //创建SessionFactory
- SessionFactory sessionfactory = cfg.buildSessionFactory();
- //新建session
- Session session = null;
- try {
- session = sessionfactory.openSession();//初始化
- session.beginTransaction();//开始事务
- Student stu = new Student();
- stu.setStuId(1);
- stu.setStuName("小明");
- //在session保存Student对象
- session.save(stu);
- //提交事务
- session.getTransaction().commit();
- }catch(Exception e) {
- e.printStackTrace();
- //回滚事务(防止操作到一半时遇到断电等情况)
- session.getTransaction().rollback();
- }finally {
- if (session != null) {
- if (session.isOpen()) {
- //关闭session
- session.close();
- }
- }
- }
- }
- }
hibernate优点:
1. 对普通JDBC访问数据库的代码做了封装,简化了平时数据访问重复的代码。
2. 使用ORM进行关联,极好的简化DAO层的编码工作。
3. 使用Java反射机制。
4. 性能好,映射的灵活性高,并且支持各种关系数据库,从一对一到多对多的各种复杂关系。