Hibernate configuration notes

xiaoxiao2021-03-06  57

An example of a configuration:

1. First create a table CAT in the database

Create Table Cat

CAT_ID VARCHAR (20) Primary Key Not Null,

Name varchar (20) Not null,

SEX Char (1))

2. Establish hibernate.cfg.xml and generate hibernaetfactory.class to manage him

Hibernate.cfg.xml

"- // Hibernate / Hibernate Configuration DTD 2.0 // en"

"

http://hibernate.sourceForge.Net/Hibernate-configuration-2.0.dtd ">>

root JDBC: mysql: // localhost: 3306 / test < / property> net.sf.hibernate.dialect.MySQLDialect org. gjt.mm.mysql.driver

hibernaetfactory.javaPackage com.mdcl.hibaNate;

Import net.sf.hibelnate.hibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.cfg.configuration;

/ ** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html}. * / Public class HibernateFactory {

/ ** * Location of hibernate.cfg.xml file * NOTICE:.. Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file That * is place the config file in a Java package - the default location * is the default Java package

* Examples:..
* CONFIG_FILE_LOCATION = "/hibernate.conf.xml" * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml ". * / private static string config_file_location =" /Hibernate.cfg.xml";/** Holds a single instance of session * / private static final threadlocal threadlocal = new threadlocal ();

/ ** The Single Instance of Hibernate Configuration * / Private Static Final Configuration CFG = New Configuration ();

/ ** The single instance of hibernate SessionFactory * / private static net.sf.hibernate.SessionFactory sessionFactory; public static Session currentSession () throws HibernateException {Session session = (Session) threadLocal.get ();! If (session = null && ! session.isopen ()) session = null; if (session == null) {if (sessionFactory == null) {Try {cfg.configure; sessionFactory = cfg.buildsessionFactory ();} catch (Exception E) {System.err .println ("%%%% Error Creating HibernateSessionFactory %%%); E.PrintStackTrace ();}} session = sessionFactory.OpenSession (); threadlocal.set (session);} returnction;} Public static void closesession () throws hibernateException {session session = (session) threadlocal.get (); threadLocal.Set (null); if (session! = null) {sessio n.close ();}}}}}}}}}}}} private hibernateFactory ()}

} 3. Establish a CAT table PO (persistent object) to generate Cat.cfg.xml, Cat.java, AbstractCat.java process and the process of generating hibernate.cfg.xml and HibernateFactory.java can be completed by MyEClipse. Cat.cfg.xml

< Generator class = "uuid.hex" /> cat.java

/ * * Created thu feb 17 16:11:44 cst 2005 by myeclipse hibernate Tool. * / Package com.mdcl.vo;

Import java.io.serializable;

/ ** * A class that represents a row in the 'cat' table. * This class may be customized as it is never re-generated * after being created. * / Public class Cat extends AbstractCat implements Serializable {/ ** * Simple CONSTRUctor of cat instances. * / public cat () {}

/ * (non-javadoc) * @see com.mdcl.vo.abstractcat # getcatid () * / public string getcatid () {// Todo auto-generated method stub return super.getcatid ();} / * (non- Javadoc) * @see com.mdcl.vo.abstractcat # getName () * / public string getname () {// Todo auto-generated method stub return super.getname ();} / * (non-javadoc) * @see Com.mdcl.vo.abstractcat # getsex () * / public string getsex () {// Todo auto-generated method stub return super.getSex ();} / * (non-javadoc) * @see com.mdcl.vo .ABSTRACTCAT # getWeight () * // * (Non-javadoc) * @see com.mdcl.vo.abstractcat # setcatid (java.lang.string) * / public void setcatid (String catid) {// Todo Auto-generated Method stub super.setcatid (catid);} / * (non-javadoc) * @see com.mdcl.vo.abstractcat # setname (java.lang.string) * / public void setname (String name) {// Todo Auto -Generated method stub super.setname (Name);} / * (non-javadoc) * @see com.mdcl.vo.abstractcat # setsex (java.lang.string) * / public void setsex (string sex) {//// Todo Auto-GE Nerated method stub super.setsex (sex);} / * (non-javadoc) * @see com.mdcl.vo.abstractcat # setWeight (java.lang.integer) * /

/ * (Non-javadoc) * @see java.lang.object # hashcode () * / public int 6code () {// Todo auto-generated method stub return super.hashcode ();} / * (non-javadoc) * @see java.lang.object # femance () * / protected void finalize () throws throwable {// Todo auto-generated method stub super.Finalize ();} / * (non-javadoc) * @see java.lang .Object # clone () * / protected Object clone () throws CloneNotSupportedException {// TODO Auto-generated method stub return super.clone ();} / * (non-Javadoc) * @see java.lang.Object # equals ( Java.lang.Object) * / public boolean equals (object obj) {// Todo auto-generated method stub return super.equals (obj);} / * (non-javadoc) * @see java.lang.object # toString () * / Public string toString () {// Todo auto-generated method stub return super.tostring ();} / ** * Constructor of cat instances given a simple primary key. * @Param catid * / public cat (java .lang.string catid) {super ();} / * add customized code below * /

} AbstractCat.java/* * WARNING:... DO NOT EDIT THIS FILE This is a generated file that is synchronized * by MyEclipse Hibernate tool integration * * Created Sat Feb 19 12:00:50 CST 2005 by MyEclipse Hibernate Tool * / Package com.mdcl.vo;

Import java.io.serializable;

/ ** * a class this represents a row in the cat table. * You can customize the behavior of this class by editing the class, {@link cat ()}. * Warning: do not edit this file. This is a recogn . file that is synchronized * by MyEclipse Hibernate tool integration * / public abstract class AbstractCat implements Serializable {/ ** The cached hash code value for this instance Settting to 0 triggers re-calculation * / private int hashValue = 0..;

/ ** The composite primary key value. * / Private java.lang.string catid; / ** The value of the simple name property. * / Private java.lang.string name;

/ ** the value of the simple sex property. * / Private java.lang.string sex;

/ ** * Simple constructor of abstractcat instances. * / Public abstractcat () {}

/ ** * Constructor of Abstractcat Instances Given a Simple Primary Key. * @Param Catid * / Public Abstractcat (Java.lang.String Catid) {this.setcatid (CAcid);

/ ** * Return The Simple Primary key value That Identifies this object. * @Return java.lang.string * / public java.lang.string getcatid () {return catid;}

/ ** * set the Simple primary key value That Identifies this object. * @Param catid * / public void setcatid (java.lang.string catid) {this.hashvalue = 0; this.catid = catid;}

/ ** * Return the value of the name column. * @Return java.lang.string * / public java.lang.string getName () {Return this.name;}

/ ** * set the value of the name column. * @Param name * / public void setName (java.lang.string name) {this.name = name;}

/ ** * Return the value of the sex column. * @Return java.lang.string * / public java.lang.string getsex () {return this.sex;}

/ ** * set the value of the sex column. * @Param sex * / public void setsex (java.lang.string sex) {this.sex = sex;}

/ ** * Implementation of the equals comparison on the basis of equals comparison on the basis of equals. * @Param rhs * @return boolean * / public boolean equals (object rhs) {if (rhs == null) Return False; if ( (RHS Instanceof Cat) Return False; Cat That = (CAT) RHS; IF (this.getcatid ()! = null && That.getcatid ()! = NULL) {if (! this.getcatid (). Equals. that.getCatId ())) {return false;}} return true;.} / ** * Implementation of the hashCode method conforming to the Bloch pattern with * the exception of array properties (these are very unlikely primary key types) * @ Return Int * / Public INT HashCode () {if (this.hashvalue == 0) {int result = 17; int CatidValue = this.getcatid () == null? 0: this.getcatid (). hashcode (); result = Result * 37 CatidValue; this.hashvalue = Return this.hashvalue;}} 4. Write an example to test servlettest.java/* * created on 2005-2-19 * * Todo to change the template for this generated file go to * window - preferences - java - Code style - code templates * / package com.mdcl.test;

Import java.io.ioException; import java.io.printwriter;

Import javax.servlet.ServletException; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse;

Import net.sf.hibelption; import net.sf.hibernate.Session; import net.sf.hibernate.transaction;

Import org.apache.log4j.logger;

import com.mdcl.hibernate.HibernateFactory; import com.mdcl.vo.Cat; / ** * @author a * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates * / public class servlettest extends httpservlet {

/ ** * deStruction of the servlet.
* / private static logger log = logger.getlogger (servlettest.class); public void destroy () {super.destroy (); // Just Puts "Destroy" string in log // put your code here}

/ ** * The doget method method of the servlet.
* * this method is called when a form is it. * * @Param Request the Request Send by the client to the server * @Param Response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred * / public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);

}

/ ** * The dopost method of the servlet.
* * this method IS Called When a form HAS ITS TAG VALUE METHOD Equals to post. * * @Param Request the Request Send by The Client To the Server * @Param Response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred * / public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Response.setContentType ("text / html"); printwriter out = response.getwriter (); out .println ("") Out.println (""); OUT.Println (" a servlet </ title> </ head>"); out.println ("<body>"); Out.print ("This is"); out.print (this.getClass ()); try {log.info ("........ servlettest.dopost () .... start"); session session = HibernateFactory .currentations (); transaction tx = session.begintransaction (); Cat Cat = new cat (); cat.setcatid ("4"); Cat.setName ("Karl"); Cat.SetSex ("f"); session .save (cat); tx.commit ();} catch (hibernateException e) {E.PrintStackTrace (); log.error ("........ servlettest.dopost () .... error") Log.debug ("start"); out.println (", using the post method"); out.println ("</ body>"); out.println ("</ html>"); OUT. Flush (); out.close (); log.info ("........ servlettest.dopost () .... End");} / ** * Initialization of the se RVlet. <br> * * @Throws servletexception if an error itis init () THROWS servletexception {// put your code here}</p> <p>} Ok, complete Hibernate travel. Don't you understand? Reference Hibernate Chinese Documentation Hibernate Chinese Site Http://www.hibernate.org.cn/</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-40645.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="40645" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '5RcYJlM9p9zNASDlGtt8NpOUscPW_2BkmXjBFpI60F6SVYZO179Sh28ks70w1XASWodNH6rIhHoS_2FByUVZcTdPfQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>