이 기사에서는 배치로 데이터를 추가하기위한 최대 절전 모드 방법에 대해 설명합니다. 다음과 같이 참조에 대해 공유하십시오.
1. Hibernate_016_batchadddata 프로그램 디렉토리 구조 :
2. LIB 디렉토리에 소개 된 JAR 패키지 :
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;/*** Drug Database Operation Class*/Public Class Medicinedao {/public collection* @param ms* @param ms* @param ms* @param ms* @param ms* @param ms* @param ms* @param ms* @param ms. Savemedicines (list <cection> ms) {세션 세션 = null; if (ms! = null && ms.size ()> 0) {try {session = hibernateutil.getSession (); // 세션 세션을 가져옵니다 .BegIntransaction (); // // 약물 개체 생성 // (int i = 0; i <ms.size (); i ++) {medicine = (의학) Ms.get (i); // 마약 세션을 받으십시오 .Save (Medicine); // 약물 객체 저장 // 삽입 된 개체의 배치는 즉시 데이터베이스에 기록되고 (i % 10 == 0) {session.flush (); session.clear (); }} session.getTransaction (). commit (); // 물건 제출} catch (예외 e) {e.printstacktrace (); // 인쇄 오류 메시지 session.getTransaction (). rollback (); // 오류가 롤백됩니다} 마침내 {hibernateutil.closesession (세션); // 세션 닫기}}}}4. Medicine.java 소스 코드 :
package com.xqh.model;/*** 약물 지속성 클래스*/public class medicine {개인 정수 ID; // ID 번호 개인 문자열 이름; // 약물 이름 개인 이중 가격; // Price Price Private String factoryAdd; // 공장 주소 공개 정수 getId () {return id; } public void setId (정수 ID) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public double getPrice () {반환 가격; } public void setPrice (이중 가격) {this.price = 가격; } public String getCortoryAdd () {return factoryAdd; } public void setFactoryAdd (String factoryAdd) {this.factoryAdd = factoryAdd; }}5. Medicine.hbm.xml 소스 코드 :
<? XML 버전 = "1.0"?> <! DocType Hibernate Mapping Public "-// hibernate/hibernate 매핑 DTD 3.0 // 테이블 = "tb_medicine_batch"> <id name = "id"> <generator/> </id> <속성 이름 = "name"not ""true "longth ="200 "/> <속성 이름 ="price "not-null ="true "/> <속성 이름 ="factoryAdd "longth ="200 "/> </hibernate-Mapping>
6.saveMedicine.java 소스 코드 :
패키지 com.xqh.servlet; import java.io.ioexception; import java.util.arraylist; import java.util.list; import javax.servlet.servletexception; import javax.servlet.http.httpervax.servlet.http.httpepest Javax.servlet.http.http.httpervletresponse; import com.xqh.dao.medicinedao; import com.xqh.model.medicine; public class savmedicine 확장 httpservlet {private static final long serialversionuid = 3743334039515411666; public void dopost (httpservletRequest 요청, httpservletResponse 응답) servletexception, ioexception {// 약물 이름 문자열 이름 [] = request.getParametErvalues ( "name"); // 가격 문자열 가격 [] = request.getParametErvalues ( "price"); // 공장 주소 문자열 추가 [] = request.getParametErvalues ( "FactoryAdd"); // 유효성 판단 if (names! = null && price! = null && adds! = null) {if (names.length == price.length && names.length == adds.length) {// 목록 컬렉션 목록 <cection> ms = new arraylist <cection> (); 약 m = null; // 약물 물체 // 약물 물체를 차례로 인스턴스화하여 (int i = 0; i <names.length; i ++) {m = new Medicine (); // 약물을 인스턴스화 // 속성을 할당 m.setName (이름 [i]); M.SetPrice (Double.parsEdouble (가격 [i])); M.setFactoryAdd (Adds [i]); M.add (m); // 세트에 추가} // Medicinao Object Medicinao Dao = New Medicinao (); Dao.SaveMedicines (MS); // 약물 요청을 저장합니다. SetAttribute ( "정보", "약물 정보가 성공적으로 저장됩니다 !!!"); }} // 앞으로 (요청, 응답); }}7. articationEncodingFilter.java 소스 코드 :
/ * *이 템플릿을 변경하려면 도구를 선택하십시오 | 템플릿 * 및 편집기에서 템플릿을 엽니 다. */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; servletrtr jvletrtrrestrepcones; * 문자 인코딩 필터 */public class char 보호 된 FilterConfig FilterConfig = NULL; public void init (filterconfig filterconfig) servletexception {this.filterconfig = filterconfig; this.encoding = FilterConfig.getInitParameter ( "인코딩"); } public void dofilter (ServletRequest 요청, ServletRepsonge 응답, FilterChain 체인) IoException, servleTeXception {if (encoding! = null) {request.setchAracterEncoding (encoding); response.setContentType ( "text/html; charset ="+encoding); } chain.dofilter (요청, 응답); } public void destrove () {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 초기화 클래스, 세션을 얻는 데 사용되는 hibernate hibernate hibernate hibernate hibernate fromain {// 홍보 hibernate hibernate froma 공장 = null; // static block static {try {// hibernate configuration file configuration cfg = new configuration (); configure (); // Instantiate sessionFactory factory = cfg.buildsessionfactory (); } catch (HibernateException e) {e.printstacktrace (); }} / *** 세션 객체 가져 오기* @return 세션 객체* / public static session getsession () {// SessionFacroty가 비어 있지 않은 경우 세션 세션 세션을 활성화하십시오 (팩토리! = null)? 팩토리.opensession () : null; 반환 세션; } / *** get sessionFactory Object* @return sessionFactory Object* / public static sessionFactory getSessionFactory () {return factory; } / *** 닫기 세션* @Param 세션 객체* / public static void closesession (세션 세션) {if (session! = null) {if (session.isopen ()) {session.close (); // 세션 닫기}}}}9.hibernate.cfg.xml 소스 코드 :
<? XML 버전 = '1.0'인코딩 = 'UTF-8'?> <! DocType Hibernate-Configuration Public "-// Hibernate/Hibernate Configuration DTD 3.0 // en" "http://hiberceforge.net/hibernate-configuration-3.0.dtd"> <http://hiberceforge.net/http://hiberceforge.net-3.0.dtd ". <Session-Factory> <!-Dialect-> <Property name = "dialect"> org.hibernate.dialect.mysqldialect> <!-데이터베이스 연결-> <property name = "connection.url"> jdbc : mysql : // localhost : 3306/chorg </property> <! 이름 = "connection.username"> root </property> <!-데이터베이스 연결 암호-> <속성 이름 = "connection.password"> 1120 </property> <!-데이터베이스 드라이버-> <connection.driver_class "> com.mysql.jdbc.driver </property> <!-print </property pline ="true ql "> true ql"> 생성-> <property name = "hibernate.hbm2ddl.auto"> update </property> <!-매핑 파일-> <매핑 자원 = "com/xqh/model/medicine.hbm.xml"/> </session-factory> </hibernate-configuration>
10.LOG4J.Properties 소스 코드 :
### stdout에 직접 로그 메시지 ### log4j.appender.stdout = org.apache.log4j.consoleAppenderLog4j.appender.stdout.target = system.outlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversonversonversonpattern = %d { %c {1} : %l- %m %n ### 파일 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.conversonpattern = %d} % 비 활동#log4j.logger.org.hibernate.hql.ast.ast = debug ### log 만 sql#log4j.logger.org.hibernate.sql = debug ### log jdbc 바인드 매개 변수 #### log4j.logger.org.hibernate.type = info#log4j.logger.org.hibernate.type = debug ### log schemo export/update #### log4j.logger.org.hibernate.toole.hbm2ddl = debug hql parse trees#log4j.logger.org.hibernate.hql = Debug ### 로그 캐시 활동 #### log4j.logger.org.hibernate.cache = debug ### transaction activity#log4j.logger.org.hibernate.transaction = debug jdbc resource jdbc resource 획득#log4j.logger.org.hibernate.jdbc = Debug ## DriverManagerConnectionProvider #### log4j.logger.org.hibernate.connection.drivermanagerConnectionProvider = trace를 사용할 때 연결을 추적하려면 다음 줄을 활성화합니다.11.index.jsp 소스 코드 :
<%@ page language = "java"contmenttype = "text/html"pageencoding = "gbk"%> <! doctype html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <head> <title> 약물 정보 추가 </td {style type = "text/css": "text/css": #ebebeb; 유대 가족 : Verdana; 글꼴 크기 : 12px; 배경색 : #EBEBB; 색상 : 검은 색; 라인 높이 : 20px; 높이 : 30px;} </style> <script type = "text/javaScript"> function add () {var a = document.getElementById ( "a"); var b = document.getElementById ( "b"); B.innerhtml += a.innerhtml; } function reting () {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 ( "전체 정보를 작성하십시오!"); 거짓을 반환합니다. }}}} </script> </head> <body onload = "add ()"> <form action = "sevemedicine"method = "post"onsubmit = "return save (this);"> <테이블 align = "center"cellpadding = "3"셀 패팅 = "1"> <t> <td align = "center"> </tr> <tr> <td> <div id = "b"> </div> </td> </td> </td> </td> <tr> <입력 유형 = "value ="줄 추가 "onclick ="add () "> <input type ="button "value ="reving () "> value ="vally "> to </td> <"> to </td> < "> </form> <div id = "a"style = "display : none"> <테이블 align = "center"> <tr> <td> 이름 : </td> <td> <입력 유형 = "text"name "="size = "13"> </td> <td> 단위 가격 : </td> <td> <입력 유형 = "text"</td> finc "13"> ">"> "> td> </td> <td> <입력 유형 = "text"name = "factoryAdd"size = "30"> </td> </trave> </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> 결과 정보 </cs " href = "styles.css"> -> </head> <body> <div align = "center"> <font color = "red"size = "12px;" 스타일 = "font-weight : bold;"> $ {info} </font> <br> <br> <br> <br> <a href = "index.jsp"> return </a> </div> </body> </html>13. 데이터 테이블 TB_MEDICINE_BATCH 구조 :
14. 프로그램 작동 결과의 스크린 샷 :
이 기사의 설명이 최대 절전 모드 프레임 워크를 기반으로 한 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.