lazy 懒加载 默认为proxy

 

继承映射

discriminant column="type" type="string"

 

集合映射

生成表的语句:

public
class DbCreate {

    public
static
void main(String[] args) {

        Configuration cfg=new Configuration().configure("/hibernate.cfg.xml");

        SchemaExport exprot=new
SchemaExport(cfg);

        exprot.create(true, true);

    }

}

 

集合的实体

    private String id;

    private String name;

    private
Set
setValue;

    private
List
listValue;

    private String[] arrayValue;

    private
Map
mapValue;

 

该配置文件

<hibernate-mapping>

<class
name="com.model.Coll"
table="t_coll">

<id
name="id"
type="java.lang.String">

<generator
class="uuid"
/>

</id>

 

<property
name="name"
type="java.lang.String">

<column
name="NAME"
length="20"
/>

</property>

    

<set
name="setValue"
table="set_table">

    <key
column="set_id"></key>

    <element
type="string"
column="set_value"></element>

</set>

 

<list
name="listValue"
table="list_table">

            <key
column="list_id"/>

            <list-index
column="list_index"/>

            <element
type="string"
column="list_value"/>

        </list>

<array
name="arrayValue"
table="array_table">

            <key
column="array_id"/>

            <list-index
column="array_index"/>

            <element
type="string"
column="array_value"/>

        </array>

 

<map
name="mapValue"
table="map_table">

            <key
column="map_id"/>

            <map-key
type="string"
column="map_key"/>

            <element
type="string"
column="map_value"/>

        </map>

 

</class>

</hibernate-mapping>

生成的表结构

 

自己写的crud

package com.pcx.dao;

 

import java.util.ArrayList;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

 

import org.hibernate.Hibernate;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.pcx.model.Collection;

import com.pcx.util.HibernateSessionFactory;

 

public class CollTest {

    public void testQueryColl(String id){

        Session session=HibernateSessionFactory.getSession();

        Collection c=(Collection) session.get(Collection.class, id);

        List list=c.getListValue();

        for (Object o : list) {

            System.out.println(o);

        }

        HibernateSessionFactory.closeSession();

    }

    

    public void testColl(){

        Collection c=new Collection();

        c.setName("测试");

        

        String[]ss={"a","b","c","d"};

        ArrayList<String>list=new ArrayList<String>();

        list.add("a");

        list.add("c");

        list.add("e");

        

        HashSet<String>set=new HashSet<String>();

        set.add("1");

        set.add("3");

        set.add("aaaa");

        

        HashMap<String, String>map=new HashMap<String, String>();

        map.put("1", "11");

        map.put("2", "22");

        map.put("3", "33");

        

        c.setArrayValue(ss);

        c.setListValue(list);

        c.setSetValue(set);

        c.setMapValue(map);

        

        Session session=HibernateSessionFactory.getSession();

        Transaction tx=session.beginTransaction();

        session.save(c);

        tx.commit();

        HibernateSessionFactory.closeSession();

    }

    
 

    

    public static void main(String[] args) {

        CollTest test=new CollTest();

//        test.testColl();

        test.testQueryColl("4028d0814ecd7aa4014ecd7aa66c0001");

    }

}

 

组合映射

两个实体类对应生成一张表格

Emp类:

private String id;

    private String name;

    private Address address;

对应的地址类:address类

    private String homeAddress;

    private String comAddress;

 

对应的配置文件

<hibernate-mapping>

<class
name="com.pcx.model.Emp"
table="t_emp">

<id
name="id"
type="java.lang.String">

<generator
class="uuid"
/>

</id>

 

<property
name="name" type="java.lang.String">

<column
name="NAME"
length="20"
/>

</property>

    
 

    <component
name="address">

        <property
name="comAddress"
/>

        <property
name="homeAddress"
/>

    </component>

</class>

</hibernate-mapping>

对应生成的表结构为

自己写的crud

package com.pcx.dao;

 

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.pcx.model.Address;

import com.pcx.model.Emp;

import
com.pcx.util.HibernateSessionFactory;

 

public
class ComponentTest {

