欢迎光临
我们一直在努力

Eclipse快速上手Hibernate–5. 组件映射-JSP教程,Java技巧及代码

建站超值云服务器,限时71元/月

    这篇文章主要说的是在hibernate中的组件(component)映射,可以参考hibernate官方文档的第7章。至于环境设置,可以参考这个系列的前面几篇文章。  1. 创建项目 ·  新建一个java项目:componentmapping,注意选中“创建单独的源文件夹和输出文件夹”,同时添加“用户库”:hibernate。   2. 编写类文件 ·  新建一个类,包名:javamxj.hibernate.component,类名:person。
person.java

/* * hibernate – 组件(component)映射 * 创建日期 2005-4-10 * @author javamxj(分享java快乐) * @link blog: htpp://javamxj.mblogger.cn * htpp://blog.csdn.net/javamxj/ */package javamxj.hibernate.component;/** * @hibernate.class */public class person { private long id; private string username; private address address; /** * @hibernate.id * generator-class="hilo" * unsaved-value="null" */ public long getid() {return id;} public void setid(long id) {this.id = id;} /** * @hibernate.property * length="15" * unique="true" * not-null="true" */ public string getusername() {return username;} public void setusername(string username) {this.username = username;} /** * @hibernate.component */ public address getaddress() {return address;} public void setaddress(address address) {this.address = address;}}
·  person类调用了address类,注意在“getaddress()”方法上的“ @hibernate.component”标记。 ·  address类只含有一些“ @hibernate.property”标记,没有将其独立映射为一个表。
address.java

package javamxj.hibernate.component;public class address { private string country; private string city; private string street; private string zipcode; public address() {} public address(string country, string city, string street, string zipcode) { super(); this.country = country; this.city = city; this.street = street; this.zipcode = zipcode; } /** * @hibernate.property * length = "12" */ public string getcity() {return city;} public void setcity(string city) {this.city = city;} /** * @hibernate.property * length = "12" */ public string getcountry() {return country;} public void setcountry(string country) {this.country = country;} /** * @hibernate.property * length = "6" */ public string getzipcode() {return zipcode;} public void setzipcode(string number) {this.zipcode = number;} /** * @hibernate.property * length = "12" */ public string getstreet() {return street;} public void setstreet(string street) {this.street = street;} public string tostring(){ return ("居住在"+ country + city+"市"+ street+"区" + "\n\t邮政编码: "+ zipcode); }}
  3. 运行任务 ·  复制《eclipse快速上手hibernate–4. 继承映射(1)》文中的build.xml到项目目录下。·  双击“generate-hbm”任务,会发现在包中多了一个animal.hbm.xml文件,在src目录下会多了一个hibernate.cfg.xml文件,如果没有,按f5键刷新一下。
person.hbm.xml

<?xml version="1.0" encoding="gbk"?><!doctype hibernate-mapping public "-//hibernate/hibernate mapping dtd 2.0//en" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping> <class name="javamxj.hibernate.component.person" dynamic-update="false" dynamic-insert="false" select-before-update="false" optimistic-lock="version" > <id name="id" column="id" type="java.lang.long" unsaved-value="null" > <generator class="hilo"> <!– to add non xdoclet generator parameters, create a file named hibernate-generator-params-person.xml containing the additional parameters and place it in your merge dir. –> </generator> </id> <property name="username" type="java.lang.string" update="true" insert="true" access="property" column="username" length="15" not-null="true" unique="true" /> <component name="address" class="javamxj.hibernate.component.address" > <property name="city" type="java.lang.string" update="true" insert="true" access="property" column="city" length="12" /> <property name="country" type="java.lang.string" update="true" insert="true" access="property" column="country" length="12" /> <property name="zipcode" type="java.lang.string" update="true" insert="true" access="property" column="zipcode" length="6" /> <property name="street" type="java.lang.string" update="true" insert="true" access="property" column="street" length="12" /> </component> <!– to add non xdoclet property mappings, create a file named hibernate-properties-person.xml containing the additional properties and place it in your merge dir. –> </class></hibernate-mapping>
  · 运行mysql服务器,然后双击“schemaexport”任务,在项目根目录下,会产生一个“schema-export.sql”文件。schema-export.sql
