I haven't learned it in a few days, I finally arrived this afternoon. I have thought of hibernate, so I started writing Hibernate's first code running in Tomcat, using the database is MySQL, using a servlet, using JSP directly. I have found that I have not experienced servlet programming, but I am not used to it. It is convenient than servlet, although the code is not debugged, but does not use the reload app after modifying the code, and the configuration file does not write.
Back to the topic, in fact, in the afternoon, step by step, according to the manual comes with Hibernate, good, there is a Chinese version, which is very good for Hibernate promotion.
-----------------
1. As usual uses Eclipse, build a new project, I am named Hibstart (because the most entry framework is more, QuickStart is not good).
2. Create a directory structure, web-inf, web-inf / bin, web-inf / classes, src, etc., set the Output path. Then Hibernate must use the seven JAR envelopes to Web-Inf / Bin (DOM4J, CGLIB, Commons Collection, Commons Logging, Odmg4, Ehcache, Log4j, Hibernate2, I also copied a log4j past. Start missing One, there is a problem, depressed for me half a day), drive JDBC to the% Tomcat% / Common / Lib.
3. Because the Tomcat connection pool is used, modify Tomcat / Conf / Sever.xml
Java: Comp / Env / JDBC / Hibstart. To test this connection pool, there is no problem, you can check the Tomcat document, there is an example of a test even the connection pool of MySQL.
4. write
Hibernate.cfg.xml, put it under the src directory, configure the Hibernate file
xml version = '1.0' encoding = 'UTF-8'?>
session-factory>
hibernate-configuration> The data source used is defined, whether it displays SQL statement information, dialects, and database maps.
5. Define Pojo
Package com.maxway.web.model;
Public class cat {
Private string id;
PRIVATE STRING NAME;
Private char sex;
PRIVATE FLOAT Weight;
Public cat () {}
Public string getId () {return id;}
Private void setid (string id) {this.id = id;}
Public string getname () {return name;}
Public void setname (String name) {this.name = name;}
Public char getsex () {return sex;}
Public void setsex (char sex) {this.sex = sex;}
Public float getWeight () {return weight;}
Public void setWeight (float weight) {this.weight = weight;
} It is all as long as it defines a variable, you can automatically generate the GET / SET method with Eclipse.
6. write
Cat.hbm.xml, (also under SRC, Eclipse will automatically compile to Web-INF / CLASSES) is the mapping of CAT this POJO to the database
XML Version = "1.0"?>
clas>
hibernate-maping> About Generator I think INT types provided by the database are good, there is no need to use Hibernate, here is the UUID generator.
Column | Type | Modifier
-------- ---------------------- -----------
CAT_ID | VARCHAR (32) | NOT NULL
Name | VARCHAR (32) | Not null
SEX | char (1) |
Weight | float |
CAT_ID PRIMARY Key old man practical mysql tools to build table
7. Hibernate is mainly to manipulate the database in the session interface, and session creates through sessionFactory.opensession (), sessionFactory (). Configure (). BuildSessionFactory (); get,
SessionFactory is usually only initialized once, so created a secondary class
/ * * CREATED ON 2005-2-18 * * This class not only uses SessionFactory in its static properties, but also uses Threadlocal to save the current working thread. * / Package com.maxway.web.util;
Import net.sf.hibelnate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.cfg.configuration;
Import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; / ** * Hibernate Gets Basic Session (Hibernate's work unit). *
* sessionFactory sessionFactory = new configuration (). Configure () * .buildsessionFactory (); * pre> * ** sessionFactory is responsible for a database, and only one XML configuration file (hibernate.cfg .xml). By creating * sessionFactory (it is not variable), you can access Configuration to set additional properties (or even modify the mapping metadata).
* Where should we create sessionFactory, how to access it in our program?
* SessionFactory is usually only initialized once, such as through a load-on-startup servlet.
* This means that you should not hold it as an instance variable in Server, and should be placed elsewhere.
* More deeper, we need some Singleton mode, we can easily access SessionFactory in the program.
* This class also solves two problems: configuration and easy access to sessionFactory.
* p> * * @Author meijun * @Author hibernate.org * /Public class hibernateutil {
Private static log log = logfactory.getlog (HibernateUtil.class);
PRIVATE STATIC FINAL SESSIONFACTORY SESSIONFACTORY;
. Static {try {// Create the SessionFactory sessionFactory = new Configuration () configure () .buildSessionFactory ();} catch (Throwable ex) {log.error (, ex "Initial SessionFactory creation failed."); Throw new ExceptionInInitializerError ( EX);}}
// Local Thread Public Static Final ThreadLocal Session = New Threadlocal ();
/ ** * Get the session from the local thread, not creating one, multiple calling this method to get the same session * * @return session * @Throws HibernateException * / public static session currentsession () THROWS HibernateException {session s = Session.get (); // Open a new session, if this thread has none yet if (s == null) {s = sessionFactory.openSession (); session.set (s);} return s;} / ** * Close Session * * @throws hibernateException * /
Public Static Void CloseSession () THROWS HibernateException {session s = (session) session.get (); // Delete session object session.set (null) in the local thread; // Close the actual session if (s! = null) S.Close ();}} Configure in Web.xml, let this class starts with Tomcat
Xml Version = "1.0" encoding = "ISO-8859-1"?>
hibernateutil servlet-name> com.maxway.web.util.hibernateUtil servlet-class> 0 loading ON-Startup> servlet> web-app> 8. Now all preparation configurations have been completed, start writing a JSP file to test it, the following Test.jsp implements a very simple feature, first insert a CAT data into the library, then display all CAT data in the library, so each Refresh will be recorded again. <% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Page Import = "com.maxway.web.util. *"%> <% @ page import = "com.maxway.web.model .Cat "%> <% @ page import =" Net.sf.hibernate. * "%> <% @ Page import =" java.util.ITerator "%> <% session sessions = hibernateutil.currentSession (); Transaction TX = sessions.begintractions (); cat princess = new cat (); princess.setname ("princess"); Princess.SetSex ('f'); Princess.SetWeight (7.4f); sessions.save (princess); TX. Commit ();%>
test hibernate title> Female Cat: TD> " Cat.getName () " TD> TR> "); TX.comMit (); hibernateutil.closesis ();%> table> center> body> html> Finally I used log4j, so I still have to write a log4j.properties under SRC, Eclipse Automatically copy to CLASSES.
Open Tomcat, there should be a lot of information, but there is no error, if there is ERROR, or check the JAR package is not all, configuration issues, etc.
Access Test.jsp ... OK
-------------- When the SQL statement is not written, just use Hibernate's HQL when query, Hibernate supports multiple query methods.
PS: This article refers to the Hibernate manual, just written a JSP file and related profile, so that the example in the manual can run. Writing this article is to deepen your impression of Hibernate usage processes.
转载请注明原文地址:https://www.9cbs.com/read-56607.htmlNew Post(0)