程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 基於Java ORM框架的應用詳解

基於Java ORM框架的應用詳解

編輯:關於JAVA

基於Java ORM框架的應用詳解。本站提示廣大學習愛好者:(基於Java ORM框架的應用詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是基於Java ORM框架的應用詳解正文


ORM框架不是一個新話題,它曾經傳播了許多年。它的長處在於供給了概念性的、易於懂得的數據模子,將數據庫中的表和內存中的對象樹立了很好的映照關系。
我們在這裡重要存眷Java中經常使用的兩個ORM框架:Hibernate和iBatis。上面來引見這兩個框架簡略的應用辦法,假如未來有時光,我會深刻的寫一些更成心思的相干文章。
Hibernate
Hibernate是一個耐久化框架和ORM框架,耐久化和ORM是兩個有差別的概念,耐久化重視對象的存儲辦法能否跟著法式的加入而滅亡,ORM存眷的是若何在數據庫表和內存對象之間樹立聯系關系。
Hibernate應用POJO來表現Model,應用XML設置裝備擺設文件來設置裝備擺設對象和表之間的關系,它供給了一系列API來經由過程對對象的操作而轉變數據庫中的進程。
Hibernate更強調若何對單筆記錄停止操作,關於更龐雜的操作,它供給了一種新的面向對象的查詢說話:HQL。
我們先來界說一個關於Hibernate中Session治理的類,這裡的Session相似於JDBC中的Connection。

Hibernate的Session治理類
 public class HibernateSessionManager {

     private static SessionFactory sessionFactory;

     static
     {
         try
         {
             sessionFactory = new Configuration().configure("sample/orm/hibernate/hibernate.cfg.xml").buildSessionFactory();
         }
         catch(Exception ex)
         {
             ex.printStackTrace();
         }
     }

     public static final ThreadLocal tl = new ThreadLocal();

     public static Session currentSession()
     {
         Session s = (Session)tl.get();
         if (s == null)
         {
             s = sessionFactory.openSession();
             tl.set(s);
         }

         return s;
     }

     public static void closeSession()
     {
         Session s = (Session)tl.get();
         tl.set(null);
         if (s != null)
         {
             s.close();
         }
     }
 }

基於單張表停止操作
上面我們來看一個簡略的示例,它沿用了<基於Java回想之JDBC的應用詳解>中的數據庫,應用MySQL的test數據庫中的user表。
起首,我們來界說VO對象:

界說User對象
 public class User implements Serializable
 {
     private static final long serialVersionUID = 1L;
     private int userID;
     private String userName;
     public void setUserID(int userID) {
         this.userID = userID;
     }
     public int getUserID() {
         return userID;
     }
     public void setUserName(String userName) {
         this.userName = userName;
     }
     public String getUserName() {
         return userName;
     }
 }

然後,我們界說User對象和數據庫中user表之間的聯系關系,user表中只要兩列:id和name。

<?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
     <class name="sample.orm.hibernate.User" table="user" catalog="test">
         <id name="userID" type="java.lang.Integer">
             <column name="id" />
             <generator class="assigned" />
         </id>
         <property name="userName" type="java.lang.String">
             <column name="name" />
         </property>
     </class>
 </hibernate-mapping>

將上述內容存儲為User.hbm.xml。
接上去,我們須要界說一個關於Hibernate的全局設置裝備擺設文件,這裡文件名是hibernate.cfg.xml。

<?xml version='1.0' encoding='UTF-8'?>
 <!DOCTYPE hibernate-configuration PUBLIC
           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>
     <session-factory>
         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
         <property name="connection.url">jdbc:mysql://localhost/test</property>
         <property name="connection.username">root</property>
         <property name="connection.password">123</property>   
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
         <property name="show_sql">true</property>
         <property name="jdbc.fetch_size">50</property>
         <property name="jdbc.batch_size">25</property>

         <mapping resource="sample/orm/hibernate/User.hbm.xml" />       
     </session-factory>
 </hibernate-configuration>

可以看到,上述設置裝備擺設文件中包括了數據庫銜接的信息,諸如driver信息、數據庫url、用戶名、暗碼等等,還包含了我們下面界說的User.hbm.xml。
最初,我們編寫測試代碼,來對user表停止增、刪、查、改的操作:

應用Hibernate對user表停止操作
 private static void getUser(int id)
 {
     Session session = HibernateSessionManager.currentSession();
     System.out.println("=====Query test=====");
     User user = (User)session.get(User.class, new Integer(id));
     if (user != null)
     {
         System.out.println("ID:" + user.getUserID() + "; Name:" + user.getUserName());
     }
     HibernateSessionManager.closeSession();
 }

 private static void insertUser()
 {
     Session session = HibernateSessionManager.currentSession();
     System.out.println("=====Insert test=====");
     Transaction transaction = session.beginTransaction();
     User user = new User();
     user.setUserID(6);
     user.setUserName("Zhang Fei");
     session.save(user);
     session.flush();
     transaction.commit();
     HibernateSessionManager.closeSession();
     getUser(6);
 }

 private static void updateUser(int id)
 {
     Session session = HibernateSessionManager.currentSession();
     System.out.println("=====Update test=====");
     Transaction transaction = session.beginTransaction();
     User user = (User)session.get(User.class, new Integer(id));
     System.out.println("=====Before Update=====");
     if (user != null)
     {
         System.out.println("ID:" + user.getUserID() + "; Name:" + user.getUserName());
     }
     user.setUserName("Devil");
     session.save(user);
     session.flush();
     transaction.commit();
     user = (User)session.get(User.class, new Integer(id));
     System.out.println("=====After Update=====");
     if (user != null)
     {
         System.out.println("ID:" + user.getUserID() + "; Name:" + user.getUserName());
     }
     HibernateSessionManager.closeSession();
 }

 private static void deleteUser(int id)
 {
     Session session = HibernateSessionManager.currentSession();
     System.out.println("=====Delete test=====");
     Transaction transaction = session.beginTransaction();
     User user = (User)session.get(User.class, new Integer(id));
     System.out.println("=====Before Delte=====");
     if (user != null)
     {
         System.out.println("ID:" + user.getUserID() + "; Name:" + user.getUserName());
     }
     session.delete(user);
     transaction.commit();
     user = (User)session.get(User.class, new Integer(id));
     System.out.println("=====After Update=====");
     if (user != null)
     {
         System.out.println("ID:" + user.getUserID() + "; Name:" + user.getUserName());
     }
     else
     {
         System.out.println("Delete successfully.");
     }
     HibernateSessionManager.closeSession();
 }

我們依照以下次序挪用測試代碼:

insertUser();
updateUser(6);
deleteUser(6);

可以看到以下成果:

=====Insert test=====
Hibernate: insert into test.user (name, id) values (?, ?)
=====Query test=====
Hibernate: select user0_.id as id0_, user0_.name as name0_0_ from test.user user0_ where user0_.id=?
ID:6; Name:Zhang Fei
=====Update test=====
Hibernate: select user0_.id as id0_, user0_.name as name0_0_ from test.user user0_ where user0_.id=?
=====Before Update=====
ID:6; Name:Zhang Fei
Hibernate: update test.user set name=? where id=?
=====After Update=====
ID:6; Name:Devil
=====Delete test=====
Hibernate: select user0_.id as id0_, user0_.name as name0_0_ from test.user user0_ where user0_.id=?
=====Before Delte=====
ID:6; Name:Devil
Hibernate: delete from test.user where id=?
Hibernate: select user0_.id as id0_, user0_.name as name0_0_ from test.user user0_ where user0_.id=?
=====After Delete=====
Delete successfully.

請留意,下面的成果中,輸入了每次數據庫操作時的SQL語句,這是由於在設置裝備擺設文件中有以下設置裝備擺設:

<property name="show_sql">true</property>

我們可以在開辟調試階段將其翻開,在安排到客戶方時,將其封閉。
基於多表聯系關系的操作
Hibernate在樹立多表聯系關系時,依據主外鍵的設置,表之間的聯系關系可以分為三種:一對1、一對多和多對多。這些聯系關系會表現在表的設置裝備擺設文件和VO中。
上面我們來看一個經典的多表聯系關系示例:排課表。數據庫中樹立以下四張表:Grade/Class/ClassRoom/Schedule。剛發明,應用MySQL自帶的治理器導出表界說根本是一件弗成能的義務。。。。
上述各表除ID和需要外鍵外,只要Name一列。
然後看各個VO的界說:

界說Grade對象
 package sample.orm.hibernate;

 import java.io.Serializable;
 import java.util.Set;

 public class Grade implements Serializable
 {
     private static final long serialVersionUID = 1L;
     private int gradeID;
     private String gradeName;
     private Set classes;
     public void setGradeID(int gradeID) {
         this.gradeID = gradeID;
     }
     public int getGradeID() {
         return gradeID;
     }
     public void setGradeName(String gradeName) {
         this.gradeName = gradeName;
     }
     public String getGradeName() {
         return gradeName;
     }
     public void setClasses(Set classes) {
         this.classes = classes;
     }
     public Set getClasses() {
         return classes;
     }
 }


界說Class對象
 package sample.orm.hibernate;

 import java.io.Serializable;
 import java.util.Set;

 public class Class implements Serializable
 {
     private static final long serialVersionUID = 1L;
     private int classID;
     private Grade grade;
     private Set classrooms;
     private String className;
     public void setClassID(int classID) {
         this.classID = classID;
     }
     public int getClassID() {
         return classID;
     }
     public void setClassName(String className) {
         this.className = className;
     }
     public String getClassName() {
         return className;
     }
     public void setGrade(Grade grade) {
         this.grade = grade;
     }
     public Grade getGrade() {
         return grade;
     }
     public void setClassrooms(Set classrooms) {
         this.classrooms = classrooms;
     }
     public Set getClassrooms() {
         return classrooms;
     }
 }


界說ClassRoom對象
 package sample.orm.hibernate;

 import java.io.Serializable;
 import java.util.Set;

 public class ClassRoom implements Serializable
 {
     private static final long serialVersionUID = 1L;
     private int classRoomID;
     private String classRoomName;
     private Set classes;
     public void setClassRoomID(int classRoomID) {
         this.classRoomID = classRoomID;
     }
     public int getClassRoomID() {
         return classRoomID;
     }
     public void setClassRoomName(String classRoomName) {
         this.classRoomName = classRoomName;
     }
     public String getClassRoomName() {
         return classRoomName;
     }
     public void setClasses(Set classes) {
         this.classes = classes;
     }
     public Set getClasses() {
         return classes;
     }
 }


界說Schedule對象
 package sample.orm.hibernate;

 import java.io.Serializable;
 import java.util.Set;

 public class Schedule implements Serializable
 {
     private static final long serialVersionUID = 1L;
     private int scheduleID;
     private int classRoomID;
     private int classID;
     private Set classes;
     public void setClassRoomID(int classRoomID) {
         this.classRoomID = classRoomID;
     }
     public int getClassRoomID() {
         return classRoomID;
     }
     public void setClassID(int classID) {
         this.classID = classID;
     }
     public int getClassID() {
         return classID;
     }
     public void setClasses(Set classes) {
         this.classes = classes;
     }
     public Set getClasses() {
         return classes;
     }
     public void setScheduleID(int scheduleID) {
         this.scheduleID = scheduleID;
     }
     public int getScheduleID() {
         return scheduleID;
     }
 }

接著是各個表的聯系關系設置裝備擺設文件:
1)Grade.hbm.xml