drop table if exists persondrop table if exists hibernate_unique_keycreate table person ( id bigint not null, username varchar(15) not null unique, city varchar(12), country varchar(12), zipcode varchar(6), street varchar(12), primary key (id))create table hibernate_unique_key ( next_hi integer )insert into hibernate_unique_key values ( 0 )
 ·  切换到数据库中,会发现已经自动产生了数据表person 5. 测试程序 ●   这一次不同于前面的几个实例,这次先实现一个hibernateutil辅助类,用来管理hibernate的session,这样测试类的代码就比较简单了,可以参考hibernate官方文档的第1章。 ·  新建一个类,包名:javamxj.hibernate.util,类名:hibernateutil,代码如下:
hibernateutil.java

package javamxj.hibernate.util;import org.apache.commons.logging.log;import org.apache.commons.logging.logfactory;import net.sf.hibernate.hibernateexception;import net.sf.hibernate.session;import net.sf.hibernate.sessionfactory;import net.sf.hibernate.transaction;import net.sf.hibernate.cfg.configuration;public class hibernateutil { private static log log = logfactory.getlog(hibernateutil.class); private static sessionfactory sessionfactory; private static final threadlocal threadsession = new threadlocal(); private static final threadlocal threadtransaction = new threadlocal(); public static sessionfactory getsessionfactory() { if (sessionfactory == null) { try { // create the sessionfactory sessionfactory = new configuration().configure() .buildsessionfactory(); } catch (hibernateexception ex) { ex.printstacktrace(); throw new runtimeexception("configuration problem: " + ex.getmessage(), ex); } } return sessionfactory; } public static session currentsession() throws hibernateexception { session s = (session) threadsession.get(); // open a new session, if this thread has none yet if (s == null) { s = getsessionfactory().opensession(); log.debug("###opening new session for this thread:" + s); threadsession.set(s); } else { log.debug("###session was existed:" + s); } return s; } public static void closesession() throws hibernateexception { session s = (session) threadsession.get(); threadsession.set(null); if (s != null) { log.debug("###closing session of this thread. " + s); s.close(); } } public static void begintransaction() throws hibernateexception { transaction tx = (transaction) threadtransaction.get(); try { if (tx == null) { tx = currentsession().begintransaction(); log.debug("###starting new database transaction in this thread:"+ tx); threadtransaction.set(tx); } else { log.debug("###tx was existed:" + tx); } } catch (hibernateexception ex) { throw ex; } } public static void committransaction() throws hibernateexception { transaction tx = (transaction) threadtransaction.get(); try { if (tx != null && !tx.wascommitted() && !tx.wasrolledback()) { log.debug("###committing database transaction of this thread."); tx.commit(); } threadtransaction.set(null); } catch (hibernateexception ex) { rollbacktransaction(); throw ex; } } public static void rollbacktransaction() throws hibernateexception { transaction tx = (transaction) threadtransaction.get(); try { threadtransaction.set(null); if (tx != null && !tx.wascommitted() && !tx.wasrolledback()) { log.debug("###tyring to rollback database transaction of this thread."); tx.rollback(); } } catch (hibernateexception ex) { throw ex; } finally { closesession(); } }}
  ·  好了,然后在包javamxj.hibernate.component下新建一个componentdemo.java类。
componentdemo.java

package javamxj.hibernate.component;import java.util.iterator;import java.util.list;import javamxj.hibernate.util.hibernateutil;import net.sf.hibernate.hibernateexception;import net.sf.hibernate.session;public class componentdemo { public static void main(string[] args) { try { new componentdemo(); } catch (hibernateexception he) { he.printstacktrace(); } } public componentdemo() throws hibernateexception { session sess = hibernateutil.currentsession(); person p = new person(); p.setaddress(new address("中国", "上海", "普陀", "200055")); p.setusername("javamxj"); sess.save(p); p = new person(); p.setaddress(new address("中国", "北京", "海淀", "100086")); p.setusername("张三"); sess.save(p); list animals = sess.find("from " + person.class.getname()); for (iterator it = animals.iterator(); it.hasnext();) { person person = (person) it.next(); system.out.println(person.getusername() + ":" + person.getaddress()); } hibernateutil.closesession(); }}
 ·  运行这个类,控制台输出如下: ·  同时,数据表中生成如下数据: ·  最后的项目结构如下:   

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Eclipse快速上手Hibernate–5. 组件映射-JSP教程,Java技巧及代码
分享到: 更多 (0)

相关推荐

  • 暂无文章