標籤:finally 問題: ppi .hbm.xml map images rowset gen tran
問題:一個老師有多個家庭地址,如何儲存該老師的資訊?1.Address類:
package cn.siggy.pojo;public class Address {private String addr1;private String addr2;private String addr3;public String getAddr1() {return addr1;}public void setAddr1(String addr1) {this.addr1 = addr1;}public String getAddr2() {return addr2;}public void setAddr2(String addr2) {this.addr2 = addr2;}public String getAddr3() {return addr3;}public void setAddr3(String addr3) {this.addr3 = addr3;}}
2.Teacher類:
package cn.siggy.pojo;public class Teacher {private int id;private String name;private String sex;private Address address;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}}
3.Teacher.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.siggy.pojo"><class name="Teacher"><id name="id"><generator class="native"></generator></id><property name="name"/><property name="sex"/><!-- 組件 --><component name="address" class="Address"><property name="addr1"/><property name="addr2"/><property name="addr3"/></component></class></hibernate-mapping>
4.測試代碼:
package cn.siggy.test;import java.sql.SQLException;import javax.sql.rowset.serial.SerialException;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.junit.Test;import cn.siggy.pojo.Address;import cn.siggy.pojo.Teacher;import cn.siggy.util.HibernateUtil;public class HibernateTest {@Testpublic void testCreateDB(){Configuration cfg = new Configuration().configure();SchemaExport se = new SchemaExport(cfg);//第一個參數 是否產生ddl指令碼 第二個參數 是否執行到資料庫中se.create(true, true);}@Testpublic void testSave() throws HibernateException, SerialException, SQLException{Session session = null;Transaction tx = null;try{session = HibernateUtil.getSession();tx = session.beginTransaction();Teacher t = new Teacher();t.setName("老裴");t.setSex("男");Address address = new Address();address.setAddr1("西三旗");address.setAddr2("西直門");address.setAddr3("南六環");t.setAddress(address);session.save(t);tx.commit();}catch (HibernateException e) {if(tx!=null)tx.rollback();e.printStackTrace();throw e;}finally{HibernateUtil.closeSession();}}}
5.測試結果:
控制台資訊:
資料庫表資訊:
【6.2】hibernate_component