<?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
     <class name="sample.orm.hibernate.Grade" table="grade" catalog="test">
         <id name="gradeID" type="java.lang.Integer">
             <column name="gradeid" />
             <generator class="assigned" />
         </id>
         <property name="gradeName" type="java.lang.String">
             <column name="gradename" />
         </property>

         <set name="classes" lazy="true" inverse="true" cascade="all-delete-orphan">
             <key>
                 <column name="gradeid"/>
             </key>
             <one-to-many class="sample.orm.hibernate.Class"/>
         </set>
     </class>
 </hibernate-mapping>

留意下面的<set>設置裝備擺設,外面的<one-to-many>節點解釋了Grade和Class之間一對多的關系。
2)Class.hbm.xml

<?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
     <class name="sample.orm.hibernate.Class" table="class" catalog="test">
         <id name="classID" type="java.lang.Integer">
             <column name="classid" />
             <generator class="assigned" />
         </id>
         <property name="className" type="java.lang.String">
             <column name="classname" />
         </property>

         <many-to-one name="grade" class="sample.orm.hibernate.Grade" lazy="proxy" not-null="true">
             <column name="gradeid"/>
         </many-to-one>

         <set name="classrooms" lazy="true" inverse="true" cascade="all-delete-orphan" table="schedule">
             <key column ="classid"/>
             <many-to-many class="sample.orm.hibernate.ClassRoom" column="classroomid"/>
         </set>
     </class>
 </hibernate-mapping>

