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

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

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

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

用例代码如下:

  • 数据库DDL语句

1,CAT表

 create table CAT
(
id VARCHAR2(32 CHAR) not null,
create_time TIMESTAMP(6),
update_time TIMESTAMP(6),
cat_name VARCHAR2(255 CHAR),
first_name VARCHAR2(255 CHAR),
last_name VARCHAR2(255 CHAR),
version NUMBER(10) not null
)

2,HOBBY表

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

 package b11_ManyToMany;

 import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.Version;
import model.BaseEntity;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate; @Entity
@DynamicInsert
@DynamicUpdate
public class Cat extends BaseEntity{
/**
* 实体类
*/
private static final long serialVersionUID = -2776330321385582872L; private Set<Hobby> hobby;
private String cat_name;
private Name name;
private int version; @Version
public int getVersion() {
return version;
} public void setVersion(int version) {
this.version = version;
} public String getCat_name() {
return cat_name;
} public void setCat_name(String cat_name) {
this.cat_name = cat_name;
} @Embedded
@AttributeOverrides({
@AttributeOverride(name = "first_name", column = @Column(name = "first_name")),
@AttributeOverride(name = "last_name", column = @Column(name = "last_name")) })
public Name getName() {
return name;
} public void setName(Name name) {
this.name = name;
}
/*
* mappedBy属性:
* 如果关系是单向的,则该关联提供程序确定拥有该关系的字段。
* 如果关系是双向的,则将关联相反(非拥有)方上的 mappedBy 元素设置为拥
* 有此关系的字段或属性的名称
*/
@ManyToMany( fetch = FetchType.EAGER)
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
public Set<Hobby> getHobby() {
return hobby;
} public void setHobby(Set<Hobby> hobby) {
this.hobby = hobby;
}
}

Hobby.java

 package b11_ManyToMany;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import model.BaseEntity; @Entity
public class Hobby extends BaseEntity {
/**
* 实体类
*/
private static final long serialVersionUID = 4921844599282935594L; private String name;
private Set<Cat> cat; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} @ManyToMany(fetch=FetchType.LAZY,mappedBy = "hobby")
public Set<Cat> getCat() {
return cat;
}
public void setCat(Set<Cat> cat) {
this.cat = cat;
}
}

组件类

 package b11_ManyToMany;
import java.io.Serializable;
import javax.persistence.Embeddable; @Embeddable
public class Name implements Serializable {
/**
* 嵌入式组建
*/
private static final long serialVersionUID = -2776330321385582872L; private String first_name;
private String last_name;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
}

Dao

 package daoUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { private static final SessionFactory sessionFactory; static {
try {
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
} public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
} public static Object save(Object obj){
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(obj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
return obj;
} public static void delete(Class<?> clazz,String id){
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Object obj = session.get(clazz,id);
session.delete(obj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
}
}

main

 package b11_ManyToMany;
import java.util.HashSet;
import java.util.Set;
import daoUtil.HibernateUtil; public class Test_ManyToMany { private Cat save(){ Cat cat1 = new Cat();
Cat cat2 = new Cat();
cat1.setCat_name("b11_ManyToMany1");
cat1.setName(new Name()); cat2.setCat_name("b11_ManyToMany2");
cat2.setName(new Name()); Set<Hobby> hobbies = new HashSet<Hobby>(); Hobby hobby1 = new Hobby();
hobby1.setName("足球");
hobbies.add(hobby1); Hobby hobby2 = new Hobby();
hobby2.setName("篮球");
hobbies.add(hobby2); cat1.setHobby(hobbies);
cat2.setHobby(hobbies); HibernateUtil.save(cat1);
HibernateUtil.save(cat2);
System.out.println(cat1.getId());
System.out.println(cat2.getId());
return cat1;
} public static void main(String[] args) {
// 通过cat加载hobby
Cat cat = new Test_ManyToMany().save(); Cat cat1 = (Cat)HibernateUtil.getSession().get(Cat.class, cat.getId());
System.out.println(cat1.getId()); Set<Hobby> hobbies = cat1.getHobby();
for (Hobby hobby : hobbies) {
System.out.println(hobby.getName());
}
// delete
// HibernateUtil.delete(Cat.class,"402880854c75601d014c75602f9f0000"); // 通过hobby加载cat
// Hobby hobby = (Hobby)HibernateUtil.getSession().get(Hobby.class, "402880854c75601d014c75602fbb0001");
// System.out.println(hobby.getId());
//
// Set<Cat> cats = hobby.getCat();
// for (Cat cat2 : cats) {
// System.out.println(cat2.getCat_name());
// }
}
}

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

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

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

  1. Java、Hibernate(JPA)注解大全

    1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Ent ...

  2. hibernate jpa 注解 @Temporal(TemporalType.DATE) 格式化时间日期,页面直接得到格式化类型的值

    1.日期: @Temporal(TemporalType.DATE) @Column(name = "applyDate", nullable = false, length = ...

  3. 【hibernate/JPA】注解方式实现 复合主键【spring boot】

    1>hibernate/JPA实现复合主键的思路:是将所有的主键属性封装在一个主键类中,提供给需要复合主键的实体类使用. 2>主键类的几点要求: . 使用复合主键的实体类必须实现Seria ...

  4. Hibernate 和 JPA 注解

    转载请注明:Hibernate 和 JPA 注解 | 言曌博客 1.@Entity(name="EntityName") 必须, name为可选,对应数据库中一的个表 2.@Tab ...

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

    hibernate是实现了JPA规范,在我们使用hibernate框架的时候,我们引入了hibernate3或者4这个核心包.hibernate-jpa-2.0-api-1.0.0.Final.jar ...

  6. jpa 注解使用说明

    1.@Entity(name="EntityName") 必须,name为可选,对应数据库中一的个表 2.@Table(name="",catalog=&quo ...

  7. Hibernate基于注解方式配置来实现实体和数据库之间存在某种映射关系

    实体和数据库之间存在某种映射关系,hibernate根据这种映射关系完成数据的存取.在程序中这种映射关系由映射文件(*.hbm.xml)或者java注解(@)定义. 本文以java注解的形式总结映射关 ...

  8. Spring Hibernate JPA 联表查询 复杂查询(转)

    今天刷网,才发现: 1)如果想用hibernate注解,是不是一定会用到jpa的? 是.如果hibernate认为jpa的注解够用,就直接用.否则会弄一个自己的出来作为补充. 2)jpa和hibern ...

  9. Spring Hibernate JPA 联表查询 复杂查询

    今天刷网,才发现: 1)如果想用hibernate注解,是不是一定会用到jpa的? 是.如果hibernate认为jpa的注解够用,就直接用.否则会弄一个自己的出来作为补充. 2)jpa和hibern ...

