欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Hibernate实现批量添加数据的方法

程序员文章站 2024-03-11 10:06:31
本文实例讲述了hibernate实现批量添加数据的方法。分享给大家供大家参考,具体如下: 1.᥿...

本文实例讲述了hibernate实现批量添加数据的方法。分享给大家供大家参考,具体如下:

1.hibernate_016_batchadddata程序目录结构:

Hibernate实现批量添加数据的方法

2.lib目录下所引入的jar包:

Hibernate实现批量添加数据的方法

3.medicinedao.java源代码:

package com.xqh.dao;
import java.util.list;
import org.hibernate.session;
import com.xqh.model.medicine;
import com.xqh.util.hibernateutil;
/**
 * 药品数据库操作类
 *
 */
public class medicinedao {
  /**
   * 批量保存药品
   *
   * @param ms
   *      list集合
   */
  public void savemedicines(list<medicine> ms) {
    session session = null;
    if (ms != null && ms.size() > 0) {
      try {
        session = hibernateutil.getsession(); // 获取session
        session.begintransaction(); // 开启事物
        medicine medicine = null; // 创建药品对象
        // 循环获取药品对象
        for (int i = 0; i < ms.size(); i++) {
          medicine = (medicine) ms.get(i); // 获取药品
          session.save(medicine); // 保存药品对象
          // 批插入的对象立即写入数据库并释放内存
          if (i % 10 == 0) {
            session.flush();
            session.clear();
          }
        }
        session.gettransaction().commit(); // 提交事物
      } catch (exception e) {
        e.printstacktrace(); // 打印错误信息
        session.gettransaction().rollback(); // 出错将回滚事物
      } finally {
        hibernateutil.closesession(session); // 关闭session
      }
    }
  }
}

4.medicine.java源代码:

package com.xqh.model;
/**
 * 药品持久化类
 */