留意它界說兩個聯系關系:一個是和Grade之間多對一的關系,一個合適ClassRoom之間多對多的關系。
3)ClassRoom.hbm.xml

<?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
     <class name="sample.orm.hibernate.ClassRoom" table="classroom" catalog="test">
         <id name="classRoomID" type="java.lang.Integer">
             <column name="classroomid" />
             <generator class="assigned" />
         </id>
         <property name="classRoomName" type="java.lang.String">
             <column name="classroomname" />
         </property>

         <set name="classes" lazy="true" inverse="true" cascade="all-delete-orphan" table="schedule">
             <key column="classroomid"/>
             <many-to-many class="sample.orm.hibernate.Class" column="classid"/>
         </set>
     </class>
 </hibernate-mapping>

它只界說了一個聯系關系:和Class之間的多對多聯系關系。
4)Schedule.hbm.xml

<?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 <hibernate-mapping>
     <class name="sample.orm.hibernate.Schedule" table="schedule" catalog="test">
         <id name="scheduleID" type="java.lang.Integer">
             <column name="scheduleid" />
             <generator class="assigned" />
         </id>
         <property name="classID" type="java.lang.Integer">
             <column name="classid" />
         </property>
         <property name="classRoomID" type="java.lang.Integer">
             <column name="classroomid" />
         </property>
     </class>
 </hibernate-mapping>

