博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
20160507-hibernate入门
阅读量:6229 次
发布时间:2019-06-21

本文共 12414 字,大约阅读时间需要 41 分钟。

关联映射
多对一(Employee - Department)
一对多(Department-Employee)
一对一(Person - IDCard)
多对多(teacher - student)
组件映射(User-Name)
集合映射(set, list, map, bag)
inverse和cascade(Employee – Department)
 
多对一(Employee - Department)
映射文件<many-to-one name=”depart” column=”depart_id”/>
ER图
 
举例:
Department.java
 
package com.dzq.domain;import java.io.Serializable;import java.util.Set;public class Department implements Serializable{    private int id;    private String name;    private Set
empls; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set
getEmpls() { return empls; } public void setEmpls(Set
empls) { this.empls = empls; } }

 


Employee.java

package com.dzq.domain;import java.io.Serializable;public class Employee implements Serializable{    private int id;    private String name;    private Department depart;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Department getDepart() {        return depart;    }    public void setDepart(Department depart) {        this.depart = depart;    }}

 


Department.hbm.xml

 

  


Employee.hbm.xml

 

  测试代码:

public static void addEmAndDe(){        Employee em=new Employee();        Department depart=new Department();        depart.setName("FBI");        em.setDepart(depart);        em.setName("AK47");        HibernateUntils.add(depart);        HibernateUntils.add(em);    }

 

  

一对多(Department-Employee)

 

  

一对一(Person - IdCard)
1)基于主键的one-to-one(person的映射文件)
idCard

例子:

Person.java  主对象

package com.dzq.domain;import java.io.Serializable;public class Person  implements Serializable{    private int id;    private String name;    private IDCard idcard;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public IDCard getIdcard() {        return idcard;    }    public void setIdcard(IDCard idcard) {        this.idcard = idcard;    }}

IDCard.java 从对象

package com.dzq.domain;import java.io.Serializable;public class IDCard  implements Serializable{    private int id;    private String name;    private Person person;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Person getPerson() {        return person;    }    public void setPerson(Person person) {        this.person = person;    }}

IDCard.hbm.xml

person

Person.hbm.xml

 

测试代码:

OneToOne.java

package com.dzq.test;import org.hibernate.Session;import org.hibernate.Transaction;import com.dzq.domain.IDCard;import com.dzq.domain.Person;import com.dzq.utils.HibernateUntils;public class OneToOne {    public static void main(String[] args) {     add();     queryPerson(1);     queryIDcard(1);    }        public static Person add(){        Session s=null;        Transaction ts=null;        try {            s=HibernateUntils.getSession();            Person p=new Person();            IDCard idcard=new IDCard();            idcard.setName("0606");            p.setName("ll");            p.setIdcard(idcard);            idcard.setPerson(p);            ts=s.beginTransaction();            s.save(p);            s.save(idcard);            ts.commit();            return p;        } catch (Exception e) {            if(ts!=null)            ts.rollback();            throw new RuntimeException(e);        }finally{            if(s!=null){                s.close();            }        }    }        /**     * 查询主对象,用连接表查询     * @param id     * @return     */    public static Person queryPerson(int id){        Session s=null;        try {            s=HibernateUntils.getSession();            Person p=(Person) s.get(Person.class, id);            System.out.println(p.getIdcard().getName());            return p;        } finally{            if(s!=null){                s.close();            }        }    }    /**     * 查询从对象,查询两次     * @param id     * @return     */    public static IDCard queryIDcard(int id){        Session s=null;        try {            s=HibernateUntils.getSession();            IDCard idc= (IDCard) s.get(IDCard.class, id);            System.out.println(idc.getPerson().getName());            return idc;        } finally{            if(s!=null){                s.close();            }        }    }}

 

 

2)基于外健的one-to-one,可以描述为多对一,加unique=“true”约束
 

 

 

 

 

 

 

多对多(teacher - student)
在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使用中最好转换成一对多的对象模型;Hibernate会为我们创建中间关联表,转换成两个一对多。
<set name="teacher" table="teacher_student">
<key column="teacher_id"/>
<many-to-many class="Student" column="student_id"/>
</set>
l
 

 