public class medicine {
  private integer id;       //id号
  private string name;      //药品名称
  private double price;      //价格
  private string factoryadd;   //出厂地址
  public integer getid() {
    return id;
  }
  public void setid(integer id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public double getprice() {
    return price;
  }
  public void setprice(double price) {
    this.price = price;
  }
  public string getfactoryadd() {
    return factoryadd;
  }
  public void setfactoryadd(string factoryadd) {
    this.factoryadd = factoryadd;
  }
}

5.medicine.hbm.xml源代码:

<?xml version="1.0"?>
<!doctype hibernate-mapping public
  "-//hibernate/hibernate mapping dtd 3.0//en"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.xqh.model.medicine" table="tb_medicine_batch">
    <id name="id">
      <generator class="native"/>
    </id>
    <property name="name" not-null="true" length="200" />
    <property name="price" not-null="true"/>
    <property name="factoryadd" length="200"/>
  </class>
</hibernate-mapping>

6.savemedicine.java源代码:

package com.xqh.servlet;
import java.io.ioexception;
import java.util.arraylist;
import java.util.list;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import com.xqh.dao.medicinedao;
import com.xqh.model.medicine;
public class savemedicine extends httpservlet {
  private static final long serialversionuid = 3743334039515411666l;
  public void dopost(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    // 药品名称
    string names[] = request.getparametervalues("name");
    // 价格
    string prices[] = request.getparametervalues("price");
    // 出厂地址
    string adds[] = request.getparametervalues("factoryadd");
    // 有效性判断
    if(names != null && prices != null && adds != null){
      if(names.length == prices.length && names.length == adds.length){
        // 实例化一个list集合
        list<medicine> ms = new arraylist<medicine>();
        medicine m = null; // 药品对象
        // 依次实例化药品对象并添加到集合中
        for (int i = 0; i < names.length; i++) {
          m = new medicine(); // 实例化药品
          // 对属性赋值
          m.setname(names[i]);
          m.setprice(double.parsedouble(prices[i]));
          m.setfactoryadd(adds[i]);
          ms.add(m); // 添加到集合中
        }
        // 实例化medicinedao对象
        medicinedao dao = new medicinedao();
        dao.savemedicines(ms); // 批量保存药品
        request.setattribute("info", "药品信息保存成功!!!");
      }
    }
    // 转发到result.jsp页面
    request.getrequestdispatcher("result.jsp").forward(request, response);
  }
}

7.characterencodingfilter.java源代码:

/*
 * to change this template, choose tools | templates
 * and open the template in the editor.
 */
package com.xqh.util;
import java.io.ioexception;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
/**
 * 字符编码过滤器
 */
public class characterencodingfilter implements filter{
  protected string encoding = null;
  protected filterconfig filterconfig = null;
  public void init(filterconfig filterconfig) throws servletexception {
    this.filterconfig = filterconfig;
    this.encoding = filterconfig.getinitparameter("encoding");
  }
  public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {
    if (encoding != null) {
      request.setcharacterencoding(encoding);
      response.setcontenttype("text/html; charset="+encoding);
    }
    chain.dofilter(request, response);
  }
  public void destroy() {
    this.encoding = null;
    this.filterconfig = null;
  }
}

8.hibernateutil.java源代码:

package com.xqh.util;
import org.hibernate.hibernateexception;
import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
/**
 * hibernate初始化类,用于获取session、sessionfactory 及关闭session
 */
public class hibernateutil {
  // sessionfactory对象
  private static sessionfactory factory = null;
  // 静态块
  static {
    try {
      // 加载hibernate配置文件
      configuration cfg = new configuration().configure();
      // 实例化sessionfactory
      factory = cfg.buildsessionfactory();
    } catch (hibernateexception e) {
      e.printstacktrace();
    }
  }
  /**
   * 获取session对象
   * @return session对象
   */
  public static session getsession() {
    //如果sessionfacroty不为空,则开启session
    session session = (factory != null) ? factory.opensession() : null;
    return session;
  }
  /**
   * 获取sessionfactory对象
   * @return sessionfactory对象
   */
  public static sessionfactory getsessionfactory() {
    return factory;
  }
  /**
   * 关闭session
   * @param session对象
   */
  public static void closesession(session session) {
    if (session != null) {
      if (session.isopen()) {
        session.close(); // 关闭session
      }
    }
  }
}

9.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="dialect">org.hibernate.dialect.mysqldialect</property>
    <!-- 数据库连接 -->
    <property name="connection.url">jdbc:mysql://localhost:3306/learn</property>
    <!-- 数据库连接用户名 -->
    <property name="connection.username">root</property>
    <!-- 数据库连接密码 -->
    <property name="connection.password">1120</property>
    <!-- 数据库驱动 -->
    <property name="connection.driver_class">com.mysql.jdbc.driver</property>
    <!-- 打印sql语句 -->
    <property name="show_sql">true</property>
    <!-- 自动建表 -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- 映射文件 -->
    <mapping resource="com/xqh/model/medicine.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

10.log4j.properties源代码:

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.consoleappender
log4j.appender.stdout.target=system.out
log4j.appender.stdout.layout=org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern=%d{absolute} %5p %c{1}:%l - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.fileappender
#log4j.appender.file.file=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.patternlayout
#log4j.appender.file.layout.conversionpattern=%d{absolute} %5p %c{1}:%l - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootlogger=warn, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log hql query parser activity
#log4j.logger.org.hibernate.hql.ast.ast=debug
### log just the sql
#log4j.logger.org.hibernate.sql=debug
### log jdbc bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
#log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log hql parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log jdbc resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using drivermanagerconnectionprovider ###
#log4j.logger.org.hibernate.connection.drivermanagerconnectionprovider=trace

11.index.jsp源代码:

<%@ page language="java" contenttype="text/html" pageencoding="gbk"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
  <head>
    <title>批量添加药品信息</title>
    <style type="text/css">
td {
  background: #ebebeb;
  font-family: verdana;
  font-size: 12px;
  background-color: #ebebeb;
  color: black;
  line-height: 20px;
  height: 30px;
}
</style>
    <script type="text/javascript">
    function add(){
      var a = document.getelementbyid("a");
      var b = document.getelementbyid("b");
      b.innerhtml += a.innerhtml;
    }
    function reduce() {
      var a = document.getelementbyid("a");
      var b = document.getelementbyid("b");
      var stra = a.innerhtml;
      var strb = b.innerhtml;
      b.innerhtml = strb.substring(0, strb.length - stra.length);
    }
    function save(formname){
      for(i=0;i<formname.length;i++){
        if(formname.elements[i].value==""){
          alert("请填写完整信息!");
          return false;
        }
      }
    }
  </script>
  </head>
  <body onload="add()">
    <form action="savemedicine" method="post"
      onsubmit="return save(this);">
      <table align="center" border="0" cellpadding="3" cellspacing="1"
        width="600">
        <tr>
          <td align="center">
            <br>
            <h1>
              批量添加药品信息
            </h1>
          </td>
        </tr>
        <tr>
          <td>
            <div id="b"></div>
          </td>
        </tr>
        <tr>
          <td>
            <input type="button" value="添加一行 " onclick="add()">
            <input type="button" value="减少一行" onclick="reduce()">
            <input type="submit" value="批量添加到数据库">
          </td>
        </tr>
      </table>
    </form>
    <div id="a" style="display: none">
      <table align="center" border="0">
        <tr>
          <td>
            名称:
          </td>
          <td>
            <input type="text" name="name" size="13">
          </td>
          <td>
            单价:
          </td>
          <td>
            <input type="text" name="price" size="13">
          </td>
          <td>
            厂址:
          </td>
          <td>
            <input type="text" name="factoryadd" size="30">
          </td>
        </tr>
      </table>
    </div>
  </body>
</html>

12.result.jsp源代码:

<%@ page language="java" contenttype="text/html" pageencoding="gbk"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
 <head>
  <title>结果信息</title>
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
 </head>
 <body>
  <div align="center">
    <font color="red" size="12px;" style="font-weight: bold;">
      ${info}
    </font>
    <br><br><br><br>
    <a href="index.jsp">返回</a>
  </div>
 </body>
</html>

13.数据表tb_medicine_batch结构:

Hibernate实现批量添加数据的方法

14.程序运行结果截图:

Hibernate实现批量添加数据的方法

希望本文所述对大家基于hibernate框架的java程序设计有所帮助。