這裡就不須要再界說聯系關系了。
我們須要在Hibernate全局設置裝備擺設文件中添加以下內容:

<mapping resource="sample/orm/hibernate/Grade.hbm.xml" />
<mapping resource="sample/orm/hibernate/Class.hbm.xml" />
<mapping resource="sample/orm/hibernate/ClassRoom.hbm.xml" />
<mapping resource="sample/orm/hibernate/Schedule.hbm.xml" />

上面是各類測試辦法,在有聯系關系的情形下,Hibernate供給了上面幾個特征:
•延遲加載
•級聯添加
•級聯修正
•級聯刪除

多表聯系關系情形下的一些測試辦法
 private static void getClass(int gradeid)
 {
     Session session = HibernateSessionManager.currentSession();
     System.out.println("=====Get Class info=====");
     Transaction transaction = session.beginTransaction();
     Grade grade = (Grade)session.get(Grade.class, new Integer(gradeid));

     Hibernate.initialize(grade);
     Iterator iterator = grade.getClasses().iterator();
     System.out.println("年級:" + grade.getGradeName() + "包含以上班級:");
     while(iterator.hasNext())
     {
         System.out.println(grade.getGradeName() + ((Class)iterator.next()).getClassName());
     }
     HibernateSessionManager.closeSession();
 }

 private static void getSchedule(int gradeid)
 {
     Session session = HibernateSessionManager.currentSession();
     Transaction transaction = session.beginTransaction();
     Grade grade = (Grade)session.get(Grade.class, new Integer(gradeid));
     if (grade != null)
     {
         System.out.println("ID:" + grade.getGradeID() + "; Name:" + grade.getGradeName());
     }

     Hibernate.initialize(grade.getClasses());

     Iterator iterator = grade.getClasses().iterator();
     while(iterator.hasNext())
     {
         Class c = (Class)iterator.next();
         System.out.println(grade.getGradeName() + c.getClassName() + "應用以下教室:");
         Hibernate.initialize(c.getClassrooms());
         Iterator iterator1 = c.getClassrooms().iterator();
         while(iterator1.hasNext())
         {
             System.out.println(((ClassRoom)iterator1.next()).getClassRoomName());
         }
     }
     HibernateSessionManager.closeSession();
 }

 private static void insertGrade()
 {
     Session session = HibernateSessionManager.currentSession();
     Transaction transaction = session.beginTransaction();
     Grade grade = new Grade();
     grade.setGradeID(4);
     grade.setGradeName("四年級");

     Class c1 = new Class();
     c1.setClassID(7);
     c1.setGrade(grade);
     c1.setClassName("一班");
     Class c2 = new Class();
     c2.setClassID(8);
     c2.setGrade(grade);
     c2.setClassName("二班");

     Set set = new HashSet();
     set.add(c1);
     set.add(c2);

     grade.setClasses(set);

     session.save(grade);
     session.flush();
     transaction.commit();
     HibernateSessionManager.closeSession();
     getClass(4);
 }

 private static void deleteGrade(int gradeid)
 {
     Session session = HibernateSessionManager.currentSession();
     Transaction transaction = session.beginTransaction();
     Grade grade = (Grade)session.get(Grade.class, new Integer(gradeid));
     if (grade != null)
     {
         session.delete(grade);
         session.flush();
     }

     transaction.commit();

     grade = (Grade)session.get(Grade.class, new Integer(gradeid));
     if (grade == null)
     {
         System.out.println("刪除勝利");
     }
     HibernateSessionManager.closeSession();
 }

 private static void updateGrade1(int gradeid)
 {
     Session session = HibernateSessionManager.currentSession();
     Transaction transaction = session.beginTransaction();
     Grade grade = (Grade)session.get(Grade.class, new Integer(gradeid));
     if (grade != null)
     {
         System.out.println("ID:" + grade.getGradeID() + "; Name:" + grade.getGradeName());
     }
     grade.setGradeName("Grade " + gradeid);
     session.save(grade);
     session.flush();
     transaction.commit();
     HibernateSessionManager.closeSession();
     getClass(gradeid);
 }

 private static void updateGrade2(int gradeid)
 {
     Session session = HibernateSessionManager.currentSession();
     Transaction transaction = session.beginTransaction();
     Grade grade = (Grade)session.get(Grade.class, new Integer(gradeid));
     if (grade != null)
     {
         System.out.println("ID:" + grade.getGradeID() + "; Name:" + grade.getGradeName());
     }

     Grade newGrade = new Grade();
     newGrade.setGradeID(10);
     newGrade.setGradeName(grade.getGradeName());
     Set set = grade.getClasses();
     Set newSet = new HashSet();
     Iterator iterator = set.iterator();
     while(iterator.hasNext())
     {
         Class c = (Class)iterator.next();
         Class temp = new Class();
         temp.setClassID(c.getClassID());
         temp.setClassName(c.getClassName());
         temp.setGrade(newGrade);
         newSet.add(temp);
     }
     newGrade.setClasses(newSet);
     session.delete(grade);
     session.flush();
     session.save(newGrade);
     session.flush();
     transaction.commit();
     grade = (Grade)session.get(Grade.class, new Integer(gradeid));
     if (grade == null)
     {
         System.out.println("刪除勝利");
     }
     HibernateSessionManager.closeSession();
     getClass(10);
 }

