Hibernate first experience Cat quick start

xiaoxiao2021-03-06  73

Hibernate's CAT example feels unktown, it is difficult to run the first example with it, take a point of discount, I finally see a result, if you are a newbie, you can refer to it, less detours .

1. Download Tomcat and Hibernate

Tomcat 5.0.27http: //apache.linuxForum.Net/dist/jakarta/tomcat-5/v5.0.27/bin/jakarta-tomcat-5.0.27.ziptomcat 5.0.28Http: //apache.linuxForum.net/dist/ JAKARTA / TOMCAT-5 / V5.0.28 / bin / jakarta-tomcat-5.0.28.zipHibernate2.1.6http: //prdownloads.sourceForge.Net/Hibernate/? sort_by = Date & Sort = DESC

2. Installation

Take Tomcat MySQL Hibernate as an example

Tomcat installation, and mysql installation and DBCP formulation See http://blog.9cbs.net/ahxu/archive/2004/09/01/91611.aspx, here is not mentioned, here it is assumed that tomcat mysql has been configured And test, here% webapp% represents root of a web application you have configured, focusing on how Hibernate installation,

1) Unzip the downloaded compressed package, copy the Hibernate2.jar to% WebApp% / WEB-INF / LIB

2) will decompress the LIB directory

CGLIB-FULL-2.0.2.jarcommons-Collections-2.1.1.jarcommons-logging-1.0.4.jardom4j-1.4.jarehcache-0.9.jarjta.jarlog4j-1.2.8.jarodmg-3.0.jar

Documents are also copied to% WebApp% / Web-INF / LIB. For details, see README.TXT under the decompressed LIB directory. 3) will decompress the ETC directory

Log4j.properties

Documents are copied to% webApp% / web-inf / class.

3. Write related files

1) Follow the reference documents, configure hibernate, save the following code as hibernate.cfg.xml placed under the% WebApp% / Web-INF / CLASSES

java: comp / env / jdbc / mysql false Net.sf.hibernate.diaalect.mysqldiaalect Note: Here is different from the Hibernate document, here specifying the data source is mysql database JDBC / MySQL, dialect DiaLect is Net.sf.hibernate.Dialect.MysqldiaAlact.

2) Save the following code as Cat.java, and generate corresponding Cat.class, put% WebApp% / Web-INF / CLASSES, where you use what method to generate Cat.class, but final Cat.Class should be% WebApp% / Web-INF / CLASSES / NET / SF / Hibernate / Examples / QuickStart directory

package net.sf.hibernate.examples.quickstart; 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;}}

3) Save the following code as an O / R mapping file Cat.hbm.xml, put% WebApp% / Web-INF / CLASSES

Public "- // hibernate / hibernate mapping dtd // en"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

Generated by hibernate with the uuid pattern. ->

4) Construction form in the database, the structure is as follows

Column | Type | Modifier

-------- ---------------------- -----------

CAT_ID | Character (32) | NOT NULL

Name | Character Varying (16) | NOT NULL

SEX | Character (1) |

Weight | Real |

Indexes: CAT_PKEY PRIMARY Key Btree (Cat_ID)

5) Save the following code as Hibernateutil.java, and generate the corresponding hibernateutil.class, put% WebApp% / Web-INF / CLASSES, also pay attention to Package

Package net.sf.hibernate.examples.quickstart;

Import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory;

Import net.sf.hibernate. *;

import net.sf.hibernate.cfg *;. public class HibernateUtil {private static Log log = LogFactory.getLog (HibernateUtil.class); private static final SessionFactory sessionFactory; static {try {// Create the SessionFactorysessionFactory = new Configuration (). . configure () buildSessionFactory ();} catch (Throwable ex) {log.error ( "Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError (ex);}} public static final ThreadLocal session = new ThreadLocal (); Public static session currentations () throws hibernateException {session s = (session) session.get (); // Open a new session, if this thread has none yetif (s == null) {s = sessionFactory.openSession (); session .SET (s);} return s;} shRows HibernateException {session s = (session) session.get (); session.set (null); if (s! = null) S.Close );}} Note: Here is also different from the Hibernate document. There are 2 packages that are missing when the original document is completed.

6) Save the following code as Test.jsp, put% WebApp% / with HTTP test

<% @ page language = "java" PageEncoding = "GB2312"%> <% @ page import = "net.sf.hibernate.Transaction"%> <% @ page import = "net.sf.hibernate.Session"%> <% @ page import = "Net.sf.hibernate.cfg. *"%> <% @ page import = "net.sf.hibernate.query"%> <% @ page import = "net.sf.hibernate.examples .quickstart.hibernateutil "%> <% @ page import =" net.sf.hibernate.examples.quickstart.cat "%> <% @ Page Import =" java.util. * "%> Lomboz JSP </ title> </ head> <body bgcolor =" # ffffff "> <% // Add a CAT Session sees = hibernateutil.currentSession (); Transaction TX = SES.BEGINTRANSACTION (); CAT Princess = new cat (); princess.setname ("AHXU"); Princess.setSex ('f'); Princess.setWeight (7.4f SES.SAVE (Princess); tx.commit (); hibernateutil.closesession (); // Read all cat ses = hibernateutil.currentSession (); tx = ses.begintransaction (); query query = SES. CreateQuery ("SELECT C from cat as c where c.sex =: sex"); query.setCharacter ("sex", 'f'); for (item it = query.Iterate (); it.hasn EXT ();) {Cat Cat = (CAT) IT.Next (); Out.println ("Female Cat:" Cat.getName ());} TX.commit (); hibernateutil.closesis ();%> </ body> </ html> small knot</p> <p>The steps are basically the same as the original document step, just have some additions, convenient to play, there is no specific explanation for some of these configurations, please refer to the related document in the release package if you have any questions.</p> <p>The above Tomcat5.027 Hibernate2.1.6 test passed</p> <p>Attachment:</p> <p>Tomcat official website http://jakarta.apache.org/tomcat/index.htmlhib: //www.hibernate.orghibernamte unofficial Chinese network http://www.hibernate.org.cnmysql official graphics management tool graphical Clients - DiffERENT GUI Interfaces To Administer MySQL AND DATAMYSQL Administrator MySQL Query Browser MySQL Control Center (No Longer Under Development)</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-120675.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="120675" 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 = 'Ttqnqb8tcTFRDh3MMxKBHT0XWUdoE1jsdSHlGh41NXzBJ_2BcjXWHRaIokL3vszrrfAhIGxkz81mJ1_2BfvPQZ6evg_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>