初学Hibernate心得/

Posted 二十五

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了初学Hibernate心得/相关的知识,希望对你有一定的参考价值。

看了几天的心得记录一下

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心得/的主要内容,如果未能解决你的问题,请参考以下文章

具有运行时 pojos 的带有 Hibernate 的 OSGi 片段包

初学JSON和AJAX心得透过解惑去学习

hibernate之初学一对多和多对一配置及使用

Hibernate反向工程使用心得

FPGA初学心得

Python初学心得体会