按次序挪用下面的辦法:

getClass(1);
 getSchedule(1);
 insertGrade();
 updateGrade1(4);
 updateGrade2(4);
 deleteGrade(10);

履行成果以下:

=====Get Class info=====
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
年級:一年級包含以上班級:
一年級二班
一年級一班
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
ID:1; Name:一年級
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
一年級一班應用以下教室:
Hibernate: select classrooms0_.classid as classid1_, classrooms0_.classroomid as classroo2_1_, classroom1_.classroomid as classroo1_0_, classroom1_.classroomname as classroo2_4_0_ from schedule classrooms0_ inner join test.classroom classroom1_ on classrooms0_.classroomid=classroom1_.classroomid where classrooms0_.classid=?
教室二
教室五
教室一
一年級二班應用以下教室:
Hibernate: select classrooms0_.classid as classid1_, classrooms0_.classroomid as classroo2_1_, classroom1_.classroomid as classroo1_0_, classroom1_.classroomname as classroo2_4_0_ from schedule classrooms0_ inner join test.classroom classroom1_ on classrooms0_.classroomid=classroom1_.classroomid where classrooms0_.classid=?
教室四
教室二
教室六
Hibernate: select class_.classid, class_.classname as classname2_, class_.gradeid as gradeid2_ from test.class class_ where class_.classid=?
Hibernate: select class_.classid, class_.classname as classname2_, class_.gradeid as gradeid2_ from test.class class_ where class_.classid=?
Hibernate: insert into test.grade (gradename, gradeid) values (?, ?)
Hibernate: insert into test.class (classname, gradeid, classid) values (?, ?, ?)
Hibernate: insert into test.class (classname, gradeid, classid) values (?, ?, ?)
=====Get Class info=====
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
年級:四年級包含以上班級:
四年級二班
四年級一班
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
ID:4; Name:四年級
Hibernate: update test.grade set gradename=? where gradeid=?
=====Get Class info=====
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
年級:Grade 4包含以上班級:
Grade 4二班
Grade 4一班
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
ID:4; Name:Grade 4
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
Hibernate: select classrooms0_.classid as classid1_, classrooms0_.classroomid as classroo2_1_, classroom1_.classroomid as classroo1_0_, classroom1_.classroomname as classroo2_4_0_ from schedule classrooms0_ inner join test.classroom classroom1_ on classrooms0_.classroomid=classroom1_.classroomid where classrooms0_.classid=?
Hibernate: select classrooms0_.classid as classid1_, classrooms0_.classroomid as classroo2_1_, classroom1_.classroomid as classroo1_0_, classroom1_.classroomname as classroo2_4_0_ from schedule classrooms0_ inner join test.classroom classroom1_ on classrooms0_.classroomid=classroom1_.classroomid where classrooms0_.classid=?
Hibernate: delete from test.class where classid=?
Hibernate: delete from test.class where classid=?
Hibernate: delete from test.grade where gradeid=?
Hibernate: select class_.classid, class_.classname as classname2_, class_.gradeid as gradeid2_ from test.class class_ where class_.classid=?
Hibernate: select class_.classid, class_.classname as classname2_, class_.gradeid as gradeid2_ from test.class class_ where class_.classid=?
Hibernate: insert into test.grade (gradename, gradeid) values (?, ?)
Hibernate: insert into test.class (classname, gradeid, classid) values (?, ?, ?)
Hibernate: insert into test.class (classname, gradeid, classid) values (?, ?, ?)
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
刪除勝利
=====Get Class info=====
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
年級:Grade 4包含以上班級:
Grade 4一班
Grade 4二班
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
Hibernate: select classes0_.gradeid as gradeid1_, classes0_.classid as classid1_, classes0_.classid as classid0_, classes0_.classname as classname2_0_, classes0_.gradeid as gradeid2_0_ from test.class classes0_ where classes0_.gradeid=?
Hibernate: select classrooms0_.classid as classid1_, classrooms0_.classroomid as classroo2_1_, classroom1_.classroomid as classroo1_0_, classroom1_.classroomname as classroo2_4_0_ from schedule classrooms0_ inner join test.classroom classroom1_ on classrooms0_.classroomid=classroom1_.classroomid where classrooms0_.classid=?
Hibernate: select classrooms0_.classid as classid1_, classrooms0_.classroomid as classroo2_1_, classroom1_.classroomid as classroo1_0_, classroom1_.classroomname as classroo2_4_0_ from schedule classrooms0_ inner join test.classroom classroom1_ on classrooms0_.classroomid=classroom1_.classroomid where classrooms0_.classid=?
Hibernate: delete from test.class where classid=?
Hibernate: delete from test.class where classid=?
Hibernate: delete from test.grade where gradeid=?
Hibernate: select grade0_.gradeid as gradeid0_, grade0_.gradename as gradename1_0_ from test.grade grade0_ where grade0_.gradeid=?
刪除勝利

