Hibernate一对多(注解)

 1 <?xml version=‘1.0‘ encoding=‘UTF-8‘?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5
 6 <!-- Generated by MyEclipse Hibernate Tools.                   -->
 7 <hibernate-configuration>
 8
 9 <session-factory>
10     <property name="dialect">
11         org.hibernate.dialect.MySQLDialect
12     </property>
13     <property name="connection.url">
14         jdbc:mysql://localhost:3306/student
15     </property>
16     <property name="connection.username">root</property>
17     <property name="connection.password">123</property>
18     <property name="connection.driver_class">
19         com.mysql.jdbc.Driver
20     </property>
21     <property name="myeclipse.connection.profile">MySQL</property>
22     <property name="show_sql">true</property>
23     <!-- 格式化显示SQL -->
24     <property name="format_sql">true</property>
25
26     <property name="current_session_context_class">thread</property>
27     <!-- 让hibernate自动创建表  update:如果没有表则创建,有表则更新 -->
28     <property name="hbm2ddl.auto">create</property>
29     <mapping class="cqvie.yjq.domain.School" />
30     <mapping class="cqvie.yjq.domain.Student" />
31 </session-factory>
32
33 </hibernate-configuration>

Hibernate.cfg.xml

 1 package cqvie.yjq.domain;
 2
 3 import java.io.Serializable;
 4
 5 import javax.persistence.Column;
 6 import javax.persistence.Entity;
 7 import javax.persistence.GeneratedValue;
 8 import javax.persistence.Id;
 9 import javax.persistence.Table;
10
11 import org.hibernate.annotations.GenericGenerator;
12
13 @Entity
14 @Table(name = "school_2", catalog = "test")
15 public class School implements Serializable {
16
17     private static final long serialVersionUID = -9135891983324864046L;
18
19     @Id
20     @GenericGenerator(name = "generator", strategy = "uuid")
21     @GeneratedValue(generator = "generator")
22     @Column(name = "s_num", unique = true, nullable = false)
23     private String s_num;
24     @Column(name = "s_name", length = 50, nullable = false)
25     private String s_name;
26     @Column(name = "s_addr", length = 100, nullable = false)
27     private String s_addr;
28
29     public String getS_num() {
30         return s_num;
31     }
32     public void setS_num(String sNum) {
33         s_num = sNum;
34     }
35     public String getS_name() {
36         return s_name;
37     }
38     public void setS_name(String sName) {
39         s_name = sName;
40     }
41     public String getS_addr() {
42         return s_addr;
43     }
44     public void setS_addr(String sAddr) {
45         s_addr = sAddr;
46     }
47 }

实体类School

 1 package cqvie.yjq.domain;
 2
 3 import java.io.Serializable;
 4
 5 import javax.persistence.CascadeType;
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.Id;
10 import javax.persistence.JoinColumn;
11 import javax.persistence.ManyToOne;
12 import javax.persistence.Table;
13
14 import org.hibernate.annotations.GenericGenerator;
15
16 @Entity
17 @Table(name = "student_2", catalog = "test")
18 public class Student implements Serializable {
19
20     private static final long serialVersionUID = 7571983435023574040L;
21
22     @Id
23     @GenericGenerator(name = "generator", strategy = "uuid")
24     @GeneratedValue( generator = "generator")
25     @Column(name = "id", nullable = false, unique = true)
26     private String id;
27
28     @Column(name = "name", nullable = false, length = 20)
29     private String name;
30
31     @Column(name = "age", nullable = false, length = 3)
32     private int age;
33
34     @ManyToOne(cascade={CascadeType.ALL})
35     @JoinColumn(name = "s_num")
36     private School school;
37
38     public School getSchool() {
39         return school;
40     }
41     public void setSchool(School school) {
42         this.school = school;
43     }
44     public String getId() {
45         return id;
46     }
47     public void setId(String id) {
48         this.id = id;
49     }
50     public String getName() {
51         return name;
52     }
53     public void setName(String name) {
54         this.name = name;
55     }
56     public int getAge() {
57         return age;
58     }
59     public void setAge(int age) {
60         this.age = age;
61     }
62 }

实体类Student

 1 package cqvie.yjq.View;
 2
 3 import org.hibernate.Session;
 4 import org.hibernate.Transaction;
 5
 6 import cqvie.yjq.Util.HibernataUtil;
 7 import cqvie.yjq.domain.School;
 8 import cqvie.yjq.domain.Student;
 9
10
11 public class Test {
12
13     public static void main(String[] args) {
14
15         Session session = null;
16         Transaction tx = null;
17         try {
18             session =  HibernataUtil.getCurrentSession();
19             tx = session.beginTransaction();
20             //添加
21             School sc = new School();
22             sc.setS_name("重庆工业职业技术学院");
23             sc.setS_addr("重庆渝北");
24
25             Student stu = new Student();
26             stu.setSchool(sc);
27             stu.setAge(17);
28             stu.setName("马士兵");
29
30             session.save(stu);
31
32             tx.commit();
33         } catch (Exception e) {
34             if(tx != null) {
35                 tx.rollback();
36             }
37         } finally {
38             if(session != null && session.isOpen()) {
39                 session.close();
40             }
41         }
42
43     }
44 }

测试类Test

package cqvie.yjq.Util;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

final public class HibernataUtil {

    private static SessionFactory sessionFactory = null;
    //使用线程局部模式
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private HibernataUtil() {};
    static {
        sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    }
    //获取全新的session
    public static Session openSession() {
        return sessionFactory.openSession();
    }
    //获取和线程关联的session
    public static Session getCurrentSession() {
        Session session = threadLocal.get();
        //判断是否得到
        if(session == null) {
            session = sessionFactory.openSession();
            //把session对象设置到threadLocal,相当于已经和线程绑定
            threadLocal.set(session);
        }
        return session;
    }

    //提供一个统一的修改和删除方法(批量)
    public static void executeUpdate(String hql, String[] parameters) {
        Session s = null;
        Transaction ts = null;
        try {
            s = openSession();
            ts = s.beginTransaction();
            Query query = s.createQuery(hql);
            //先判断是否有参数要绑定
            if(parameters != null && parameters.length > 0) {
                for(int i=0;i<parameters.length;i++) {
                    query.setString(i, parameters[i]);
                }
            }
            query.executeUpdate();
            ts.commit();
        } catch(Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            if(s != null && s.isOpen()) {
                s.close();
            }
        }
    }

    //提供一个统一的添加方法
    public static void sava(Object obj) {
        Session s = null;
        Transaction ts = null;
        try {
            s = openSession();
            ts = s.beginTransaction();
            s.save(obj);
            ts.commit();
        } catch (Exception e) {
            if(ts != null) {
                ts.rollback();
            }
            throw new RuntimeException();
        } finally {
            if(s != null && s.isOpen()) {
                s.close();
            }
        }
    }

    //提供一个统一的查询方法(分页)
    @SuppressWarnings("unchecked")
    public static List executeQueryByPage(String hql, String[] parameters, int pageSize, int pageNow) {
        Session s = null;
        List list = null;
        try {
            s = openSession();
            Query query = s.createQuery(hql);
            //先判断是否有参数要绑定
            if(parameters != null && parameters.length > 0) {
                for(int i=0;i<parameters.length;i++) {
                    query.setString(i, parameters[i]);
                }
            }
            query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);
            list = query.list();
        } catch(Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            if(s != null && s.isOpen()) {
                s.close();
            }
        }
        return list;
    }

    //提供一个统一的查询方法 hql 形式 from 类 where 条件=?
    @SuppressWarnings("unchecked")
    public List executeQuery(String hql, String[] parameters) {
        Session s = null;
        List list = null;
        try {
            s = openSession();
            Query query = s.createQuery(hql);
            //先判断是否有参数要绑定
            if(parameters != null && parameters.length > 0) {
                for(int i=0;i<parameters.length;i++) {
                    query.setString(i, parameters[i]);
                }
            }
            list = query.list();
        } catch(Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            if(s != null && s.isOpen()) {
                s.close();
            }
        }
        return list;
    }
}

