Struts Hibernate Template Development Notes
Author: sharp knife prodigal son (section Hongjie)
First, establish a database link pool
Second, establish a test database
Third, establish Hibernate configuration
Fourth, map the table of the database to the class
Five, the package definition in the template
Six, design mode: single case
Seven, design mode: facade
Eight, design mode: DAO
Nine, design mode: MVC
Ten, custom label
11. Solve Chinese character encoding problems
First, establish a database link pool
1. Copulate the database driver into the common / lib directory of Tomcat5.0.
Such as: Oracle9i copy ojdbc14.jar
2. Modify the Tomcat configuration file conf / server.xml. Add the following code before host>:
1. Establish a database user name DEMO password DEMO
2. Establish a test table
Establish test table Demo
Field Description ID Char (100) Primary Key Name VARCHAR2 (50) Name Image_id Number (10) Image ID System_Date Date System Date User_Date Date Entry Date
Create a picture index table image
Field Description ID Char (100) Primary Key Title Varchar2 (50) Picture Title Message Varchar2 (2000) Image ORIGINAL_IMAGE_PATH VARCHAR (200) Original Picture Save Path Small _Image_path varchar (200) Small picture Save Path Image_id Number (10) Image ID System_Date Date System date ID index table SINGLETON_ID
Field Description ID Char (100) Primary Key Name Varchar2 (50) Index Name (need to build an index for this field) Value Number (10) Index ID
Third, establish Hibernate configuration
1. Copy Oracle9i Database Driver Ojdbc14.jar to the Lib Directory of the JBuilder9 installation directory. Use JBuilder9.0 to establish Project Project.
2. Put the following Hibernate-2.0.3 must be included in the project.
Hibernate2.jar
Commons-beanutils.jar
Commons-Collects.jar
Commons-dbcp.jar
Commons-lang.jar
Commons-logging.jar
Commons-pool.jar
Dom4j.jar
CGLIB-asm.jar
CONNECTOR.JAR
3. Establish a hibernate.cfg.xml file and copy to the src directory
xml version = '1.0' encoding = 'UTF-8'?>
Fourth, map the table of the database to the class
Download Hibernate-Extensions Compressed Pack. Modify the environment variables in the setEnv.bat file. Mainly modify the Hibernate directory and database driver file name.
E.g:
@echo off rem ---------------------------------------------------------------------------------------------------------------------- -------------------- Rem Setup Environment for Hibernate ToolsRem ----------------------- ------------------------------------------- set jdbc_driver = .. / ../../lib/ojdbc14.jarset hibernate_home = .. / .. / .. / Hibernate-2.0.3
SET CORELIB =% hibernate_Home% / libset lib = .. / libset props =% hibernate_Home% / srcset CP =% jdbc_driver%;% PROPS%;% hibernate_home% / hibernate2.jar;% CoreLib% / Commons-logging.jar;% Corelib%;% corelib% / commiss-lang.jar;% corelib% / cglib.jar;% Corelib% / Dom4j.jar;% Corelib% / odmg.jar;% Corelib% / XML-APIS .jar;% Corelib% / Xerces.jar;% Corelib% / Xalan.jar;% lib% / jdom.jar;% lib% / .. / hibernate-tools.jar
Run DDL2HBM.BAT, set parameters as follows:
[Connection] Driver Class: Oracle.jdbc.driver.OracleDriver (org.gjt.mm.mysql.driver) Connection URL: JDBC: Oracle: Thin: @ 192.168.3.200: 1521: Demo (JDBC: mysql: // localhost / Authority) User: Demopassword: Demo
[Mapping] Key Field: IDSChemaexport: uuid.hex
[Code] package name: com.company.demo.jdo
[OUTPUT] F: / J_WORK / WORKING / DEMO / SRC
Other use of default, click [Tables] Tables .. Select Table, Program Generate Class and XML
The generated files are as follows:
(1) Image.java
package com.company.demo.jdo; import java.io.Serializable; import java.util.Date; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import Org.apache.commons.lang.builder.toStringBuilder;
/ ** @Author hibernate codeGenerator * / public class image imports serializable {
/ ** iDentifier Field * / private string id;
/ ** Nullable persistent Field * / private string Title
/ ** Nullable Persistent Field * / private string message;
/ ** Nullable Persistent Field * / Private String OriginalImagePath;
/ ** Nullable Persistent Field * / Private String SmallImagePath; / ** Nullable Persistent Field * / Private Long ImageId;
/ ** Nullable Persistent Field * / Private Date SystemDate;
/ ** full constructor * / public Image (String title, String message, String originalImagePath, String smallImagePath, long imageId, Date systemDate) {this.title = title; this.message = message; this.originalImagePath = originalImagePath; this.smallImagePath = SmallImagePath; this.imageId = imageid; this.systemdate = systemdate;}
/ ** Default constructor * / public image () {}
Public string getId () {returnim.
Public void setid (string id) {this.id = id;}
Public string gettitle () {return this.title;
Public void settitle (string title) {this.title = Title;}
Public string getMessage () {return this.Message;
Public void setmessage (string message) {this.Message = message;}
Public String getoriginalImagePath () {return this.originalImagePath;
Public void setORIGINALIMAGEPATH (String OriginalImagePath) {this.originalImagePath = OriginalImagePath;}
Public string getsmallimagepath () {return this.smallimagepath;}
Public void setsmallImagePath {this.smallImagePath = smallimagepath;
Public long getImageId () {return this.imageId;
Public void setImageId (long meansid) {this.imageId = imageid;
Public Date getSystemDate () {return this.systemdate;}
Public void setsystemdate (date systemdate) {this.systemdate = systemdate;}
Public string toString () {Return New TostringBuilder (this) .append ("id", getId ()). Tostring ();}
public boolean equals (Object other) {if return false ((other instanceof Image)!); Image castOther = (Image) other;.. return new EqualsBuilder () append (this.getId (), castOther.getId ()) isEquals (); public int.come () {return new hashcodebuilder (). append (getId ()). tohashcode ();
}
(2) Image.hbm.xml
XML Version = "1.0" encoding = "UTF-8"?>
Other generated files!
Five, the package definition in the template
Com.company.Demo.dataModule data model com.Company.DEMO.DAO DAO model com.Company.Demo.exception exception com.Company.Demo.jdo hibernate class map com.Company.Demo.start launching JSP service When you load COM.Company.Demo.tags Custom Tag Class COM.Company.Demo.thread thread class com.Company.Demo.util tool class com.Company.Demo.Web struts class com.company.demo.facade facade called class six , Design mode: single case
Data model
Interface (DataModule.java)
Package com.Company.Demo.dataModule; package com.company.demo.dataModule
Import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibelnate.hibernateException;
Import net.sf.hibrnate.SessionFactory; import net.sf.hibrnate.cfg.configuration;
/ ***
Title: Struts Hibernate Development Template P> *
Description: General Development Template P> *
Copyright: CopyRight (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public interface DataModule {public sessionFactory getsessionFactory ();}
Data model (DATAMODULEIMPL.JAVA)
Package com.company.demo.dataModule;
/ ***
Title: Struts Hibernate Development Template P> *
Description: General Development Template P> *
Copyright: CopyRight (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibelnate.hibernateException;
Import net.sf.hibrnate.SessionFactory; import net.sf.hibrnate.cfg.configuration;
/ *** Establish sessionFactory * /
Public Class DataModuleImpl Implements DataModule {
Private sessionFactory sessionFactory;
Public DataModuleImpl () throws hibernateException {sessionFactory = new configuration (). configure (). buildsessionFactory ();} / *** SedionsFactory * / from DataModule * /
Public sessionFactory GetSessionFactory () {return this.SessionFactory;}} 2. Produced parent class
Singletoniddao.java
Package com.Company.Demo.dao; / ***
Title: struts hibernate development template p> *
description: General Development Template P> *
Copyright: CopyRight (c) 2003 p> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public interface singletoniddao {}
ID parent class (SingletonidDaoImpl.java)
Package com.Company.Demo.da;
Import java.util.list; import com.company.demo.dataModule. *; import com.company.demo.jdo.singletonid;
Import net.sf.hibinal.SessionFactory; import net.sf.hibernate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.query;
/ *** Generate a unique ID ** database structure (Oracle9i): * Name Singleton_ID * Field ID (Char) Name Varchar2 (50) Value Number (10.0) ***
Title: Struts Hibernate Development Template < / p> *
Description: General Development Template P> *
Copyright: Copyright (C) 2003 P> *
Company: Advantages Technology P> * @Author Duan Hongjie * @version 1.0 *** /
Public Class SingletonidDaoImpl Implements Singletonidda {
Private sessionFactory sessionFactory; private datamodule DataModule;
/ *** Set data model * /
Public void setDataModule {this.dataModule = DATAModule; this.SessionFactory = DATAMODULE.GETSESSIONFACTORY ()
The following business logic private SingletonId findByName (String name) throws HibernateException, Exception {Transaction transaction = null; SingletonId singletonId = new SingletonId (); Session session = sessionFactory.openSession (); String queryString = "select g from SingletonId as g where g .name =: name order by g.value desc "; try {transaction = session.begintransaction (); query query = session.createQuery (queryString); Query.setString (" name ", name); // q.setfirstresult ( 20000); // q.setMaxResults (100); query.setMaxResults (1); list list = query.list (); singletonid = (singletonid) list.get (0); transaction.commit ();} catch (Exception EX) {if (transaction! = null) {transaction.rollback ();} // throw ex;} finally {session.close ();} return singletonid;} / ** gaining value * @Param Name produced unique ID Type name * @Return Value * @throws HibernateException * /
protected long getValue (String name) throws HibernateException, Exception {SingletonId singletonId = findByName (name); return singletonId.getValue ();} / ** set value * @param name Name Type yield unique ID * @throws HibernateException * /
protected void setValue (String name) throws HibernateException, Exception {Session session = sessionFactory.openSession (); SingletonId singletonId = findByName (name); singletonId.setName (name); singletonId.setValue (singletonId.getValue () 1); Transaction transaction = null; try {transaction = session.beginTransaction (); session.saveOrUpdate (singletonId); transaction.commit ();} catch (HibernateException he) {if (transaction = null!) {transaction.rollback ();} throw HE;} finally {session.close ();}}}
3. Single case image ID (ImageSingletonid.java)
package com.company.demo.dao.count; import net.sf.hibernate.HibernateException; import com.company.demo.dao.SingletonIdDAOImpl; import com.company.demo.datamodule.DataModule; / ***
Title : Struts Hibernate Development Template P> *
Description: General Development Template P> *
Copyright: Copyright (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public class imageSingletonid Extends SingletonidDaoImpl {
Private static imageashletonid iMageSingletonid = NULL;
/ *** private constructor * / private ImageSingletonId () {} / *** static factory pattern, made ImageSingletonId instance * / public static synchronized ImageSingletonId getInstance () {if (imageSingletonId == null) {imageSingletonId = new ImageSingletonId () Return ImageSingletonId;}
/ *** Take a graphic unique id * / public synchronized long getimagevalval () throws hibernateException, Exception {long value; setValue ("image"); value = getValue ("image"); return value;}
}
4. Picture ID test file (TestimageSingletonid.jsp)
<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ page import = "Net.sf.hibernate. *"%> <% @ Page Import = "Net.sf.hibernate.cfg. * "%> <% @ page import =" com.company.demo.dataModule. * "%> <% @ page import =" com.company.demo.dao.count. * "%> <%! DataModule DataModule; ImageSingletonid imageSingletonId;%> <% try {imageSingletonId = ImageSingletonId.getInstance (); imageSingletonId.setDataModule (new DataModuleImpl ());} catch (Exception ex) {ex.toString ();} for (int i = 0; i <100 i ) {OUT.PRINT ("Test .........
"); out.print (imageSingletonid.getImageValue ()); out.print ("-------- --------
");}%>
5. SinglePageSingletonid.java package com.company.demo.dao.count; import net.sf.hibernate.hibernateException; import com.company.demo.dao.singletonidDaoImpl; import com.company. Demo.dataModule.DataModule;
/ ***
Title: Struts Hibernate Development Template P> *
Description: General Development Template P> *
Copyright: CopyRight (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public class mainpageSingletonid Extends SingletonidDaoImpl {
Private static mainpageSingletonid mainpageSingletonid = NULL
/ *** private constructor * / private MainPageSingletonId () {} / *** static factory pattern, made MainPageSingletonId instance * / public static synchronized MainPageSingletonId getInstance () {if (mainPageSingletonId == null) {mainPageSingletonId = new MainPageSingletonId () Return MainpageSingletonid;}
/ *** Take a unique ID * / public synchronized long getMainPageValue () throws hibernateException, Exception {long value; setValue ("mainpage"); value = getValue ("mainpage"); return value;}
}
6. Music ID Test File (TestMainPageSingletonid.jsp)
<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ page import = "Net.sf.hibernate. *"%> <% @ Page Import = "Net.sf.hibernate.cfg. * "%> <% @ page import =" com.company.demo.dataModule. * "%> <% @ page import =" com.company.demo.dao.count.mainpageSingletonid "%> <%! DataModule DataModule; mainpageSingletonid mainPageSingletonId;%> <% try {mainPageSingletonId = MainPageSingletonId.getInstance (); mainPageSingletonId.setDataModule (new DataModuleImpl ());} catch (Exception ex) {ex.toString ();} for (int i = 0; i <100 ; i ) {OUT.PRINT ("Test .........
"); out.print (MainpageSingletonid.getMainPageValue ()); Out.print ("-------- --------
");}%> 7. Comprehensive single sample test (omitted)
Seven, design mode: facade
1. Tune "Session Facade" class in JSP
Insert the following tags in the JSP file:
2.SessionBean class
Package com.company.demo.meb;
Import com.company.demo.datamodule.demo.thread. *; import com.company.demo.facade. *; / ***
Title: struts hibernate development template p > *
Description: General Development Template P> *
Copyright: Copyright (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public class sessionBean {private damodule data model; // Data Model Private Auth; // Logic User Information Private Business Business; // Service Logic Mainline Private Line Line; / / Save Module / *** structure function, initializes the business logic class (singleton) * / public SessionBean () {try {dataModule = SessionBeanSingletonFactory.getDataModule (); auth = SessionBeanSingletonFactory.getAuth (); business = SessionBeanSingletonFactory.getBusiness (); line = SessionBeanSingletonFactory. GetLine ();} catch (exception ex) {ex.printStackTrace ();}} / *** Facade mode called public application module * @return utility * / public utility get1ility () {return sessionBeanfactory.getILITILITILITILITILITY () } 3.SessionBeanFactory class
Package com.company.demo.dataModule.Demo.dataModule.Demo.dataModule.Demo.thread. *; import com.company.demo.facade. *; import net.sf.hibernate.hibernateException / *** SessionBean facade pattern Abstract factory class *
Title: struts hibernate development template p> *
Description: General Development Template P> *
Copyright: CopyRight (c) 2003 p> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
public class SessionBeanFactory {/ *** service logic state of the instance generation (facade) * @return LineImpl * @throws HibernateException * / private SessionBeanFactory () {} public final static Utility getUtility () {return new UtilityImpl ();}
}
4.SessionBeansingletonFactory class
Package com.company.demo.dataModule.Demo.dataModule.Demo.dataModule.Demo.thread. *; import com.company.demo.facade. *; import net.sf.hibernate.hibernateException ;
/ ***
Title: Struts Hibernate Development Template P> *
Description: General Development Template P> *
Copyright: CopyRight (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public class sessionBeansingletonFactory {/ *** Generate user authentication instance (single case) * @Return Authimpl * @throws hibernateException * / private sessionBeansingletonFactory () {}
public final static Auth getAuth () throws HibernateException {return new AuthImpl ();} / *** generated business logic instance (singleton) * @return BusinessImpl * @throws HibernateException * / public final static Business getBusiness () throws HibernateException {return New businessimpl ();} / *** Generate data model instance (Sample) * @Return DataModuleImpl * @throws hibernateException * /
Public final static datamodule getDataModule () throws hibernateException {return new dataModuleImpl ();} / *** Generate business logic status instance (single case) * @return lineImpl * @throws hibernateException * /
Public final static line getLine () throws hibernateException {return new lineImpl ();
}
Eight, design mode: DAO
Using Data Access Objects (DAO) allows us to separate the underlying data access logic to business logic. We build a DAO class that provides GRUD (creation, reading, update, delete) for each data source.
Below is a DAO instance of a data source GRUD.
1. Demodao.java
Package com.Company.Demo.da;
Import net.sf.hibernate.hibernateException; import com.company.demo.jdo.demo; import com.company.demo.datamodule. *; / ***
Title: struts hibernate development template p> *
description: General Development Template P> *
Copyright: Copyright (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public interface demodao {
/ ** Set data model ** / public void setDataModule (DATAMODULE DATAMODULE); / ** Establish an object ** / public void createDemo (Demo Demo) HibernateException, Exception
}
2. Abstract factory (DemodaOfactory.java)
Package com.Company.Demo.dao; / ***
Title: struts hibernate development template p> *
description: General Development Template P> *
Copyright: CopyRight (c) 2003 p> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public class demodaofactory {
PRIVATE DEMODAOFACTORY ()} public final static demodao getdemodao () {Return New DemodaoImpl ();}} 3.DAO class (DEMODAOIMPL.JAVA)
Package com.company.demo.dao; import java.util.list; import com.company.demo.dataModule.DataModule.Demo.do.demo;
Import net.sf.hibinal.SessionFactory; import net.sf.hibernate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.query;
/ ***
Title: Struts Hibernate Development Template P> *
Description: General Development Template P> *
Copyright: CopyRight (C) 2003 P> *
Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * /
Public Class DemodaoImpl Implements Demodao {
Private sessionFactory sessionFactory; private datamodule DATAMODULE DATAMODULE
/ *** Set Data Model * @Param DataModule * / Public Void SetDataModule {this.DataModule = DATAModule; this.SessionFactory = DataModule.GetSessionFactory ();
/ *** establish DEMO * @param demo * @throws HibernateException * @throws java.lang.Exception * / public void createDemo (Demo demo) throws HibernateException, Exception {Transaction transaction = null; Session session = sessionFactory.openSession (); Try {Transaction = session.begintransaction (); session.save (demo); transaction.commit ();} catch (hibernateException he) {i (transaction! = null) {= i (transaction! = null);} throw he;} finally {session.close ();
}
Nine, design mode: MVC
1. Representation layer (Application Template)
JSP file (Template / BasicTemplate.jsp)
<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Taglib Uri = '/ Web-INF / STRUTS-TEMPLATE.TLD' Prefix = 'Template'%>
| |
| |
<% / *** Title: Struts Development Test 1.0 P> * Description: Item Description P> * Copyright: Copyright (C) 2003-2008 P> * < P> Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * @time [October 22, 2003] ** /%> <% @ Page ContentType = "Text / HTML; Charset = GB2312 "%> <% @ Taglib URI = '/ Web-inf / struts-template.tld' prefix = 'template'%> JSP file (Content / AddDemo.jsp) <% / *** Title: Struts Development Test 1.0 P> * Description: Item Description P> * Copyright: Copyright (C) 2003-2008 P> * < P> Company: Advantage Technology P> * @Author Duan Hongjie * @version 1.0 * @time [October 22, 2003] ** /%> <% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "HTML"%> <% @ Taglib URI = "/ WEB-INF / IMAGETAG.TLD "prefix =" image "%> <% @ Taglib URI =" / Web-inf / datetag.tld "prefix =" date "%> |