1. 程式人生 > >初學Hibernate心得/

初學Hibernate心得/

nfa 分享圖片 記錄 使用 利用 {} 所有 item 語句

看了幾天的心得記錄一下

技術分享圖片

1、配置hibernate

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <!--Hibernate的配置信息 -->
 6 <hibernate-configuration
> 7 <!--配置工廠信息,全局信息 --> 8 <session-factory> 9 <!--1、設置四本一言 --> 10 <!--四本一言 四大基本項: 1、驅動類名 2、指明需要連接的url 3、用戶名 4、密碼 Hibernate支持不同的數據庫,但是每種數據庫語法可能有區別,可以使用方言,註意版本 --> 11 <!--數據庫驅動類全稱 --> 12 <property name="hibernate.connection.driver_class"
>com.mysql.jdbc.Driver</property> 13 <!--數據庫url地址 --> 14 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/text?characterEncoding=UTF-8</property> 15 <!--用戶名 --> 16 <property name="hibernate.connection.username">root</
property> 17 <!--密碼 --> 18 <property name="hibernate.connection.password">1111</property> 19 <!--方言 --> 20 <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> 21 <!--2、全局配置信息 --> 22 <!--執行DDL的類別: 23 create:每次都刪除新建 24 update:存在就修改,不存在就新建 --> 25 <property name="hibernate.hbm2ddl.auto">update</property> 26 <!--是否顯示SQL語句 --> 27 <property name="hibernate.show_sql">true</property> 28 <!--是否格式化SQL語句 --> 29 <property name="hibernate.format_sql">true</property> 30 <!-- 啟用getCurrentSession,默認未啟用 --> 31 <property name="hibernate.current_session_context_class">thread</property> 32 <!--3、加載配置文件 --> 33 <mapping resource="com/Student.hbm.xml"></mapping> 34 <mapping resource="com/Classes.hbm.xml"></mapping> 35 36 </session-factory> 37 </hibernate-configuration>

2、建立實體類

課程類

 1 package com;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 
 6 public class Classes {
 7     /**
 8      * @param cid
 9      * @param name
10      */
11     public Classes() {}
12     public Classes(int cid, String name) {
13         this.cid = cid;
14         this.name = name;
15     }
16     private int cid; //標示符屬性
17     private String name;  //一般屬性
18     private String description;
19     private Set<Student> student = new HashSet<Student>();
20     public Set<Student> getStudent() {
21         return student;
22     }
23     public void setStudent(Set<Student> student) {
24         this.student = student;
25     }
26 
27     public int getCid() {
28         return cid;
29     }
30     public void setCid(int cid) {
31         this.cid = cid;
32     }
33     public String getName() {
34         return name;
35     }
36     public void setName(String name) {
37         this.name = name;
38     }
39     public String getDescription() {
40         return description;
41     }
42     public void setDescription(String description) {
43         this.description = description;
44     }
45 
46 }

學生類

 1 package com;
 2 
 3 public class Student {
 4     public Student(int sid, String name, String description, Classes classes) {
 5         this.sid = sid;
 6         this.name = name;
 7         this.description = description;
 8         this.classes = classes;
 9     }
10     public Student(int sid, String name, Classes classes) {
11         this.sid = sid;
12         this.name = name;
13         this.classes = classes;
14     }
15     public Student()
16     {}
17     private int sid;
18     private String name;
19     private String description;
20     private Classes classes;
21     public Classes getClasses() {
22         return classes;
23     }
24     public void setClasses(Classes classes) {
25         this.classes = classes;
26     }
27 
28     public int getSid() {
29         return sid;
30     }
31     public void setSid(int sid) {
32         this.sid = sid;
33     }
34     public String getName() {
35         return name;
36     }
37     public void setName(String name) {
38         this.name = name;
39     }
40     public String getDescription() {
41         return description;
42     }
43     public void setDescription(String description) {
44         this.description = description;
45     }
46 
47 }

3、配置實例類

