hibernate Day2 案例代碼

來源:互聯網
上載者:User

標籤:復原事務   緩衝   logs   建立對象   utf-8   l資料庫   java   null   www.   

1、編寫實體類Person

package com.icss.pojo;public class Person {private int uid;private String uname;private String pword;private String addr;public int getUid() {return uid;}public void setUid(int uid) {this.uid = uid;}public String getUname() {return uname;}public void setUname(String uname) {this.uname = uname;}public String getPword() {return pword;}public void setPword(String pword) {this.pword = pword;}public String getAddr() {return addr;}public void setAddr(String addr) {this.addr = addr;}@Overridepublic String toString() {return "Person [uid=" + uid + ", uname=" + uname + ", pword=" + pword+ ", addr=" + addr + "]";}}

  2、編寫person.hbm.xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.icss.pojo.Person" table="t_person"><id name="uid" column="uid"><generator class="native"></generator></id><property name="uname" column="uname"></property><property name="pword" column="pword"></property><property name="addr" column="addr"></property></class></hibernate-mapping>

  3、編寫hibernate.cfg.xml

<?xml version=‘1.0‘ encoding=‘UTF-8‘?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><!-- 設定資料庫資訊 必須配置 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_day01?useUnicode=true&characterEncoding=utf8</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><!-- 設定資料庫方言,就是針對不同的資料庫有不同的sql標準 --><property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property><!--下列是Database Explore綁定資料庫連接時候定義的資料來源名稱吧 無關緊要的一個東西,其實就是 Diver name --><property name="myeclipse.connection.profile">mysql</property><!-- 配置hibernate資訊 可選 --><!-- 輸出底層sql語句 --><property name="show_sql">true</property><!-- 輸出底層sql語句並格式化 --><property name="format_sql">true</property><!-- 使得hibernate協助我們建立表,因為表不會自己建立,需要我們進行配置使其自動建立 --><property name="hibernate.hbm2ddl.auto">update</property><!-- 把對應檔載入過來 --><mapping resource="com/icss/pojo/person.hbm.xml" /></session-factory></hibernate-configuration>

  4、編寫工具類

package com.icss.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtils {private static SessionFactory sf = null;private HibernateUtils() {// TODO Auto-generated constructor stub}public static SessionFactory getSessionFactory(){if(sf==null){Configuration cfg=new Configuration().configure();sf=cfg.buildSessionFactory();}return sf;}}  

       5、編寫hibernate的增刪改查     測試

package com.icss.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Ignore;import org.junit.Test;import com.icss.pojo.Person;import com.icss.util.HibernateUtils;public class HibernateCRUDCache {/** * CRUD操作 * 先解決中文問題,在配置資料連線時,指定編碼類別型,注意&即 * <property name="hibernate.connection.url"> * jdbc:mysql://localhost:3306/hibernate_day01?useUnicode=true&characterEncoding=utf8 * </property> */@Testpublic void test1() {Configuration cfg = new Configuration().configure("hibernate.cfg.xml");SessionFactory sf=cfg.buildSessionFactory();Session ss = sf.openSession();//開啟事務Transaction tx = ss.beginTransaction(); /** * 添加       * Person p=new Person(‘zs‘,‘123‘,‘shanghai‘); * ss.save(p); * 添加時,若是設定了已經存在的id,則save會自動處理id問題,是添加一條記錄(id自增) *//**  * 查詢 * 通過反射機制       指定使用具體的類和主鍵來找到對應的資料記錄 * Person object = (Person)ss.get(Person.class, 10); * System.out.println(object);  *//** * 修改 * 先查詢指定要修改的對象,然後再修改 * 修改過程中,到person表中,根據id找到指定對象,然後執行update陳述式完成修改 *   Person p=(Person)ss.get(Person.class,13); *   p.setUname("李四"); *   ss.update(p); *   若修改時,id不是查詢出來的,自己指定的,則要給出準確的id,且修改時,所有屬性均要設定,否則為null *//** * 刪除 * 先查詢指定要修改的對象,然後再刪除 * Person p = (Person)ss.get(Person.class,10); * ss.delete(p); *///一級緩衝驗證/**  System.out.println("--------------------");Person p = (Person)ss.get(Person.class,11);System.out.println(p);System.out.println("--------------------");Person p2 = (Person)ss.get(Person.class,11);System.out.println(p2);*///一級緩衝特性Person p = (Person)ss.get(Person.class,11);p.setUname("張三");p.setPword("000");p.setAddr("上海");tx.commit();ss.close();sf.close();}}/** * 實體類對象狀態(概念)    有三種 * 瞬時態:對象裡沒有id,對象與session沒有關聯,一般是添加操作 * Person p=new Person(‘zs‘,‘123‘,‘shanghai‘); * ss.save(p); *  * 持久態:對象有id,對象與session有關聯    查詢操作 * Person p = (Person)ss.get(Person.class,10); *  * 託管態:對象有id,但對象與session沒有關聯   自己建立的對象 *       瞬時態與託管態的區別:瞬時態未指定id值,託管態指定了id,但都是自己建立對象 *       注意:對自己建立的對象的指定id值時,save是添加操作,而saveOrUpdates是修改操作! *        * 在瞬時狀態,saveOrUpdate是做insert操作 * 在持久狀態,saveOrUpdate是做update操作 * 在託管狀態,saveOrUpdate是做update操作 */

         6、編寫hibernate的事務     測試  

package com.icss.test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.junit.Test;import com.icss.pojo.Person;import com.icss.util.HibernateUtils;public class HibernateTransaction {@Testpublic void test1() {SessionFactory sf = null;Session ss = null;Transaction tx = null;try {sf = HibernateUtils.getSessionFactory();// 使用sessionFactory建立Session對象ss = sf.openSession();// 開啟事務tx = ss.beginTransaction();// 添加功能Person p = new Person();p.setUname("王五");p.setPword("111");p.setAddr("黃埔");// 調用session對象的實現方法,完成添加ss.save(p);// 類比一個異常int x = 10 / 0;// 提交事務tx.commit();} catch (Exception e) {// 輸出異常資訊//e.printStackTrace();// 有異常,則復原事務/** * 一直交易回復失敗的原因是資料庫的原因, * mysql資料庫只有InnoDB引擎支援事務; * 預設引擎是MyISAM,不支援事務, * 所以,需要設定資料庫的表結構為InnoDB; * 即alter table 表名 ENGINE=InnoDB; * 同時,將方言設定為MySQLInnoDBDialect */if (tx != null) {ss.clear();tx.rollback(); System.out.println("交易回復!");}} finally {// 關閉資源if (ss != null && ss.isOpen()) {ss.close();}if (sf != null && !sf.isClosed()) {sf.close();}}}}

  

hibernate Day2 案例代碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.