    public
void testCom(){

        Session session=HibernateSessionFactory.getSession();

        Transaction tx=session.beginTransaction();

        Address ad=new Address();

        ad.setComAddress("济南长清");

        ad.setHomeAddress("山东泰安");

        Emp e=new Emp();

        e.setName("程志");

        e.setAddress(ad);

        session.save(e);

        tx.commit();

        HibernateSessionFactory.closeSession();

    }

    

    public
void testQueryCom(String id){

        Session session=HibernateSessionFactory.getSession();

        Emp e=(Emp) session.get(Emp.class,id );

        System.out.println(e.getId());

        System.out.println(e.getName());

        System.out.println(e.getAddress().getHomeAddress());

    }

    

    public
static
void main(String[] args) {

        ComponentTest com=new ComponentTest();

//        com.testCom();

        com.testQueryCom("4028d0814ece0647014ece0648f20001");

    }

}

 

 

 

 

联合主键

如果一个表没主键,那么由表生成类的时候会单独生成一个 id类

Student 类中就单独一个StudentId

StudentId中则包含 id name

生成的配置文件为:

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

<class name="com.pcx.model.Student" table="student" catalog="hibernate">

<composite-id name="id" class="com.pcx.model.StudentId">

<key-property name="id" type="java.lang.Integer">

<column name="id" />

</key-property>

<key-property name="name" type="java.lang.String">

<column name="name" />

</key-property>

</composite-id>

</class>

</hibernate-mapping>

 

在一个例子

Emp

private PKId pkid;

    private String name;

PKId

private Integer fristId;

    private Integer lastId;

 

配置文件:

<?xml
version="1.0"
encoding="utf-8"?>

<!DOCTYPE hibernate-mapping
PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class
name="com.pcx.entity.Emp" table="t_emp">

<composite-id
name="pkid">

    <key-property
name="fristId"
/>

    <key-property
name="lastId"
/>

</composite-id>

 

<property
name="name"
type="java.lang.String">

<column
name="NAME"
length="20"
/>

</property>

    
 

</class>

</hibernate-mapping>

配置文件字段配置错了可能会出现

类的变量没配对

提示错误找不到配置文件。

 

 

 

多对多关系

多个学生对应多个老师

学生

private String id;

    private String name;

    private Set<Teacher> teachers;

老师

    private String id;

    private String name;

    private Set<Student> students;

配置文件

学生

<hibernate-mapping>

<class
name="com.pcx.entity.Student"
table="t_student"
>

<id
name="id"
type="java.lang.String"
>

<generator
class="uuid"
/>

</id>

<property
name="name"
type="java.lang.String">

<column
name="NAME"
length="20"
/>

</property>

 

<set
name="teachers"
table="t_teacher_student"
cascade="all">

    <key
column="sid"></key>

    <many-to-many
class="com.pcx.entity.Teacher"
column="tid"
></many-to-many>

</set>

</class>

</hibernate-mapping>

老师

<hibernate-mapping>

<class
name="com.pcx.entity.Teacher"
table="t_teacher">

<id
name="id"
type="java.lang.String">

<generator
class="uuid"
/>

</id>

<property
name="name"
type="java.lang.String">

<column
name="NAME"
length="20"
/>

</property>

 

<set
name="students"
table="t_teacher_student"
cascade="all">

    <key
column="tid"></key>

    <many-to-many
class="com.pcx.entity.Student"
column="sid"></many-to-many>

</set>

</class>

</hibernate-mapping>

 

对应的crud

package com.pcx.dao;

 

import java.util.HashSet;

import java.util.Set;

 

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.pcx.entity.Student;

import com.pcx.entity.Teacher;

import
com.pcx.util.HibernateSessionFactory;

 

public
class TestManyToMany {

    private
void
testManyToMany(){

        Session session=HibernateSessionFactory.getSession();

        Transaction tx=session.beginTransaction();

        

        Teacher t1=new Teacher();

        t1.setName("彭");

        Teacher t2=new Teacher();

        t2.setName("李");

        Student s1=new Student();

        Student s2=new Student();

        Student s3=new Student();

        Student s4=new Student();

        

        s1.setName("aaa");

        s2.setName("aaa");

        s3.setName("bbb");

        s4.setName("aaa");

        

        Set<Teacher>set=new HashSet<Teacher>();

        set.add(t1);set.add(t2);

        s1.setTeachers(set);

        

        session.save(s1);

        

        tx.commit();

        HibernateSessionFactory.closeSession();

    }