<?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>
    <!-- name:實體, table:表名 -->
    <class name="com.Classes" table="m2o_cla">
        <!-- name:主鍵的名字,column:主鍵數據庫表列,identity自增 -->
        <id name="cid">
            <!-- Hibernate使用generator類來生成主鍵 -->
            <generator class="identity" />
        </id>
        <!-- name:實體中的屬性名,length:長度 ,column:表中的字段(實體屬性和字段一致可省略),type:類型(可不寫由hiberbate自動匹配) -->
        <property name="name"  />
        <property name="description"/>
        
        <!-- inverse:這個屬性(stus) 是否為關系的維護方,默認值為false
            如果inverse設置為true,表示將由對方維護兩者之間的關聯關系
         -->
        <!--cascade(級聯)意思是指定兩個對象之間的操作聯動關系,對一個對象執行了操作之後,對其指定的級聯對象也需要執行相同的操作
            all-代表在所有的情況下都執行級聯操作
            none-在所有情況下都不執行級聯操作
            save-update-在保存和更新的時候執行級聯操作
            delete-在刪除的時候執行級聯操作
         -->
         <!--lazy:延遲加載,默認true,如學生實體不調用班級實體信息,可以不用加載  -->
        <set name="student" inverse="false" cascade="all" lazy="true">
            <!-- 關系維護方的外鍵列 -->
            <key column="cid"></key>
            <one-to-many class="com.Student" />
        </set>
    </class>
</hibernate-mapping>

<?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>
    <!-- name:實體, table:表名 -->
    <class name="com.Student" table="m2o_stu">
        <!-- name:主鍵的名字,column:主鍵數據庫表列,identity自增 -->
        <id name="sid">
            <!-- Hibernate使用generator類來生成主鍵 -->
            <generator class="identity" />
        </id>
        <!-- name:實體中的屬性名,length:長度 ,column:表中的字段(實體屬性和字段一致可省略),type:類型(可不寫由hiberbate自動匹配) -->
        <property name="name"  />
        <property name="description"/>
        
        <!-- 對應班級配置中的cid -->
        <many-to-one name="classes" column="cid" cascade="save-update"></many-to-one>
    </class>
</hibernate-mapping>

4、幫助類,因Configuration中運行會生成大量sql語句,用static限定/

 1 package com;
 2 import org.hibernate.Session;
 3 import org.hibernate.SessionFactory;
 4 import org.hibernate.Transaction;
 5 import org.hibernate.cfg.Configuration;
 6 
 7 public class project_text {
 8     public static Configuration cfg;
 9     public static SessionFactory sessionFactory;
10     static { 
11         cfg = new Configuration().configure("hibernate.cfg.xml");
12         sessionFactory = cfg.buildSessionFactory();
13     }
14     public static Session openSesson()
15     {
16         return sessionFactory.openSession();
17     }
18     public static Transaction beginTransaction(Session session)
19     {
20         return session.beginTransaction();
21     }
22 }

5、通過對實體類的操作實現對數據庫的操作/

沒copy出text實體類/原理同上/

 1 package com;
 2 
 3 import java.util.List;
 4 
 5 import org.hibernate.Query;
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.Transaction;
 9 import org.hibernate.cfg.Configuration;
