Let Struts work together with Hibernate

xiaoxiao2021-03-06  37

Installation article 1, download installation J2SDK1.4 (www.sun.com)) or above, set ClassPath, Java_Home. Second, download the server, the free version has Tomcat, Resin, of course, there is also a giant talented to WebLogic, but you have to see if your computer is configured! Here is only RESIN to explain, other configurations are similar, You can view the documentation files that each server comes. The RESIN server can be downloaded in Caucho.com, select the appropriate version, and download the decompression can be used directly. Here RESIN has a RESIN-EE version, which is mainly supported by EJB functionality. If you don't use EJB, it is general enough. Third, then the database, there are many database products to choose, DB2, Oracle, MSSQL, MySQL, etc. too much. Here I choose MySQL, not only because it is free, but its 4.0 version is integrated in InnoDB (http://www.innodb.com) advanced transaction mechanism. I believe that along with Linux's growth, it will take place in the commercial database market. However, on the database itself, it lacks support for powerful functions such as subqueries. There are not many installations, configure the user name, password. Then you can download MySQL-Front to visualize the operational database. Fourth, in Java programming, an IDE function is obviously indispensable, now there are many popular IDEs, there are jBuilder, Eclipse, Intellj Idea, JCREATOR, etc., where Eclipse relies on powerful plug-in functions by the powerful plug-in function. The future tool, JBuilder has the strongest Java tool, but the computer can't run, poor, but you can have a new computer. So I still like Jcreator, small and fun, and have more than enough applications. When compiling and developing, you want to get a prompt support, you need to import JAR files in Configure - Option - JDK Profiles. V. Development of a site front desk, of course, is inseparable from Ding Ding DreamWeaver, which supports the development of many languages ​​such as JSP, ASP. In particular, the nearest Dreamweaver MX 2004 enhances the functionality of the site, which can be easily controlled to a site. Faced with the Struts front desk custom label, there is a MXP plug-in to support the label of Sturts. Import the .tld file in the editing-tag library before use, currently only supports both of the BEAN. Configuration article 1, RESIN virtual site configuration

Then establish a site under the defined directory. Second, the Dreamweaver site is not said. Third, Struts Configuration Here we use struts1.1, download and decompress to the temporary folder, assume that it is a TEM folder. First copy all the .tld files all .TLD files to the site / web-inf / directory, copy all .jar files to / web-inf / lib / directory, the last web.xml file is almost as follows:

action org.apache.struts.Action.ActionServlet config /web-inf/struts-config.xml debug 2 detail 2 2 Action *. do Index.jsp / tags / struts-bean < Taglib-location> /Web-inf/struts-bean.tld

/ Tags/Struts-html< Taglib-Location>B-inf/Struts-html.tld> /web-inf/struts-logic.tld / tags / struts-nested /web-inf/struts-nested.tld / tags / struts-tiles /web-inf/struts-tiles.tld four, Hibernate configuration download and copy / lib directory

Hibernate2.jar Commons-beanutils.jar Commons-Collections.jar Commons-dbcp.jar Commons-Lang.jar Commons-logging.jar Commons-pool.jar Dom4j.jar cglib-asm.jar connector.jar

Under the / lib directory of the application site. Next, configure the hibernate.cfg.xml file

JDBC: mysql: // localhost: 3306 / YourDatabase org.gjt.mm.mysql.Driver yourname youyrpassword false net.sf.hibernate.diaalect.mysqldiaalect net.sf.hibernate.transaction.JDBCTransactionFactory 10 true

The address and user name, password, etc. used in database connections are configured. Please refer to the official documentation for the meaning of the specific parameters. The content of the mapping file can be written manually, or it can be automatically generated by some tools. The whole need two files: .hbm.xml configuration file and .java persistent object, both are interrelated, .hbm.xml The mapping of the database also needs .java this bean to operate. So the entire process needs to first design the database, then export .hbm.xml file according to the database, then export .java file. There are many tools to implement this project, we use MiddleGen-Hibernate to implement the transformation of the database to .hbm.xml file, implement the HBM2JAVA in the Hibernate-Extension kit. HBM.XML to .java file transformation! Find keyword "! Entity", get: ]>