    public
void testQuery(String id){

        Session session=HibernateSessionFactory.getSession();

        Teacher t=(Teacher) session.get(Teacher.class, id);

        System.out.println(t.getName());

        Set<Student>ss=t.getStudents();

        for (Student student : ss) {

            System.out.println(student.getName());

        }

        HibernateSessionFactory.closeSession();

    }

    public
static
void main(String[] args) {

        TestManyToMany test=new TestManyToMany();

//        test.testManyToMany();

        test.testQuery("4028d0814ece5103014ece51053b0002");

    }

}

 

一对一

 

查询

 

Hql

 

懒加载的问题

一对多的表关系中 默认是proxy

true 不加载关联的 老师查出来学生不被加载了

false 加载关联的

enchor代理

 

load验证id在表中是否存在, 不加载其他的属性,若不关闭Session 可以取出name 因为被代理掉了

同Query类的iterator

 

查询一个单体的时候

根据ID来查询 get load

get直接发送sql语句,直接将数据从数据库中加载到当前程序中,并且置入对象属性。

load不发送sql语句,只是查询当前给定的id在数据库中是否有这样一条记录对应存在

协助维护数据关系的

 

可以通过forward --过滤器 用于开启或关闭Session

 

 

unionQueresult()

 

分页

 

Criteria类

gt 大于1000的

lt 小于1000的

复合条件

 

.add().add()

排序 addorder

ReStrictions

 

 

结合离线查询

查询的案例代码

package com.pcx.dao;

 

import java.util.List;

 

import org.hibernate.Criteria;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.criterion.DetachedCriteria;

import org.hibernate.criterion.Order;

import org.hibernate.criterion.Restrictions;

 

 

import com.pcx.model1.Emp;

import com.pcx.util.HibernateSessionFactory;

 

public class QueryTest {

    

    public static void initDate(){

        Session session=HibernateSessionFactory.getSession();

        Transaction tx=session.beginTransaction();

        for (int i = 0; i < 100; i++) {

            Emp e=new Emp();

            e.setName("张三"+i);

            session.save(e);

        }

        tx.commit();

        HibernateSessionFactory.closeSession();

    }

    public static List<Emp> hql1(){

        Session session=HibernateSessionFactory.getSession();

        

        String hql=" from Emp e where e.sal>1000";

        Query query=session.createQuery(hql);

        

        List<Emp>emps=query.list();

        for (Emp emp : emps) {

            System.out.println(emp);

        }

        HibernateSessionFactory.closeSession();

        return emps;

    }

    /**

     * 查询的第二种情况

     * @param args

     */

    public static void hql2(){

        Session session=HibernateSessionFactory.getSession();

        

        String hql="select name,age from Emp ";

        Query query=session.createQuery(hql);

        

        List emps=query.list();

        

        Object[]obj=(Object[]) emps.get(0);

        

        String name=(String) obj[0];

        Integer age=(Integer) obj[1];

        System.out.println("name:"+name+" age:"+age);

        HibernateSessionFactory.closeSession();

    }

    /**

     * 绑定变量

     * @param args

     */

    public static void bindVar(){

        Session session=HibernateSessionFactory.getSession();

        

        String hql="from Emp where name=:name";

        Query q=session.createQuery(hql);

        q.setParameter("name", "张三");

        List<Emp>list=q.list();

        System.out.println(    list.get(0));;

        HibernateSessionFactory.closeSession();

    }

//    使用Criteria