異樣,履行成果中包括了各個SQL語句。
iBatis
iBatis是別的一種ORM框架,和Hibernate善於操作單筆記錄分歧,iBatis是基於SQL模板的,可以說,iBatis每次和數據庫停止操作時,都有明白的SQL語句,而這些SQL語句,就是我們界說在設置裝備擺設文件中的。
我們照樣以test數據庫中的user表為例,簡略解釋iBatis的操作流程:
起首,我們照樣須要界說VO對象,這裡照樣應用和Hibernate講授時雷同的User:

界說User對象
 package sample.orm.ibatis;

 import java.io.Serializable;

 public class User implements Serializable
 {
     private static final long serialVersionUID = 1L;
     private int userID;
     private String userName;
     public void setUserID(int userID) {
         this.userID = userID;
     }
     public int getUserID() {
         return userID;
     }
     public void setUserName(String userName) {
         this.userName = userName;
     }
     public String getUserName() {
         return userName;
     }

 }

然後須要針對這個VO,界說一個自力的設置裝備擺設文件:User.xml

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE sqlMap
     PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
     "http://www.ibatis.com/dtd/sql-map-2.dtd">

 <sqlMap namespace="User">

     <typeAlias alias="user" type="sample.orm.ibatis.User" />

    
     <cacheModel id="user-cache" type="OSCache" readOnly="true" serialize="true">
         <flushInterval milliseconds="1" />
         <flushOnExecute statement="insertUser" />
         <flushOnExecute statement="updateUser" />
         <flushOnExecute statement="getUser" />
         <flushOnExecute statement="getAllUser" />
         <property value="1" name="size" />
      </cacheModel>

     <!--
     <resultMap >
         <result property="userID" column="id" />
         <result property="userName" column="name" />
     </resultMap>
     -->

    
     <select id="getUser" parameterClass="java.lang.Integer" resultClass="user" cacheModel="user-cache" >
         select id as userID,name as userName from user where id = #userID#
     </select>
     <select id="getAllUser" resultClass="user" cacheModel="user-cache">
         select id as userID,name as userName from user
     </select>
     <update id="updateUser" parameterClass="user">
         update user SET name=#userName# WHERE id = #userID#
     </update>
     <insert id="insertUser" parameterClass="user">
         insert into user ( id, name ) VALUES ( #userID#,#userName#)
     </insert>
     <delete id="deleteUser" parameterClass="java.lang.Integer">
         delete from user where id=#userID#
     </delete>

 </sqlMap>

這個設置裝備擺設文件重要包含三部門:
1)緩存的設置裝備擺設
2)對象屬性和表字段之間的聯系關系
3)針對表的各類CRUD操作
然後是關於iBatis的全局設置裝備擺設文件SqlMapConfig.xml:

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE sqlMapConfig
     PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
     "http://www.ibatis.com/dtd/sql-map-config-2.dtd">

 <sqlMapConfig>

     <settings cacheModelsEnabled="true" enhancementEnabled="true"
         lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="32"
         maxSessions="10" maxTransactions="5" useStatementNamespaces="false" />

     <transactionManager type="JDBC">
         <dataSource type="SIMPLE">
            <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
            <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/test" />
            <property name="JDBC.Username" value="root" />
            <property name="JDBC.Password" value="123" />
            <property name="Pool.MaximumActiveConnections" value="10" />
            <property name="Pool.MaximumIdleConnections" value="5" />
            <property name="Pool.MaximumCheckoutTime" value="120000" />
            <property name="Pool.TimeToWait" value="500" />
            <property name="Pool.PingQuery" value="select 1 from user" />
            <property name="Pool.PingEnabled" value="false" />
         </dataSource>
     </transactionManager>

     <sqlMap resource="sample/orm/ibatis/User.xml" />

 </sqlMapConfig>