b) Application Name

c) Output Directory Find Keyword "Name =" Build.gen-src.dir ", get:

d) Package Name of the corresponding code

After the configuration is completed, running Ant in the MiddleGen root directory, the Middle Gen interface will appear: Select the required table, click the Generate button on the top of the window, MiddleGen generates the Hibernate mapping files corresponding to these database tables. The next job is completed by hibernate extension, and the Hibernate Extension's Tools / bin directory contains three tools: 1. Hbm2java.bat generates a corresponding POJO based on the mapping file. With MiddleGen we have got a mapping file, the next step is to generate the corresponding POJO through the HBM2Java.bat tool. 2. Class2HBM.BAT generates a mapping file according to Pojo Class, which is rarely used, and it will not be detailed here. 3. DDL2HBM.BAT is exported from the library table structure and generate mapping files and Pojo. This feature overlaps with MiddleGen's function, but since it is not mature enough (actually has been discarded, no more maintenance), the provided function is limited, so we still use MiddleGen to generate a mapping file, and then generate Pojo according to the mapping file by the mapping file. the way. Here we use the first HBM2JAVA.BAT to automatically generate Java files using the .hbm.xml file just generated. In order to use this tool, first we need to configure some parameters, open the Tools / Bin / SetENV.bat file, modify the JDBC_Driver and hibernate_home environment variables to point to our directory where the actual JDBC DRIVER file and Hibernate are located. At the same time, check if there is actually existing in the environment variable CP, especially the JAR file under% corelib%, some versions of the file name in the default configuration, and the actual file name (as%) Corelib% / commons-logging.jar, in the Hibernate release package, may actually actually file names are commons-logging-1.0.3.jar, such as this). Using HBM2JAVA, generate Java code according to MiddleGen generated mapping file: Open Command Window, execute under Tools / Bin directory: HBM2JAVA C: / Sample / Org / Hibernate / sample / *. Xml --output = C: / Sample / pass The above steps we generate all the basic configuration files required. Next, you can initialize these configurations. In this section we have to configure a complete application configuration. In fact, every one can write this book alone, but I just focus on my own summary, I will continue to write about the lessons learned by learning. First, Log4j's initialization configuration log4j.properties

### direct log message to stdout #### log4j.appender.stdout = org.apache.log4j.consoleappender # log4j.appender.stdout.target = system.Sout # log4j.appender.stdout.Layout = Org.apache. Log4j.patternLayout% C {1}:% L -% M% N # log4j.Appender.stdout.Layout.conversionPattern =% - 5P% D {YYYY-MM-DD HH: mm: SS}% L% N% M % n log4j.logger.seerlog = DEBUG, A2log4j.appender.A2 = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.A2.file = d: //log//applog.txtlog4j.appender.A2.DatePattern= '.' YYYY-mm-ddlog4j.appender.a2.Layout = org.apache.log4j.patternlayoutLog4j.Appender.a2.Layout.conversionPattern =% - 5P% D {YYYY-MM-DD HH: mm: ss}% m% N # Log4j.logger.all = debug, a1log4j.Appender.a1 = org.apache.log4j.dailyrollingfileAppenderlog4j.Appender.a1.file = d: //log/All.Loglog4j.Appender.a1.datepattern='.'yyyy- MM-DDLOG4J.APPENDER.A1.LOG4J.PATTERNLAYOUTLOG4J.PPPnder.a1.Layout.conversionPattern =% - 5P% D {YYYY-MM-DD HH: mm: SS}% L% N% 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, stdoutlog4j.rootlogger = info, A1 # below is Hibernate API Need to configure log4j.logger.net.sf.hibernate = info ### log just the sql # log4j.logger.net.sf.hibernate.sql = debug ### log jdbc bind parameters ### log4j.logger.net .sf.hibernate.Type = info ### log schema export / update ### log4j.logger.net.sf.hibernate.tool.hbm2ddl =