    public static void load1(){

        Session s=HibernateSessionFactory.getSession();

        Criteria c=s.createCriteria(Emp.class);

        //这个Criteria绝大多数的应用是增加条件

//        c.add(Restrictions.eq("name", "李四"));

//        c.add(Restrictions.between("sal", 1000.00, 5000.00));

//        c.add(Restrictions.gt("age", 20));//大于

//        c.add(Restrictions.lt("age", 20));//小于

//        c.add(null).add(null);//可以不停的去add 节省了拼sql的时间

//        c.add(Restrictions.like("name", "李%"));

//        c.setFirstResult(0);

//        c.setMaxResults(20);

        c.addOrder(Order.asc("sal"));

        List<Emp>list=c.list();

        for (Emp emp : list) {

            System.out.println(emp);

        }

        HibernateSessionFactory.closeSession();

    }

    //离线查询
脱离Session 创建查询

    public static void load2(){

        Session session=HibernateSessionFactory.getSession();

        

        DetachedCriteria dc=DetachedCriteria.forClass(Emp.class);

        dc.add(Restrictions.eq("name", "李四"));

        List<Emp>list=dc.getExecutableCriteria(session).list();

        for (Emp emp : list) {

            System.out.println(emp);

        }

        HibernateSessionFactory.closeSession();

    }

    

    //分页查询

    public static void load3(int firstRow,int maxResult){

        Session session=HibernateSessionFactory.getSession();

        Query query=session.createQuery("from Emp");

        query.setFirstResult(firstRow);

        query.setMaxResults(maxResult);

        List<Emp>list=query.list();

        for (Emp emp : list) {

            System.out.println(emp);

        }

        HibernateSessionFactory.closeSession();

    }

    //分页查询二

    public static void load4(int currentPage){

        int pageSize=10;

        int totalPageSize=(int)getTotalSize();

        int pageCount=totalPageSize/pageSize;

        if (totalPageSize%pageSize!=0) {

            pageCount++;

        }

        System.out.println("共"+pageCount+"页");

        System.out.println("共"+totalPageSize+"条记录");

        

        //如果客户给出的
当前页
小于 1 则给当前页赋值1 防止负数的出现

        if (currentPage<1) {

            currentPage=1;

        }

        

        //如果客户给出的当前页大于总页数。则给当前页赋值为最大页数

        if(currentPage>pageCount){

            currentPage = pageCount;

        }

        Session session = HibernateSessionFactory.getSession();

        String hql = "from Emp order by id";

        Query query = session.createQuery(hql);

        query.setFirstResult((currentPage-1)*pageSize);

        query.setMaxResults(pageSize);

        List<Emp> list = query.list();

        

        for (Emp emp : list) {

            System.out.println(emp.getId());

            System.out.println(emp.getName());

        }

        

        

        HibernateSessionFactory.closeSession();

 

    }

    private static long getTotalSize() {

        Session session = HibernateSessionFactory.getSession();

        String hql ="select count(*) from Emp";

        Query query = session.createQuery(hql);

        List list = query.list();

        Object obj = list.get(0);

        return (Long) obj;

 

    }

    public static void main(String[] args) {

//        List<Emp>emps=hql1();

        //Session已经关闭,加载不了对象
如果开启懒加载的话
就不会报错

//        for (Emp emp : emps) {

//            System.out.println(emp);

//        }

        

//        hql2();

//        bindVar();

//        load2();

        initDate();

    }

}

