Hibernate的CRUD配置及简单使用

参考博客:https://blog.csdn.net/qq_38977097/article/details/81326503

1.首先是jar包,可以在官网下载。

或者点击下面链接下载

链接:https://pan.baidu.com/s/1pW3LHu18nK0E6TzGxHBafg
提取码:cf2o
百度网盘下载的文件中,log文件放在src目录下

2.配置数据库连接的文件,放在src下面hibernate.cfg.xml,我使用的为mysql,如果是sqlserver修改对应的url和driver class即可。

<?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>
        <!-- 配置关于数据库连接的四个项:driverClass  url username password -->
<!--         <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> -->
<!--         <property name="hibernate.connection.url">jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Javaweb</property> -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/javaweb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

        <!-- 可以将向数据库发送的SQL语句显示出来 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 格式化SQL语句 -->
        <property name="hibernate.format_sql">true</property>

        <!-- hibernate的方言 -->    
<!--         <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>  -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property> 
        <!-- 配置hibernate的映射文件所在的位置 -->
        <mapping resource="Model/Student.hbm.xml" />
    </session-factory>
</hibernate-configuration>

3.配置数据库对应表格的属性,其中需要一个Student.java,对应一个mapping,路径在hibernate.cfg.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="Model">
    <!-- 
        name:即实体类的全名
        table:表名
     -->
    <class name="Student" table="t_student" >
        <id name="id" column="id"> 
            <generator class="native"></generator>
        </id>
    
<property name="name" column="name" length="50"></property> <property name="xuehao" column="xuehao" length="50"></property> <property name="sex" column="sex" length="50"></property> <property name="shengri" column="shengri" length="50"></property> <property name="zhuzhi" column="zhuzhi" length="50"></property> </class> </hibernate-mapping>

需要在property中配置实体类对应的属性,即列名

4.下一步就是数据库操作,首先创建一个工具类

HibernateUtils.java
package Util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {
    private static SessionFactory sessionFactory;

    static {
        sessionFactory = new Configuration() 
                .configure() 
                .buildSessionFactory(); 
    }


    //获取全局唯一的SessionFactory
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }


    /从全局唯一的SessionFactory中打开一个Session
    public static Session openSession() {
        return sessionFactory.openSession();
    }

}

5.对数据库的增删改查

StudentDao.java

package Dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import Model.Student;
import Util.HibernateUtils;

public class StudentDao {
    public void add(Student student) {
        // 使用Hibernate的API来完成将Customer信息保存到mysql数据库中的操作
        Session session = HibernateUtils.openSession();
        try {
            Transaction tx = session.beginTransaction(); // 开启事务
            session.save(student);
            tx.commit(); // 提交事务
        } catch (RuntimeException e) {
            session.getTransaction().rollback(); // 回滚事务
            throw e;
        } finally {
            session.close(); // 关闭session
        }
    }
    
    public void delete(int id) {
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            Object student = session.get(Student.class, id); // 要先获取到这个对象
            session.delete(student); // 删除的是实体对象

            tx.commit();
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }
    
    public void update(Student student) {
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(student);// 操作
            tx.commit();
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }
    public Student load(int id) {
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Student student = (Student) session.get(Student.class, id);// 操作
            tx.commit();
            return student;
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }
    
    public List<Student> load() {
        Session session = HibernateUtils.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

            // 方式一:使用HQL语句
            List<Student> list = session.createQuery("FROM Student").list(); // 使用HQL查询

            tx.commit();
            return list;
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
        } finally {
            session.close();
        }
    }
    

}

这样基本的配置及方法已经完成,只要调用对应的方法即可完成crud

 

posted @ 2019-05-19 22:30  星际毁灭  阅读(213)  评论(0编辑  收藏  举报