Hibernate,JPA注解@ManyToMany

@ManyToMany默认值,当双向多对多关联中没有定义任何物理映射时, Hibernate根据以下规则生成相应的值:

关联表名: 主表表名+_下划线+从表表名;

关联到主表的外键名:从表用于关联的属性名+_下划线+主表中的主键列名;

关联到从表的外键名:主表用于关联的属性名+_下划线+从表的主键列名, 以上规则对于双向一对多关联同样有效。

用例代码如下:

  • 数据库DDL语句

1,CAT表

 1 create table CAT
 2 (
 3   id          VARCHAR2(32 CHAR) not null,
 4   create_time TIMESTAMP(6),
 5   update_time TIMESTAMP(6),
 6   cat_name    VARCHAR2(255 CHAR),
 7   first_name  VARCHAR2(255 CHAR),
 8   last_name   VARCHAR2(255 CHAR),
 9   version     NUMBER(10) not null
10 )

2,HOBBY表

1 create table HOBBY
2 (
3   id          VARCHAR2(32 CHAR) not null,
4   create_time TIMESTAMP(6),
5   update_time TIMESTAMP(6),
6   name        VARCHAR2(255 CHAR),
7   cat_id      VARCHAR2(32 CHAR)
8 )
  • hibernate.cfg.xml
 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <!DOCTYPE hibernate-configuration
 3  PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
 4  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!-- 数据库驱动配置 -->
 8         <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
 9         <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
10         <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
11         <property name="connection.username">wxuatuser</property>
12         <property name="connection.password">xlh</property>
13         <property name="show_sql">true</property>
14         <!-- 自动执行DDL属性是update,不是true -->
15         <property name="hbm2ddl.auto">update</property>
16         <!-- hibernate实体类 -->
17
18         <mapping class="b11_ManyToMany.Cat"/>
19         <mapping class="b11_ManyToMany.Hobby"/>
20
21     </session-factory>
22 </hibernate-configuration>
  • java类

实体类 - 基类

package model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
/**
 * 实体类 - 基类
 */
@MappedSuperclass
public class BaseEntity implements Serializable {

    private static final long serialVersionUID = -6718838800112233445L;

    private String id;// ID
    private Date create_time;// 创建日期
    private Date update_time;// 修改日期
    @Id
    @Column(length = 32, nullable = true)
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Column(updatable = false)
    public Date getCreate_time() {
        return create_time;
    }
    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }
    public Date getUpdate_time() {
        return update_time;
    }
    public void setUpdate_time(Date update_time) {
        this.update_time = update_time;
    }
    @Override
    public int hashCode() {
        return id == null ? System.identityHashCode(this) : id.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass().getPackage() != obj.getClass().getPackage()) {
            return false;
        }
        final BaseEntity other = (BaseEntity) obj;
        if (id == null) {
            if (other.getId() != null) {
                return false;
            }
        } else if (!id.equals(other.getId())) {
            return false;
        }
        return true;
    }
}

实体类

Cat.java

 1 package b11_ManyToMany;
 2
 3 import java.util.Set;
 4 import javax.persistence.AttributeOverride;
 5 import javax.persistence.AttributeOverrides;
 6 import javax.persistence.Column;
 7 import javax.persistence.Embedded;
 8 import javax.persistence.Entity;
 9 import javax.persistence.FetchType;
10 import javax.persistence.ManyToMany;
11 import javax.persistence.Version;
12 import model.BaseEntity;
13 import org.hibernate.annotations.Cascade;
14 import org.hibernate.annotations.DynamicInsert;
15 import org.hibernate.annotations.DynamicUpdate;
16
17 @Entity
18 @DynamicInsert
19 @DynamicUpdate
20 public class Cat extends BaseEntity{
21     /**
22      * 实体类
23      */
24     private static final long serialVersionUID = -2776330321385582872L;
25
26     private Set<Hobby> hobby;
27     private String cat_name;
28     private Name name;
29     private int version;
30
31     @Version
32     public int getVersion() {
33         return version;
34     }
35
36     public void setVersion(int version) {
37         this.version = version;
38     }
39
40     public String getCat_name() {
41         return cat_name;
42     }
43
44     public void setCat_name(String cat_name) {
45         this.cat_name = cat_name;
46     }
47
48     @Embedded
49     @AttributeOverrides({
50             @AttributeOverride(name = "first_name", column = @Column(name = "first_name")),
51             @AttributeOverride(name = "last_name", column = @Column(name = "last_name")) })
52     public Name getName() {
53         return name;
54     }
55
56     public void setName(Name name) {
57         this.name = name;
58     }
59     /*
60      * mappedBy属性:
61      * 如果关系是单向的,则该关联提供程序确定拥有该关系的字段。
62      * 如果关系是双向的,则将关联相反(非拥有)方上的 mappedBy 元素设置为拥
63      * 有此关系的字段或属性的名称
64      */
65     @ManyToMany( fetch = FetchType.EAGER)
66     @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
67     public Set<Hobby> getHobby() {
68         return hobby;
69     }
70
71     public void setHobby(Set<Hobby> hobby) {
72         this.hobby = hobby;
73     }
74 }