10 public class pro_text {
11 
12     public static void main(String[] args) {
13         project_text text_hibernate = new project_text();
14         Session textSession =  text_hibernate.openSesson();
15         Transaction textTransaction = text_hibernate.beginTransaction(textSession);
16         text text1 =new text(2,"quanmina","123");
17         job job1 =new job(2,"adress","1111");
18         
19         textSession.save(text1);
20         
21         text text2 = new text();
22         text2.setId(1);
23         text2.setName("updatename");
24         text2.setPassword("123123");
25         textSession.update(text2);
26         
27 //        text text3 = new text();
28 //        text3.setId(3); 
29 //        textSession.delete("3",text3);
30         
31         //text text4 = (text)textSession.get("text", 1);
32         //System.out.println("id:"+text4.getId()+"---name:"+text4.getName()+"----password:"+text4.getPassword());
33         Query  query = textSession.createQuery("from text");
34         List<text> textList = query.list();
35         System.out.println("-*----------------------------------------*-");
36         for( text item  :  textList)
37         {
38             System.out.println("id:"+item.getId()+"---name:"+item.getName()+"----password:"+item.getPassword()+"------"+item.get_job().getJobAdress());
39         }
40         
41         Query  query1 = textSession.createQuery("from text,job where text.id=job.id");
42         List<text> textList1 = query1.list();
43         System.out.println("-*----------------------------------------*-");
44         for( text item  :  textList1)
45         {
46             System.out.println("id:"+item.getId()+"---name:"+item.getName()+"----password:"+item.getPassword());
47         }
48         textSession.getTransaction().commit();
49         textSession.close();
50         
51         // TODO 自動生成的方法存根
52 //        Configuration conf=new Configuration();//這個構造方法調用了一個受保護的構造方法:
53 //        conf.configure("hibernate.cfg.xml");
54 //        //創建工廠
55 //        SessionFactory sf=conf.buildSessionFactory();
56 //        //取得session
57 //        Session session=sf.openSession();
58 //        //開始事務
59 //        session.beginTransaction();
60 //        text text=new text(1,"quanmina","123");
61 //        session.save(text);
62 //        System.out.println("保存成功");
63 //        session.getTransaction().commit();
64 //        session.close();
65 //        sf.close();
66     }
67 
68 }

6、mian函數,聯合查詢,一對多的例子/

 1 package com;
 2 
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 
 6 import org.hibernate.Query;
 7 import org.hibernate.Session;
 8 import org.hibernate.Transaction;
 9 
10 public class StudClassesMian {
11 
12     public static void main(String[] args) {
13         // TODO 自動生成的方法存根
14         project_text text_hibernate = new project_text();
15         Session session =  text_hibernate.openSesson();
16         Transaction transaction = text_hibernate.beginTransaction(session);
17         Student student = new Student();
18         student.setName("asfd");
19         Classes classes = new Classes();
20         classes.setName("12期");
21          //創建班級與學生之間的關聯
22         student.setClasses(classes);  //通過學生建立的關聯  
23          //session.save(student);
24          transaction.commit();
25             String hqlS= "select s.sid,s.name,c.cid,c.name from com.Student as s,com. Classes as c where s.classes = c.cid";
26             Query query = session.createQuery(hqlS);
27             List<Object> list_stu = query.list();
28             List<Student> listResult= new LinkedList<Student>();
29             for(int i=0;i<list_stu.size();i++)
30             {
31                 Object[] obj = (Object[])list_stu.get(i);    
32                 Classes cls = new Classes((int)obj[2],obj[3].toString());  //利用構造函數將查詢結構保存到實體類中,方便數據使用/
33                 Student stu = new Student((int)obj[0],obj[1].toString(),cls);
34                 listResult.add(stu);
35             }
36             for(Student item : listResult)
37             {
38                 System.out.println(item.getSid()+"=="+item.getName()+"=="+item.getClasses().getCid()+"=="+item.getClasses().getName());
39             }
40             List<Object> list = query.list();
41             for(int i=0;i<list.size();i++)
42             {
43                 Object[] obj = (Object[])list.get(i);
44                 System.out.println(obj[0]+"==="+obj[1]+"==="+obj[2]+"==="+obj[3]+"===");
45             }
46             System. out.println(list.size());
47             String SQLStr= "select s.sid as sid,s.name as sname,c.cid as cid,c.name as cname from m2o_stu as s, m2o_cla as c where s.cid = c.cid";
48             Query querySQL = session.createSQLQuery(SQLStr);
49             List lsitSQL = querySQL.list();
50             System. out.println(lsitSQL.size());
51          session.close();
52     }
53 
54 }

初學Hibernate心得/