欢迎来到study-hard-forever的博客

《Java EE编程技术》综合应用系统开发_作业管理系统_Struts2_Hibernate_设计报告

《Java EE编程技术》综合应用系统开发_作业管理系统_Struts2_Hibernate_设计报告

目录

一、连接数据源: 1

二、hibernate的引入与整合: 4

1. 首先导入必须的jar包: 4

2. 在module中引入hibernate tools工具: 5

3. 接下来即可自动生成配置hibernate.cfg.xml。 5

4. 目录结构: 6

①hibernate.cfg.xml: 7

②StudentEntity: 9

③映射文件StudentEntity.hbm.xml: 11

5. 在项目中采用hibernate方式操作后部分结构变化如下(整合): 13

 

(这里下面的文档结构由于格式原因,序号标题等产生了一些问题,请见谅)

对于struts2相关内容及项目的设计实现流程请参见《Java EE编程技术》综合应用系统开发_作业管理系统_Struts2_设计报告,这里不再赘述,本文主要讲解hibernate的配置和使用以及struts2+hibernate整合思路。

一、连接数据源:

为方便使用我们先连接数据源(即使用IDE方式直接与数据库进行连接,以便于我们更加直观的使用数据库):

选择MySQL输入相应的用户名、密码、URL

(jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai)等配置信息即可。

二、hibernate的引入与整合:

1. 首先导入必须的jar包:

  1. 在module中引入hibernate tools工具:

  1. 接下来即可自动生成配置hibernate.cfg.xml。

 

此时选择自动生成实体和对应的配置文件:

 

  1. 目录结构:

对应的实体类和配置文件已经生成完毕。

(根据软件工程思想,这属于逆向工程)(由于数据库我们已经建立完毕,因此这里采用的是逆向的,如果我们一开始确立的对象是java对象,我们也可以利用hibernate生成对应的数据库表文件,则称为正向):

正向工程:Java实体类 ---->mapping---- > DB数据库关系表

逆向工程:先创建DB数据库关系表,用工具生成生成mapping 和Java实体类。

此时配置文件中内容如下(部分):

①hibernate.cfg.xml:

注意自动生成后的配置文件还需要添加一些属性:

例如:

    <!-- 运行时是否打印 SQL -->

    <property name="show_sql">true</property>

    <!-- 运行时是否格式化 SQL -->

    <property name="format_sql">true</property>

    <!-- 生成数据表的策略 -->

<property name="hbm2ddl.auto">update</property>