Hobby.java

 1 package b11_ManyToMany;
 2 import java.util.Set;
 3 import javax.persistence.Entity;
 4 import javax.persistence.FetchType;
 5 import javax.persistence.ManyToMany;
 6 import model.BaseEntity;
 7
 8 @Entity
 9 public class Hobby extends BaseEntity {
10     /**
11      * 实体类
12      */
13     private static final long serialVersionUID = 4921844599282935594L;
14
15     private String name;
16     private Set<Cat> cat;
17
18     public String getName() {
19         return name;
20     }
21     public void setName(String name) {
22         this.name = name;
23     }
24
25     @ManyToMany(fetch=FetchType.LAZY,mappedBy = "hobby")
26     public Set<Cat> getCat() {
27         return cat;
28     }
29     public void setCat(Set<Cat> cat) {
30         this.cat = cat;
31     }
32 }

组件类

 1 package b11_ManyToMany;
 2 import java.io.Serializable;
 3 import javax.persistence.Embeddable;
 4
 5 @Embeddable
 6 public class Name implements Serializable {
 7     /**
 8      * 嵌入式组建
 9      */
10     private static final long serialVersionUID = -2776330321385582872L;
11
12     private String first_name;
13     private String last_name;
14     public String getFirst_name() {
15         return first_name;
16     }
17     public void setFirst_name(String first_name) {
18         this.first_name = first_name;
19     }
20     public String getLast_name() {
21         return last_name;
22     }
23     public void setLast_name(String last_name) {
24         this.last_name = last_name;
25     }
26 }

Dao

 1 package daoUtil;
 2 import org.hibernate.HibernateException;
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.Configuration;
 7 import org.hibernate.service.ServiceRegistry;
 8 import org.hibernate.service.ServiceRegistryBuilder;
 9
10 public class HibernateUtil {
11
12     private static final SessionFactory sessionFactory;
13
14     static {
15         try {
16             Configuration cfg = new Configuration().configure();
17             ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
18                     .applySettings(cfg.getProperties()).buildServiceRegistry();
19             sessionFactory = cfg.buildSessionFactory(serviceRegistry);
20         } catch (Throwable ex) {
21             throw new ExceptionInInitializerError(ex);
22         }
23     }
24
25     public static Session getSession() throws HibernateException {
26         return sessionFactory.openSession();
27     }
28
29     public static Object save(Object obj){
30         Session session = HibernateUtil.getSession();
31         Transaction tx = null;
32         try {
33             tx = session.beginTransaction();
34             session.save(obj);
35             tx.commit();
36         } catch (RuntimeException e) {
37             if (tx != null) {
38                 tx.rollback();
39             }
40             throw e;
41         } finally {
42             session.close();
43         }
44         return obj;
45     }
46
47     public static void delete(Class<?> clazz,String id){
48         Session session = HibernateUtil.getSession();
49         Transaction tx = null;
50         try {
51             tx = session.beginTransaction();
52             Object obj = session.get(clazz,id);
53             session.delete(obj);
54             tx.commit();
55         } catch (RuntimeException e) {
56             if (tx != null) {
57                 tx.rollback();
58             }
59             throw e;
60         } finally {
61             session.close();
62         }
63     }
64 }

main

 1 package b11_ManyToMany;
 2 import java.util.HashSet;
 3 import java.util.Set;
 4 import daoUtil.HibernateUtil;
 5
 6 public class Test_ManyToMany {
 7
 8     private Cat save(){
 9
10         Cat cat1 = new Cat();
11         Cat cat2 = new Cat();
12         cat1.setCat_name("b11_ManyToMany1");
13         cat1.setName(new Name());
14
15         cat2.setCat_name("b11_ManyToMany2");
16         cat2.setName(new Name());
17
18         Set<Hobby> hobbies = new HashSet<Hobby>();
19
20         Hobby hobby1 = new Hobby();
21         hobby1.setName("足球");
22         hobbies.add(hobby1);
23
24         Hobby hobby2 = new Hobby();
25         hobby2.setName("篮球");
26         hobbies.add(hobby2);
27
28         cat1.setHobby(hobbies);
29         cat2.setHobby(hobbies);
30
31         HibernateUtil.save(cat1);
32         HibernateUtil.save(cat2);
33         System.out.println(cat1.getId());
34         System.out.println(cat2.getId());
35         return cat1;
36     }
37
38     public static void main(String[] args) {
39         // 通过cat加载hobby
40         Cat cat = new Test_ManyToMany().save();
41
42         Cat cat1 = (Cat)HibernateUtil.getSession().get(Cat.class, cat.getId());
43         System.out.println(cat1.getId());
44
45         Set<Hobby> hobbies = cat1.getHobby();
46         for (Hobby hobby : hobbies) {
47             System.out.println(hobby.getName());
48         }
49         // delete
50 //        HibernateUtil.delete(Cat.class,"402880854c75601d014c75602f9f0000");
51
52         // 通过hobby加载cat
53 //        Hobby hobby = (Hobby)HibernateUtil.getSession().get(Hobby.class, "402880854c75601d014c75602fbb0001");
54 //        System.out.println(hobby.getId());
55 //
56 //        Set<Cat> cats = hobby.getCat();
57 //        for (Cat cat2 : cats) {
58 //            System.out.println(cat2.getCat_name());
59 //        }
60     }
61 }

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:http://files.cnblogs.com/files/xiluhua/hibernate%40ManyToMany.rar