debug ### log cache activity #### log4j.logger.net.sf.hibernate.cache = debug ### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ## ## log4j.logger.net.sf.hibernate.connection.driverManagerConnectionProvider = TRAC configuration After calling, first you need to initialize the configuration file, this process only needs once, so we can do it in servletContextListener. String prefix = context.getRealPath ("/"); PropertyConfigurator.configure (Prefix / Web-INF / CLASSES / LOG4J.PROPERTIES "); here you need your configuration file path to initialize. After the initialization is completed, we can call like this in the next Action:

Static logger log = logger.getlogger ("seerlog"); log.warn ("IT's log4j warn"); log.info ("it's log4j info"); About Log4j's full use, it will make a detailed description in the future ! Second, Hibernate initialization First we have to put hibernate.cfg.xml in the application's classs directory, and then use the example of the Hibernate reference document to encapsulate the use of the background.

public class Hi {private static final SessionFactory sessionFactory; private static Connection conn; static {try {sessionFactory = new Configuration () configure () buildSessionFactory ();} catch (HibernateException ex) {throw new RuntimeException ( "Exception building SessionFactory..: " ex.getMessage (), ex.}} public static final threadlocal session = new threadlocal (); public static session getsession () THROWS HIBERNATEXCEPTION {session s = (session) session.get (); // If there is no one Available threads opens a new session, if (s == null) {conn = dbconnectionManager.getConnection (); s = sessionFactory.opensession (conn); session.set (s);} return s;} public static void CloseSession () throws hibernateException {session s = (session) session.get (); session.set (null); if (s! = null) s.close (); if (conn! = null) DBConnectionManager.ReturnConnection (conn) }} DBConnectionManager.getConnection () is a DAO class, providing connection pool implementation. We use this CON connection to create a session, Sission is a database connection to the session period, which provides powerful management data. In the future, we can use Hi.GetSession () in an action method method to get a session support. Typical applications are as follows:

Try {// Open a session and start the transaction rollback capability session session = hi.getations (); transaction tx = session.begintransaction (); // Query the database, use HQL Query Q = Session.createQuery ("from topic as Topic ORDER BY TOPIC.ID DESC "); Q.SetFirstResult (0); Q.SetMaxResults (5); // Get a list product list new path new path newtopiclist = q.list (); // Service processing newtopiPICList NTLBean = New NewTopiPICLIST (); Ntlbean.setlist (newtopiclist); Req.setttribute ("newtopiclist", ntlbean; // transaction submission, remember to close the session! TX.comMit (); hi.closesession ();} // Because the entire session will throw an exception, you need to use try-catch to wrap Catch (HibernateException E) {// log log.error (E.TOSTRING )));} The HQL can be used to learn from Hibernate official documentation. Third, Struts Struts configuration file struts-config.xml is placed under the application / web-inf / directory, the rough configuration is as follows

< / action-mapings> Here is a visual tool called Struts-Console, current version 4.8, free download available When the configuration file does not need to remember, please refer to it, copy one to change it. Just here mainly design, what is the design, what Action, their relationship, and so on. A good Designed to definitely save a lot of rework possibilities. Struts has a "struts on action", absolutely learning Struts classic books, I have the first 8 chapters of translation in my hand, I can contact me in need. We are not detailed here. Describe the process of each configuration, only struts and hibernate cooperation. An action has an Execute method, of course, can also be used by Perform methods, but the Perform method is not recommended in Struts1.1, but uses a more powerful execute () method. Net.seerlog.action;

转载请注明原文地址:https://www.9cbs.com/read-64516.html

New Post(0)