Hibernate笔记③--集合映射、组合映射、联合主键、查询案例的更多相关文章

  1. Hibernate主配置文件、映射配置文件以及复合主键查询

    Hibernate.cfg.xml主配置文件 主配置文件中主要配置:数据库连接信息.其他参数.映射信息! 常用配置查看源码: hibernate-distribution-3.6.0.Final\pr ...

  2. hibernate 联合主键 composite-id

    如果表使用联合主键(一个表有两个以上的主键),你可以映射类的多个属性为标识符属性.如:<composite-id>元素接受<key-property> 属性映射(单表映射)和& ...

  3. Hibernate(5)—— 联合主键 、一对一关联关系映射(xml和注解) 和 领域驱动设计

    俗话说,自己写的代码,6个月后也是别人的代码……复习!复习!复习!涉及的知识点总结如下: One to One 映射关系 一对一单向外键(XML/Annotation) 一对一双向外键关联(XML/A ...

  4. Hibernate联合主键映射

    1.联合主键的映射规则 1) 类中的每个主键属性都对应到数据表中的每个主键列. Hibernate要求具有联合主键的实体类实现Serializable接口,并且重写hashCode与equals方法, ...

  5. hibernate 注解 联合主键映射

    联合主键用Hibernate注解映射方式主要有三种: 第一.将联合主键的字段单独放在一个类中,该类需要实现java.io.Serializable接口并重写equals和hascode,再将 该类注解 ...

  6. Hibernate 中 联合主键映射 组合关系映射 大对象映射(或者说文本大对象,二进制数据大对象)

    Clob:文本大对象,最长4G Blob:二进制数据大对象,最长4G util: public class HibUtil { private static SessionFactory sessio ...

  7. hibernate里联合主键composite-id映射,查询单个主键的问题

    今天项目中遇到这个问题,搞了大半天,现在记录下来hibernate里联合主键配置(多个字段一起作为主键) <class name="com.cskj.hibernate.map.BbW ...

  8. Hibernate注解映射联合主键的三种主要方式

    今天在做项目的时候,一个中间表没有主键,所有在创建实体的时候也未加组件,结果报以下错误: org.springframework.beans.factory.BeanCreationException ...

  9. 联合主键用Hibernate注解映射的三种方式

    第一.将联合主键的字段单独放在一个类中,该类需要实现java.io.Serializable接口并重写equals和hascode,再将该类注解为@Embeddable,最后在主类中(该类不包含联合主 ...

随机推荐

  1. p标签不自动换行原因

    前言:发现以前写的就像是笔记,哪像博客啊,这里再次修改. 问题描述: 在固定宽度的p元素里(任何块级元素同理),长单词不自动换行,中文字符会自动换行,效果如:http://codepen.io/ali ...

  2. mac php项目除了首页全飘not found

    1.httpd.conf配置文件中加载了mod_rewrite.so模块2.AllowOverride None 将None改为 All DocumentRoot "/Library/Web ...

  3. 兼容性/pollyfill/shim/渐进增强/优雅降级

    http://ued.ctrip.com/blog/browser-compatibility-testing-tools-in-firefox-compatibility-detector.html ...

  4. WPF不同线程之间的控件的访问

    原文:WPF不同线程之间的控件的访问 WPF不同线程之间的控件是不同访问的,为了能够访问其他线程之间的控件,需要用Dispatcher.Invoke执行一个新的活动即可. 例如: public voi ...

  5. Caffe中Layer注册机制

    Caffe内部维护一个注册表用于查找特定Layer对应的工厂函数(Layer Factory的设计用到了设计模式里的工厂模式).Caffe的Layer注册表是一组键值对(key, value)( La ...

  6. BZOJ 2395 [Balkan 2011]Time is money

    题面 题解 将\(\sum_i c_i\)和\(\sum_i t_i\)分别看做分别看做\(x\)和\(y\),投射到平面直角坐标系中,于是就是找\(xy\)最小的点 于是可以先找出\(x\)最小的点 ...

  7. CF1039D You Are Given a Tree 根号分治,贪心

    CF1039D You Are Given a Tree LG传送门 根号分治好题. 这题可以整体二分,但我太菜了,不会. 根号分治怎么考虑呢?先想想\(n^2\)暴力吧.对于每一个要求的\(k\), ...

  8. 数据结构与算法 —— 链表linked list(06)

    回文链表 链接 请检查一个链表是否为回文链表. 进阶:你能在 O(n) 的时间和 O(1) 的额外空间中做到吗? 解题思路: 回文链表的特点就是对称. 把链表放到栈中去,利用栈的先进后出的规则,和原链 ...

  9. halcon算子之tuple_gen_const,用于生成特定长度的元组并且初始化其元素

    原文地址:http://blog.sina.com.cn/s/blog_d38f8be50102wczk.html 函数原型: tuple_gen_const(: : Length, Const : ...

  10. opengl-glsl

    GLSL 着色器是使用一种叫GLSL的类C语言写成的.GLSL是为图形计算量身定制的,它包含一些针对向量和矩阵操作的有用特性. 着色器的开头总是要声明版本,接着是输入和输出变量.uniform和mai ...