时间: 2024-11-04 14:03:56

Hibernate,JPA注解@ManyToMany的相关文章

Java、Hibernate(JPA)注解大全

1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Entity配合使用,只能标注在实体的class定义处,表示实体对应的数据库表的信息 name:可选,表示表的名称.默认地,表名和实体名称一致,只有在不一致的情况下才需要指定表名 catalog:可选,表示Catalog名称,默认为Catalog(“”). schema:可选,表示Schema名称,默认为

hibernate自带的注解和jpa注解的冠希

hibernate是实现了JPA规范,在我们使用hibernate框架的时候,我们引入了hibernate3或者4这个核心包.hibernate-jpa-2.0-api-1.0.0.Final.jar这个包的作用是hibernate jpa实现. 注解的选择,建议采用hibernate jpa,为什么呢,如果你要把你的代码移植到其他框架,比如EJB中,那么你可以不修改任何一句代码,就能实现很好的移植.至于hibernate 的table可能会出现莫名其妙的错误,所以基本上都采用hibernate

Hibernate Annotations 注解

Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么使用,但是hibernate中也封装了javax.persistence,而且数据库映射注释主要还是使用javax.persistence,即如下注释元素Column,使用规则如下.  分类: Java(66)  [java] view plain copy @Entity 声明当前是一个持久化类

JPA注解catalog

Table Table用来定义entity主表的name,catalog,schema等属性. 元数据属性说明: name: 表名catalog: 对应关系数据库中的catalog,如果在entitybean中设置此属性,将在表名前面加上catalog指定的值,注意catalog的值一定是数据库的名称,不然会生成的sql语句回报找不到表的错误.schema:对应关系数据库中的schemaUniqueConstraints:定义一个UniqueConstraint数组,指定需要建唯一约束的列   

Spring Hibernate JPA 联表查询 复杂查询

(转自:http://www.cnblogs.com/jiangxiaoyaoblog/p/5635152.html) 今天刷网,才发现: 1)如果想用hibernate注解,是不是一定会用到jpa的? 是.如果hibernate认为jpa的注解够用,就直接用.否则会弄一个自己的出来作为补充. 2)jpa和hibernate都提供了Entity,我们应该用哪个,还是说可以两个一起用? Hibernate的Entity是继承了jpa的,所以如果觉得jpa的不够用,直接使用hibernate的即可

jpa 注解使用说明

1.@Entity(name="EntityName") 必须,name为可选,对应数据库中一的个表 2.@Table(name="",catalog="",schema="") 可选,通常和@Entity配合使用,只能标注在实体的class定义处,表示实体对应的数据库表的信息;name:可选,表示表的名称.默认地,表名和实体名称一致,只有在不一致的情况下才需要指定表名 catalog:可选,表示Catalog名称,默认为Ca

Hibernate+JPA(转)

近年来ORM(Object-Relational Mapping)对象关系映射,即实体对象和数据库表的映射)技术市场人声音鼎沸,异常热闹, Sun在充分吸收现有的优秀ORM框架设计思想的基础上,制定了新的JPA(Java Persistence API)规范.JPA Java Persistence API,是Java EE 5的标准ORM接口,也是ejb3规范的一部分. 那么什么是JPA呢?JPA是通过JDK5.0注解或XML描述对象-关系表的映射关系,并将运行期实体对象持久化到数据库中去.

Hibernate+JPA (EntityMange讲解)

近年来ORM(Object-Relational Mapping)对象关系映射,即实体对象和数据库表的映射)技术市场人声音鼎沸,异常热闹, Sun在充分吸收现有的优秀ORM框架设计思想的基础上,制定了新的JPA(Java Persistence API)规范.JPA Java Persistence API,是Java EE 5的标准ORM接口,也是ejb3规范的一部分. 那么什么是JPA呢?JPA是通过JDK5.0注解或XML描述对象-关系表的映射关系,并将运行期实体对象持久化到数据库中去.

JPA注解实现联合主键

当表中一个主键不能唯一标识一条记录的时候,就需要使用联合主键了,下面是使用JPA注解实现联合主键的代码 1 首先需要建立一个复合主键类,用来存放需要生产联合主键的属性,该类需要实现序列化. package com.ericsson.adp.entity.cons; import java.io.Serializable; public class ConsumerGroupMapPK implements Serializable{ private String msisdn;//电话号码 pr