在進行這個實例之前,先說之前出現(xiàn)的問題: 1、類前面一定要避免有空格,在這之前,從未想過類名前面有空格還能創(chuàng)建文件;在配置的時候,會出現(xiàn)如果沒有空格,就無法找到映射類。當(dāng)然,加了空格就可以,但請避免使用。 2、在配置過程中,請一定要根據(jù)需要創(chuàng)建數(shù)據(jù)庫表,并且這個表的主鍵是否考慮整型,默認(rèn)值,是否自增等。 3、運行過程中報錯,優(yōu)先看控制臺,判斷出錯問題,快速定位;如無法找到,再運用其他技巧。 下面:先將之前幾個實例用到的數(shù)據(jù)庫表及本次使用的表貼出來: 表1: CREATE TABLE `customers` ( `customerID` varchar(8) NOT NULL, `name` varchar(15) DEFAULT NULL, `phone` varchar(16) DEFAULT NULL, PRIMARY KEY (`customerID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 表2: CREATE TABLE `customers2` ( `customerID` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(15) DEFAULT NULL, `phone` varchar(16) DEFAULT NULL, PRIMARY KEY (`customerID`) ) ENGINE=InnoDB AUTO_INCREMENT=1015 DEFAULT CHARSET=utf8; ? 表3: CREATE TABLE `customers3` ( `customerID` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(15) DEFAULT NULL, `phone` varchar(16) DEFAULT NULL, PRIMARY KEY (`customerID`) ) ENGINE=InnoDB AUTO_INCREMENT=1015 DEFAULT CHARSET=utf8; ? 表4:(略,Oracle數(shù)據(jù)庫測試) 表5: CREATE TABLE `customers5` ( `customerID` varchar(50) NOT NULL, `name` varchar(15) DEFAULT NULL, `phone` varchar(16) DEFAULT NULL, PRIMARY KEY (`customerID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 表5示例 uuid.hex生成方式【依據(jù)機器標(biāo)識等自生】 一、Customer.hbm.xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www./dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="bean" auto-import="false"> <!-- POJO類映射表及某表的關(guān)系--> <class name="bean.Customer5" table="customers5" catalog="test"> <id name="customerID" type="java.lang.String"> <column name="customerID"/> <generator class="uuid.hex"></generator> </id> <!-- 映射表中name字段 --> <property name="name" type="java.lang.String"> <column name="name" length="40"/> </property> <!-- 映射表中phone字段 --> <property name="phone" type="java.lang.String"> <column name="phone" length="16"/> </property> </class> </hibernate-mapping> 二、hibernate.cfg.xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www./dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!-- 配置文件標(biāo)簽順序property*,mapping*,(class-cache|collection-cache),event,listener* --> <session-factory> <!-- 設(shè)置訪問mysql數(shù)據(jù)庫的驅(qū)動描述 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 設(shè)置數(shù)據(jù)庫的url --> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property> <!-- 指定登錄數(shù)據(jù)庫用戶賬戶 --> <property name="connection.username">root</property> <!-- 指定登錄數(shù)據(jù)庫用戶密碼 --> <property name="connection.password">123456</property> <!-- 設(shè)置訪問數(shù)據(jù)庫的方言,提高數(shù)據(jù)庫訪問性能 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 設(shè)置ddl --> <!-- <property name="hbm2ddl.auto">auto</property> --> <!-- 配置控制臺視圖,顯示查詢內(nèi)容 --> <property name="show_sql">true</property> <!-- 下面是多表映射 --> <!-- 指出映射文件 --> <mapping resource="resource/Customer.hbm.xml"/> <!-- 映射文件 --> <mapping resource="resource/Customer2.hbm.xml"/> <!-- 映射文件 --> <mapping resource="resource/Customer3.hbm.xml"/> <!-- 映射文件 --> <mapping resource="resource/Customer5.hbm.xml"/> </session-factory> </hibernate-configuration> 三、Customer5.java package bean; //驗證uuid.hex生成主鍵方式的映射類,數(shù)據(jù)庫對應(yīng)表customers2 public class Customer5 { private String customerID; private String name,phone; public String getCustomerID() { return customerID; } public void setCustomerID(String customerID) { this.customerID = customerID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } 四、HibernateSessionFactory.java package hibernate.factory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static String configfile = "resource/hibernate.cfg.xml"; /**ThreadLocal是一個本地線程**/ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration config; private static SessionFactory sessionFactory; /**讀取配置文件,創(chuàng)建一個工廠會話,這段代碼為靜態(tài)塊,編譯后已經(jīng)運行**/ static{ try { config = new Configuration().configure(configfile); sessionFactory = config.buildSessionFactory(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /**通過會話工廠打開會話,就可以訪問數(shù)據(jù)庫了**/ public static Session getSession(){ Session session = (Session)threadLocal.get(); if (session==null||!session.isOpen()) { if (sessionFactory==null) { rebuildSessionFactory(); } session = (sessionFactory!=null)?sessionFactory.openSession():null; } return session; } /**重新創(chuàng)建一個會話工廠**/ public static void rebuildSessionFactory() { try { config.configure(configfile); sessionFactory = config.buildSessionFactory(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /**關(guān)閉與數(shù)據(jù)庫的會話**/ public static void closeSession() { Session session = (Session)threadLocal.get(); threadLocal.set(null); if (session!=null) { session.close(); } } } 五、Customer5Demo.java package bean; import java.util.List; import hibernate.factory.HibernateSessionFactory; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; //用于測試increment主鍵生成方式,增加記錄,不建議使用,他是實例自增,多實例訪問時,會重復(fù)主鍵,出問題 //由于是增加數(shù)據(jù),所以不需要寫Query,只需要new表,增加數(shù)據(jù)即可 public class Customer5Demo { Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction(); public static void main(String[] args) { //測試increment主鍵生成 Customer5Demo demo = new Customer5Demo(); Customer5 customer5 = new Customer5(); demo.saveCustomer5IDByIdentity(customer5, "華山", "580"); //測試查詢結(jié)果 List list = demo.queryAllCustomer5(); for (int i = 0; i < list.size(); i ) { Customer5 customer = (Customer5)list.get(i); System.out.println(customer.getCustomerID() customer.getName() customer.getPhone()); } HibernateSessionFactory.closeSession(); } //下面是封裝保存 public void saveCustomer5IDByIdentity(Customer5 customer5,String name,String phone) { customer5.setName(name); customer5.setPhone(phone); session.save(customer5); //一定一定要記得提交事務(wù) tran.commit(); } //下面是封裝查詢 @SuppressWarnings("rawtypes") public List queryAllCustomer5(){ /**由會話工廠類創(chuàng)建一個會話Session對象**/ Session session = HibernateSessionFactory.getSession(); /**由會話session對象創(chuàng)建一個查詢對象**/ Query query = session.createQuery("from bean.Customer5"); List list = query.list(); HibernateSessionFactory.closeSession(); return list; } } ? 來源:http://www./content-4-218801.html |
|