和Hibernate全局設置裝備擺設文件相似,它也包括了數據庫銜接的信息、數據庫銜接池的信息和我們界說的User.xml。
上面是測試辦法:

iBatis測試辦法
 public class Sample {

     private SqlMapClient sqlMap = null;

     private void buildMap() throws IOException
     {
         String resource = "sample/orm/ibatis/SqlMapConfig.xml";         
         Reader reader = Resources.getResourceAsReader(resource);
         this.sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
     }

     private void insertUser() throws IOException, SQLException
     {
         System.out.println("=====Insert test=====");
         if (this.sqlMap == null)
         {
             this.buildMap();
         }
         this.sqlMap.startTransaction();
         User user = new User();
         user.setUserID(10);
         user.setUserName("Angel");

         this.sqlMap.insert("insertUser", user);
         this.sqlMap.commitTransaction();

         user = getUser(10);
         printUserInfo(user);
     }

     private void updateUser() throws IOException, SQLException, InterruptedException
     {
         System.out.println("=====Update test=====");
         if (this.sqlMap == null)
         {
             this.buildMap();
         }
         this.sqlMap.startTransaction();
         User user = new User();
         user.setUserID(10);
         user.setUserName("Devil");
         this.sqlMap.update("updateUser", user);
         this.sqlMap.commitTransaction();
         this.sqlMap.flushDataCache();
 //        Thread.sleep(3000);
         user = getUser(10);
         printUserInfo(user);
     }

     private void deleteUser() throws IOException, SQLException
     {
         System.out.println("=====Delete test=====");
         if (this.sqlMap == null)
         {
             this.buildMap();
         }
         sqlMap.flushDataCache();
         this.sqlMap.startTransaction();
         this.sqlMap.delete("deleteUser", 10);
         this.sqlMap.commitTransaction();
         getAllUser();
     }

     private User getUser(int id) throws IOException, SQLException
     {
         if (this.sqlMap == null)
         {
             this.buildMap();
         }
         User user = (User)this.sqlMap.openSession().queryForObject("getUser", id);

         return user;
     }

      private List<User> getAllUser() throws IOException, SQLException
      {
             if(this.sqlMap==null)
                this.buildMap();

          List userList=null; 
          userList=this.sqlMap.openSession().queryForList("getAllUser");
          printUserInfo(userList);
          return userList;
      }

      private void printUserInfo(User user)
      {
          System.out.println("=====user info=====");
          System.out.println("ID:" + user.getUserID() + ";Name:" + user.getUserName());
      }

      private void printUserInfo(List<User> users)
      {
          System.out.println("=====user info=====");
          for(User user:users)
          {
              System.out.println("ID:" + user.getUserID() + ";Name:" + user.getUserName());
          }
      }

      public static void main(String[] args) throws IOException, SQLException, InterruptedException
      {
          Sample sample = new Sample();
          sample.getAllUser();
          sample.insertUser();
          sample.updateUser();
          sample.deleteUser();
      }
 }

它的履行成果以下:

=====user info=====
ID:1;Name:Zhang San
ID:2;Name:TEST
=====Insert test=====
=====user info=====
ID:10;Name:Angel
=====Update test=====
=====user info=====
ID:10;Name:Devil
=====Delete test=====
=====user info=====
ID:1;Name:Zhang San
ID:2;Name:TEST

這篇文章只是簡略引見了Hibernate和iBatis的用法,並沒有觸及全體,例如Hibernate的事務、攔阻、HQL、iBatis的緩存等等。這裡重要是為了描寫ORM框架的根本輪廓,和在應用方法上它和JDBC的差別。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved