在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

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

2016-8-29 13:22| 发布者: zhangjf| 查看: 680| 评论: 0

摘要: 本文实例讲述了Hibernate实现批量添加数据的方法。分享给大家供大家参考,具体如下: 1.????????Hibernate_016_BatchAddData程序目录结构: 2.lib目录下所引入的jar包: 3.MedicineDao.java源代码: package com.x ...

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

1.????????Hibernate_016_BatchAddData程序目录结构:

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

3.MedicineDao.java源代码:

  1. package com.xqh.dao;
  2. import java.util.List;
  3. import org.hibernate.Session;
  4. import com.xqh.model.Medicine;
  5. import com.xqh.util.HibernateUtil;
  6. /**
  7. * 药品数据库操作类
  8. *
  9. */
  10. public class MedicineDao {
  11. /**
  12. * 批量保存药品
  13. *
  14. * @param ms
  15. * List集合
  16. */
  17. public void saveMedicines(List<Medicine> ms) {
  18. Session session = null;
  19. if (ms != null && ms.size() > 0) {
  20. try {
  21. session = HibernateUtil.getSession(); // 获取Session
  22. session.beginTransaction(); // 开启事物
  23. Medicine medicine = null; // 创建药品对象
  24. // 循环获取药品对象
  25. for (int i = 0; i < ms.size(); i++) {
  26. medicine = (Medicine) ms.get(i); // 获取药品
  27. session.save(medicine); // 保存药品对象
  28. // 批插入的对象立即写入数据库并释放内存
  29. if (i % 10 == 0) {
  30. session.flush();
  31. session.clear();
  32. }
  33. }
  34. session.getTransaction().commit(); // 提交事物
  35. } catch (Exception e) {
  36. e.printStackTrace(); // 打印错误信息
  37. session.getTransaction().rollback(); // 出错将回滚事物
  38. } finally {
  39. HibernateUtil.closeSession(session); // 关闭Session
  40. }
  41. }
  42. }
  43. }
复制代码

4.Medicine.java源代码:

  1. package com.xqh.model;
  2. /**
  3. * 药品持久化类
  4. */
  5. public class Medicine {
  6. private Integer id; //id号
  7. private String name; //药品名称
  8. private double price; //价格
  9. private String factoryAdd; //出厂地址
  10. public Integer getId() {
  11. return id;
  12. }
  13. public void setId(Integer id) {
  14. this.id = id;
  15. }
  16. public String getName() {
  17. return name;
  18. }
  19. public void setName(String name) {
  20. this.name = name;
  21. }
  22. public double getPrice() {
  23. return price;
  24. }
  25. public void setPrice(double price) {
  26. this.price = price;
  27. }
  28. public String getFactoryAdd() {
  29. return factoryAdd;
  30. }
  31. public void setFactoryAdd(String factoryAdd) {
  32. this.factoryAdd = factoryAdd;
  33. }
  34. }
复制代码

5.??Medicine.hbm.xml源代码:

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="com.xqh.model.Medicine" table="tb_medicine_batch">
  7. <id name="id">
  8. <generator class="native"/>
  9. </id>
  10. <property name="name" not-null="true" length="200" />
  11. <property name="price" not-null="true"/>
  12. <property name="factoryAdd" length="200"/>
  13. </class>
  14. </hibernate-mapping>
复制代码

6.SaveMedicine.java源代码:

  1. package com.xqh.servlet;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import com.xqh.dao.MedicineDao;
  10. import com.xqh.model.Medicine;
  11. public class SaveMedicine extends HttpServlet {
  12. private static final long serialVersionUID = 3743334039515411666L;
  13. public void doPost(HttpServletRequest request, HttpServletResponse response)
  14. throws ServletException, IOException {
  15. // 药品名称
  16. String names[] = request.getParameterValues("name");
  17. // 价格
  18. String prices[] = request.getParameterValues("price");
  19. // 出厂地址
  20. String adds[] = request.getParameterValues("factoryAdd");
  21. // 有效性判断
  22. if(names != null && prices != null && adds != null){
  23. if(names.length == prices.length && names.length == adds.length){
  24. // 实例化一个List集合
  25. List<Medicine> ms = new ArrayList<Medicine>();
  26. Medicine m = null; // 药品对象
  27. // 依次实例化药品对象并添加到集合中
  28. for (int i = 0; i < names.length; i++) {
  29. m = new Medicine(); // 实例化药品
  30. // 对属性赋值
  31. m.setName(names[i]);
  32. m.setPrice(Double.parseDouble(prices[i]));
  33. m.setFactoryAdd(adds[i]);
  34. ms.add(m); // 添加到集合中
  35. }
  36. // 实例化MedicineDao对象
  37. MedicineDao dao = new MedicineDao();
  38. dao.saveMedicines(ms); // 批量保存药品
  39. request.setAttribute("info", "药品信息保存成功!!!");
  40. }
  41. }
  42. // 转发到result.jsp页面
  43. request.getRequestDispatcher("result.jsp").forward(request, response);
  44. }
  45. }
复制代码

7.CharacterEncodingFilter.java源代码:

  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.xqh.util;
  6. import java.io.IOException;
  7. import javax.servlet.Filter;
  8. import javax.servlet.FilterChain;
  9. import javax.servlet.FilterConfig;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.ServletRequest;
  12. import javax.servlet.ServletResponse;
  13. /**
  14. * 字符编码过滤器
  15. */
  16. public class CharacterEncodingFilter implements Filter{
  17. protected String encoding = null;
  18. protected FilterConfig filterConfig = null;
  19. public void init(FilterConfig filterConfig) throws ServletException {
  20. this.filterConfig = filterConfig;
  21. this.encoding = filterConfig.getInitParameter("encoding");
  22. }
  23. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  24. if (encoding != null) {
  25. request.setCharacterEncoding(encoding);
  26. response.setContentType("text/html; charset="+encoding);
  27. }
  28. chain.doFilter(request, response);
  29. }
  30. public void destroy() {
  31. this.encoding = null;
  32. this.filterConfig = null;
  33. }
  34. }
复制代码

8.HibernateUtil.java源代码:

  1. package com.xqh.util;
  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.cfg.Configuration;
  6. /**
  7. * Hibernate初始化类,用于获取Session、SessionFactory 及关闭Session
  8. */
  9. public class HibernateUtil {
  10. // SessionFactory对象
  11. private static SessionFactory factory = null;
  12. // 静态块
  13. static {
  14. try {
  15. // 加载Hibernate配置文件
  16. Configuration cfg = new Configuration().configure();
  17. // 实例化SessionFactory
  18. factory = cfg.buildSessionFactory();
  19. } catch (HibernateException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. /**
  24. * 获取Session对象
  25. * @return Session对象
  26. */
  27. public static Session getSession() {
  28. //如果SessionFacroty不为空,则开启Session
  29. Session session = (factory != null) ? factory.openSession() : null;
  30. return session;
  31. }
  32. /**
  33. * 获取SessionFactory对象
  34. * @return SessionFactory对象
  35. */
  36. public static SessionFactory getSessionFactory() {
  37. return factory;
  38. }
  39. /**
  40. * 关闭Session
  41. * @param session对象
  42. */
  43. public static void closeSession(Session session) {
  44. if (session != null) {
  45. if (session.isOpen()) {
  46. session.close(); // 关闭Session
  47. }
  48. }
  49. }
  50. }
复制代码

9.hibernate.cfg.xml源代码:

  1. <?xml version='1.0' encoding='UTF-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <!-- 方言 -->
  8. <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  9. <!-- 数据库连接 -->
  10. <property name="connection.url">jdbc:mysql://localhost:3306/learn</property>
  11. <!-- 数据库连接用户名 -->
  12. <property name="connection.username">root</property>
  13. <!-- 数据库连接密码 -->
  14. <property name="connection.password">1120</property>
  15. <!-- 数据库驱动 -->
  16. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  17. <!-- 打印SQL语句 -->
  18. <property name="show_sql">true</property>
  19. <!-- 自动建表 -->
  20. <property name="hibernate.hbm2ddl.auto">update</property>
  21. <!-- 映射文件 -->
  22. <mapping resource="com/xqh/model/Medicine.hbm.xml"/>
  23. </session-factory>
  24. </hibernate-configuration>
复制代码

10.log4j.properties源代码:

  1. ### direct log messages to stdout ###
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  3. log4j.appender.stdout.Target=System.out
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c小贝:%L - %m%n
  6. ### direct messages to file hibernate.log ###
  7. #log4j.appender.pold=org.apache.log4j.FileAppender
  8. #log4j.appender.file.File=hibernate.log
  9. #log4j.appender.file.layout=org.apache.log4j.PatternLayout
  10. #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c小贝:%L - %m%n
  11. ### set log levels - for more verbose logging change 'info' to 'debug' ###
  12. log4j.rootLogger=warn, stdout
  13. #log4j.logger.org.hibernate=info
  14. #log4j.logger.org.hibernate=debug
  15. ### log HQL query parser activity
  16. #log4j.logger.org.hibernate.hql.ast.AST=debug
  17. ### log just the SQL
  18. #log4j.logger.org.hibernate.SQL=debug
  19. ### log JDBC bind parameters ###
  20. #log4j.logger.org.hibernate.type=info
  21. #log4j.logger.org.hibernate.type=debug
  22. ### log schema export/update ###
  23. #log4j.logger.org.hibernate.tool.hbm2ddl=debug
  24. ### log HQL parse trees
  25. #log4j.logger.org.hibernate.hql=debug
  26. ### log cache activity ###
  27. #log4j.logger.org.hibernate.cache=debug
  28. ### log transaction activity
  29. #log4j.logger.org.hibernate.transaction=debug
  30. ### log JDBC resource acquisition
  31. #log4j.logger.org.hibernate.jdbc=debug
  32. ### enable the following line if you want to track down connection ###
  33. ### leakages when using DriverManagerConnectionProvider ###
  34. #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
复制代码

11.index.jsp源代码:

  1. <%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>批量添加药品信息</title>
  6. <style type="text/css">
  7. td {
  8. background: #EBEBEB;
  9. font-family: Verdana;
  10. font-size: 12px;
  11. background-color: #EBEBEB;
  12. color: black;
  13. line-height: 20px;
  14. height: 30px;
  15. }
  16. </style>
  17. <script type="text/javascript">
  18. function add(){
  19. var a = document.getElementById("a");
  20. var b = document.getElementById("b");
  21. b.innerHTML += a.innerHTML;
  22. }
  23. function reduce() {
  24. var a = document.getElementById("a");
  25. var b = document.getElementById("b");
  26. var stra = a.innerHTML;
  27. var strb = b.innerHTML;
  28. b.innerHTML = strb.substring(0, strb.length - stra.length);
  29. }
  30. function save(formName){
  31. for(i=0;i<formName.length;i++){
  32. if(formName.elements[i].value==""){
  33. alert("请填写完整信息!");
  34. return false;
  35. }
  36. }
  37. }
  38. </script>
  39. </head>
  40. <body onload="add()">
  41. <form action="SaveMedicine" method="post"
  42. onsubmit="return save(this);">
  43. <table align="center" border="0" cellpadding="3" cellspacing="1"
  44. width="600">
  45. <tr>
  46. <td align="center">
  47. <br>
  48. <h1>
  49. 批量添加药品信息
  50. </h1>
  51. </td>
  52. </tr>
  53. <tr>
  54. <td>
  55. <div id="b"></div>
  56. </td>
  57. </tr>
  58. <tr>
  59. <td>
  60. <input type="button" value="添加一行 " onclick="add()">
  61. <input type="button" value="减少一行" onclick="reduce()">
  62. <input type="submit" value="批量添加到数据库">
  63. </td>
  64. </tr>
  65. </table>
  66. </form>
  67. <div id="a" style="display: none">
  68. <table align="center" border="0">
  69. <tr>
  70. <td>
  71. 名称:
  72. </td>
  73. <td>
  74. <input type="text" name="name" size="13">
  75. </td>
  76. <td>
  77. 单价:
  78. </td>
  79. <td>
  80. <input type="text" name="price" size="13">
  81. </td>
  82. <td>
  83. 厂址:
  84. </td>
  85. <td>
  86. <input type="text" name="factoryAdd" size="30">
  87. </td>
  88. </tr>
  89. </table>
  90. </div>
  91. </body>
  92. </html>
复制代码

12.result.jsp源代码:

  1. <%@ page language="java" contentType="text/html" pageEncoding="GBK"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>结果信息</title>
  6. <!--
  7. <link rel="stylesheet" type="text/css" href="styles.css">
  8. -->
  9. </head>
  10. <body>
  11. <div align="center">
  12. <font color="red" size="12px;" style="font-weight: bold;">
  13. ${info}
  14. </font>
  15. <br><br><br><br>
  16. <a href="index.jsp">返回</a>
  17. </div>
  18. </body>
  19. </html>
复制代码

13.数据表tb_medicine_batch结构:

14.程序运行结果截图:

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

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 01:26

Copyright 2015-2025 djqfx

返回顶部