随机推荐

  1. 对JSP和Servlet性能优化,提升执行效率

    你的J2EE应用是不是运行的很慢?它们能不能承受住不断上升的访问量?本文讲述了开发高性能.高弹性的JSP页面和Servlet的性能优化技术.其意思是建立尽可能快的并能适应数量增长的用户及其请求.在本文 ...

  2. Android --ListView模板

    调整了近一上午的模板 ListView表头 <?xml version="1.0" encoding="utf-8"?> <LinearLay ...

  3. Java 线程池的介绍以及工作原理

    在什么情况下使用线程池? 1.单个任务处理的时间比较短 2.将需处理的任务的数量大 使用线程池的好处: 1. 降低资源消耗: 通过重复利用已创建的线程降低线程创建和销毁造成的消耗.2. 提高响应速度: ...

  4. IntelliJ IDEA 的 Java 热部署插件 JRebel 安装及使用

    JRebel 介绍 JRebel for Intellij JRebel 在 Java Web 开发中, 一般更新了 Java 文件后要手动重启 Tomcat 服务器, 才能生效,  自从有了 JRe ...

  5. SWIFT 闭包的简单使用二

    import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: ...

  6. IOS Suppot Font 苹果默认支持的字体一览(配图)

    这些字体都是IOS设备(使用ipad2测试) 默认支持的字体,也就是在AIR中不用设置绑定字体情况下 看到的样子 感觉上应该IOS仅为中文设置了一种字体就是 Heiti SC

  7. For循环输出九九乘法表

    题:使用For循环输出九九乘法表 解析: 1*1=1 1*2=2  2*2=4 1*3=3  2*3=6  3*3=9 .... 1*9=9  ........ .....9*9=81 可以看做j*i ...

  8. nyist 606 ACM之路

    http://acm.nyist.net/JudgeOnline/problem.php?pid=606 ACM之路 时间限制:1000 ms | 内存限制:65535 KB 描述 转眼间,12级新生 ...

  9. MST之kruskal算法

    一.普里姆(Prim)算法 1.基本思想:设G=(V, E)是具有n个顶点的连通网,T=(U, TE)是G的最小生成树, T的初始状态为U={u0}(u0∈V),TE={},重复执行下述操作:在所有u ...

  10. UML:组件图

    要搞清楚组件图,必须先搞清楚什么是组件? 组件有以下特点:1.能实现一定功能,或者提供一些服务.2.不能单独运行,要作为系统的一部分来发挥作用.3.在物理上独立的,不是逻辑上的概念.4.可单独维护.可 ...