package com.dzq.test;import java.util.HashSet;import java.util.Set;import org.hibernate.Session;import org.hibernate.Transaction;import com.dzq.domain.Student;import com.dzq.domain.Teacher;import com.dzq.utils.HibernateUntils;public class ManyToMany {    public static void main(String[] args) {    add();    query(1);    }        public static void add(){        Session s=null;        Transaction ts=null;        try {            Set
tes=new HashSet
(); Set
stus=new HashSet
(); s=HibernateUntils.getSession(); Teacher t1=new Teacher(); t1.setName("gao"); Teacher t2=new Teacher(); t2.setName("gaoji"); tes.add(t1); tes.add(t2); Student s1=new Student(); s1.setName("hu"); Student s2=new Student(); s2.setName("xiaohu"); stus.add(s1); stus.add(s2); t1.setStudents(stus); t2.setStudents(stus); /*s1.setTeachers(tes); s2.setTeachers(tes);*/ // 会报错,插入重复,要一个就行 ts=s.beginTransaction(); s.save(t1); s.save(t2); s.save(s1); s.save(s2); ts.commit(); } catch (Exception e) { if(ts!=null) ts.rollback(); throw new RuntimeException(e); }finally{ if(s!=null){ s.close(); } } } /** * 多对多查询,效率很低,用的比较少,最好使用分页查询,数据量很小才会使用,数据大量是会存在很严重的性能问题 * @param id */ public static void query(int id){ Session s=null; try { s=HibernateUntils.getSession(); Teacher teacher=(Teacher) s.get(Teacher.class, id); System.out.println(teacher.getStudents().size()); } finally{ if(s!=null){ s.close(); } } } }
组件映射(User-Name)
关联的属性是个复杂类型的持久化类,但不是实体即:数据库中没有表与该属性对应,但该类的属性要之久保存的。
当组件的属性不能和表中的字段简单对应的时候可以选择实现:
org.hibernate.usertype. UserType或
org.hibernate.usertype. CompositeUserType
 
package com.dzq.domain;public class Name {    private String firstName;    private String lastName;    public String getFirstName() {        return firstName;    }    public void setFirstName(String firstName) {        this.firstName = firstName;    }    public String getLastName() {        return lastName;    }    public void setLastName(String lastName) {        this.lastName = lastName;    }}

只会产生一张表

关联关系的级联操作

 

package com.dzq.test;import java.util.HashSet;import java.util.Set;import org.hibernate.Hibernate;import org.hibernate.Session;import org.hibernate.Transaction;import com.dzq.domain.Department;import com.dzq.domain.Employee;import com.dzq.utils.HibernateUntils;public class ManyToOne {       public static void main(String[] args) {        add();    }    public static void addEmAndDe(){        Employee em=new Employee();        Department depart=new Department();        depart.setName("FBI");        em.setDepart(depart);        em.setName("AK47");        HibernateUntils.add(depart);        HibernateUntils.add(em);    }        public static void add(){        Session s=null;        Transaction ts=null;        try {                        Department dep=new Department();            dep.setName("FBI");            Employee e1=new Employee();            Employee e2=new Employee();            e1.setName("hi");            e1.setDepart(dep);            e2.setName("hello");            e2.setDepart(dep);            Set
empls=new HashSet
(); empls.add(e1); empls.add(e2); dep.setEmpls(empls); s=HibernateUntils.getSession(); ts=s.beginTransaction(); //s.save(e1); //s.save(e2); s.save(dep); ts.commit(); } catch (Exception e) { ts.rollback(); throw new RuntimeException(e); }finally{ if(s!=null){ s.close(); } } } }

 

 

转载于:https://www.cnblogs.com/xiaoduc-org/p/5467938.html

你可能感兴趣的文章
Data Guard实现故障自动切换(二)(r11笔记第39天)
查看>>
[20171211]ora-16014 11g.txt
查看>>
oracle的正则表达式
查看>>
这几天的两件趣事
查看>>
小块头大作用 新型低成本测距传感器适用于无人机
查看>>
VSTO之旅系列(五):创建Outlook解决方案
查看>>
[erlang] mnesia
查看>>
php编码
查看>>
Java使用Socket传输文件遇到的问题(转)
查看>>
MYSQL-用户权限的验证过程(转)
查看>>
快递配送最后一公里的痛:利益失衡后开始崩塌
查看>>
深入理解Tomcat系列之一:系统架构(转)
查看>>
ArcMap打开越来越慢
查看>>
nagios客户端未启动报错
查看>>
Redux
查看>>
基于API调用的恶意软件分析技术
查看>>
顺序容器
查看>>
NodeJs——进程管理(一)
查看>>
微信支付开发(7) H5支付
查看>>
ffmpeg解码RTSP/TCP视频流H.264(QT界面显示视频画面)
查看>>