......

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.url">
      <![CDATA[jdbc:mysql://localhost:3306/homework?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai]]></property>
    <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    
    <!-- 设定一些其他配置 -->
    <!-- 运行时是否打印 SQL -->
    <property name="show_sql">true</property>
    <!-- 运行时是否格式化 SQL -->
    <property name="format_sql">true</property>
    <!-- 生成数据表的策略 -->
    <property name="hbm2ddl.auto">update</property>
    <!-- 设置 Hibernate 的事务隔离级别 -->
    <property name="connection.isolation">2</property>
    <!-- 删除对象后, 使其 OID 置为 null -->
    <property name="use_identifier_rollback">true</property>
    <!-- 配置 C3P0 数据源 -->
    <property name="hibernate.c3p0.max_size">10</property>
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="c3p0.acquire_increment">2</property>
    <property name="c3p0.idle_test_period">2000</property>
    <property name="c3p0.timeout">2000</property>
    <property name="c3p0.max_statements">1000</property>
    <!-- 设定 JDBC 的 Statement 读取数据的时候每次从数据库中取出的记录条数 -->
    <property name="hibernate.jdbc.fetch_size">1000</property>
    <!-- 设定对数据库进行批量删除,批量更新和批量插入的时候的批次大小 -->
    <!-- 需要关联的 hibernate 映射文件 .hbm.xml -->

    <mapping resource="entity_hibernate/PublishEntity.hbm.xml"/>
    <mapping class="entity_hibernate.PublishEntity"/>
    <mapping resource="entity_hibernate/StudentEntity.hbm.xml"/>
    <mapping class="entity_hibernate.StudentEntity"/>
    <mapping class="entity_hibernate.SubmitEntity"/>
    <mapping resource="entity_hibernate/SubmitEntity.hbm.xml"/>
    <mapping resource="entity_hibernate/TeacherEntity.hbm.xml"/>
    <mapping class="entity_hibernate.TeacherEntity"/>
    <!-- <property name="connection.username"/> -->
    <!-- <property name="connection.password"/> -->

    <!-- DB schema will be updated if needed -->
    <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
  </session-factory>
</hibernate-configuration>

②StudentEntity:

package entity_hibernate;

import javax.persistence.*;
import java.util.Objects;

@Entity
@Table(name = "student", schema = "homework", catalog = "")
public class StudentEntity {
    private int sId;
    private String sPassword;
    private String sName;
    private String sCollege;
    private String sDepartment;
    private Integer sClass;
    private String sSex;
    private String sEmail;

    @Id
    @Column(name = "s_id", nullable = false)
    public int getsId() {
        return sId;
    }

    public void setsId(int sId) {
        this.sId = sId;
    }

    @Basic
    @Column(name = "s_password", nullable = true, length = 20)
    public String getsPassword() {
        return sPassword;
    }

    public void setsPassword(String sPassword) {
        this.sPassword = sPassword;
    }

    @Basic
    @Column(name = "s_name", nullable = true, length = 20)
    public String getsName() {
        return sName;
    }

    public void setsName(String sName) {
        this.sName = sName;
    }

    @Basic
    @Column(name = "s_college", nullable = true, length = 30)
    public String getsCollege() {
        return sCollege;
    }

    public void setsCollege(String sCollege) {
        this.sCollege = sCollege;
    }

    @Basic
    @Column(name = "s_department", nullable = true, length = 30)
    public String getsDepartment() {
        return sDepartment;
    }

    public void setsDepartment(String sDepartment) {
        this.sDepartment = sDepartment;
    }

    @Basic
    @Column(name = "s_class", nullable = true)
    public Integer getsClass() {
        return sClass;
    }

    public void setsClass(Integer sClass) {
        this.sClass = sClass;
    }

    @Basic
    @Column(name = "s_sex", nullable = true, length = 10)
    public String getsSex() {
        return sSex;
    }

    public void setsSex(String sSex) {
        this.sSex = sSex;
    }

    @Basic
    @Column(name = "s_email", nullable = true, length = 30)
    public String getsEmail() {
        return sEmail;
    }

    public void setsEmail(String sEmail) {
        this.sEmail = sEmail;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StudentEntity that = (StudentEntity) o;
        return sId == that.sId &&
                Objects.equals(sPassword, that.sPassword) &&
                Objects.equals(sName, that.sName) &&
                Objects.equals(sCollege, that.sCollege) &&
                Objects.equals(sDepartment, that.sDepartment) &&
                Objects.equals(sClass, that.sClass) &&
                Objects.equals(sSex, that.sSex) &&
                Objects.equals(sEmail, that.sEmail);
    }

    @Override
    public int hashCode() {
        return Objects.hash(sId, sPassword, sName, sCollege, sDepartment, sClass, sSex, sEmail);
    }
}

③映射文件StudentEntity.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>

    <class name="entity_hibernate.StudentEntity" table="student" schema="homework">
        <id name="sId">
            <column name="s_id" sql-type="int(11)"/>
        </id>
        <property name="sPassword">
            <column name="s_password" sql-type="varchar(20)" length="20" not-null="true"/>
        </property>
        <property name="sName">
            <column name="s_name" sql-type="varchar(20)" length="20" not-null="true"/>
        </property>
        <property name="sCollege">
            <column name="s_college" sql-type="varchar(30)" length="30" not-null="true"/>
        </property>
        <property name="sDepartment">
            <column name="s_department" sql-type="varchar(30)" length="30" not-null="true"/>
        </property>
        <property name="sClass">
            <column name="s_class" sql-type="int(10)" not-null="true"/>
        </property>
        <property name="sSex">
            <column name="s_sex" sql-type="varchar(10)" length="10" not-null="true"/>
        </property>
        <property name="sEmail">
            <column name="s_email" sql-type="varchar(30)" length="30" not-null="true"/>
        </property>
    </class>
</hibernate-mapping>

对于上述配置完毕后,我们只需修改dao层的一些方法即可,对于简单的SQL语句我们可以直接采用native方式进行,无需修改。

  1. 在项目中采用hibernate方式操作后部分结构变化如下(整合):

这里为了降低耦合度,dao层采用接口方式,分别利用JDBC或者c3p0进行实现,这里引入hibernate后又有了不同的实现方式,但是由于接口的透明性,我们隐藏了对上层服务的实现细节,因此如果整合hibernate只需增加更改hibernate实现即可。

 

需要注意的内容HibernateUtil:

package db_util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public final class HibernateUtil {
   private static SessionFactory sessionFactory;
   private static ThreadLocal<Session> session = new ThreadLocal<Session>();

   private HibernateUtil() {
   }

   static {
      // 第一步:读取Hibernate的配置文件 hibernamte.cfg.xml文件
      Configuration configuration = new Configuration().configure();
      // 第二步:创建服务注册构建器对象,通过配置对象中加载所有的配置信息
      StandardServiceRegistryBuilder regbulider = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
      // 创建注册服务
      ServiceRegistry serviceRegistry = regbulider.build();
      // 第三步:创建会话工厂
      sessionFactory = configuration.buildSessionFactory(serviceRegistry);

   }

   public static Session getThreadLocalSession() {
      Session s = (Session) session.get();
      if (s == null) {
         s = sessionFactory.openSession();
         session.set(s);
      }
      return s;
   }  

   public static void closeSession() {
      Session s = (Session) session.get();
      if (s != null) {
         s.close();
         session.set(null);
      }
   }

}

本项目无需采用Hibernate的高级特性,也无需使用HQL语言进行数据库操作,但是使用hibernate可以大大简化实现过程。

hibernate为我们提供了大量接口,除上述接口外还有如Transaction接口:

commit():提交事务,transaction.commit()。

rollback():撤销事务操作,transaction.rollback()。

wasCommitted():检查事务是否提交,transaction.wasCommitted()。

 

Query接口等等:

使用Query接口提供的方法,可以方便地查询数据库中的数据,它主要通过HQL(Hibernate Query Language)查询数据。

 

posted @ 2021-01-20 00:47  study-hard-forever  阅读(116)  评论(0编辑  收藏  举报