工具类HibernateUtil

时间: 2024-10-07 09:59:22

Hibernate一对多(注解)的相关文章

Hibernate 一对多注解 实例

student: /** * */ package com.wonders.task.sample.bo; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persisten

hibernate一对多注解

package net.zmcheng.model; import java.util.HashSet;import java.util.Set; import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.GeneratedValue;

Hibernate @OneToMany 一对多注解

配置一 @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="fatherID") //对应儿子类的哪个字段 子类中配置ManyToOne的字段名称 private Set<Child> children; 配置二 @OneToMany(mappedBy = "qeTopic", cascade = CascadeType.ALL, fetch = FetchType.LAZY) //qeTopic

spring+hibernate实体类注解详解(非原创) + cascade属性取值

@Entity //继承策略.另一个类继承本类,那么本类里的属性应用到另一个类中 @Inheritance(strategy = InheritanceType.JOINED ) @Table(name="INFOM_TESTRESULT") public class TestResult extends IdEntity{} 1 @Entity(name="EntityName") 必须 name为可选,对应数据库中一的个表 2 @Table(name="

Hibernate中的注解说明

Hibernate中注解注解比较多,常用的也就那么几个,在这里把Hibernate中的注解汇总总结一下. @Entity:将一个类声明为一个实体bean,即一个持久化POJO; @Id:声明bean的标识属性,即和表中的主键对应的属性: @Table:声明bean映射数据库中指定的表: @Column:声明bean的属性到表的列的映射,该注解还有以下属性: name:可选,属性要映射的列明,如果属性名和列名相同则可以省略: unique:可选,是否在该列上设置唯一约束,默认值为false: nu

Hibernate一对多、多对一关联

一对多.多对一关联:在多方加外键 示例:Group(一方)和User(多方),一个Group可以有多个User,每个User只能属于一个Group   多对一单向关联 在User(多方)中建Group(一方)对象,并添加@ManyToOne注解 1.建Group实体类和User实体类,添加Annotation注解,如下 @Entity @Table(name="_group") //group在MySQL中是关键字,不能直接做表名 public class Group { privat

菜鸟学习Hibernate——一对多关系映射

Hibernate中的关系映射,最常见的关系映射之一就是一对多关系映射例如学生与班级的关系,一个班级对应多个学生.如图: Hibernate中如何来映射这两个的关系呢? 下面就为大家讲解一下: 1.创建实体类Classes和实体类Student Classes.java package com.bjpowernode.hibernate; import java.util.Set; public class Classes { private int id; private String nam

hibernate 一对多关联关系(详细分析)

在领域模型中, 类与类之间最普遍的关系就是关联关系. 在 UML 中, 关联是有方向的. 以 Customer 和 Order 为例: 一个用户能发出多个订单, 而一个订单只能属于一个客户. 从 Order 到 Customer 的关联是多对一关联; 而从 Customer 到 Order 是一对多关联 单向关联 双向关联 单向 n-1 单向 n-1 关联只需从 n 的一端可以访问 1 的一端 域模型: 从 Order 到 Customer 的多对一单向关联需要在Order 类中定义一个 Cus

Rhythmk 学习 Hibernate 08 - Hibernate annotation 关联关系注解

1.一对一 (One to One)    共三种情况:     1.1 主键共享    1.2 外键共享 1.3 中间表关联 1.1  code: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Entity public class article {     @Id     @GeneratedValue    public Integer getArticleId() {         return articleId;     }     .....  

Rhythmk 学习 Hibernate 07 - Hibernate annotation 实体注解

参考: http://docs.jboss.org/hibernate/annotations/3.4/reference/zh_cn/html_single/ 1.系统配置: 可以通过使用  mapping的 resource,于class 属性混合配置 <mapping resource="com/rhythmk/model/product.hbm.xml" /> <mapping class="com.rhythmk.model.User"&