可以通过@ManyToMany注解可定义的多对多关联。同时,也需要通过注解@JoinTable描述关联表和关联条件。如果是双向关联,其中一段必须定义为owner,另一端必须定义为inverse(在对关联表进行更新操作时这一端将被忽略)。被关联端不必也不能描述物理映射: 只需要一个简单的mappedBy参数,该参数包含了主体端的属性名,这样就绑定双方的关系。
用例代码如下:
- 数据库DDL语句
1,CAT表
create table CAT
(
id VARCHAR2(32 CHAR) not null,
create_time TIMESTAMP(6) default sysdate,
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="b12_ManyToMany_JoinTable.Cat"/>
<mapping class="b12_ManyToMany_JoinTable.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 b12_ManyToMany_JoinTable;
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.JoinColumn;
import javax.persistence.JoinTable;
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 String cat_name;
private Name name;
private int version; private Set<Hobby> hobby; @ManyToMany(fetch = FetchType.EAGER)
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinTable(name = "CAT_HOBBY",
joinColumns = { @JoinColumn(name = "CAT_ID") },
inverseJoinColumns = { @JoinColumn(name = "HOBBY_ID") })
public Set<Hobby> getHobby() {
return hobby;
} public void setHobby(Set<Hobby> hobby) {
this.hobby = hobby;
}
@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;
}
}
Hobby.java
package b12_ManyToMany_JoinTable;
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; @ManyToMany(mappedBy = "hobby",fetch=FetchType.LAZY)
public Set<Cat> getCat() {
return cat;
}
public void setCat(Set<Cat> cat) {
this.cat = cat;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
组件类
package b12_ManyToMany_JoinTable;
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 b12_ManyToMany_JoinTable;
import java.util.HashSet;
import java.util.Set;
import daoUtil.HibernateUtil; public class Test_ManyToMany_JoinTable { private Cat save(){
Cat cat1 = new Cat();
Cat cat2 = new Cat();
cat1.setCat_name("b12_ManyToMany_JoinTable1");
cat2.setCat_name("b12_ManyToMany_JoinTable2"); 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_JoinTable().save(); // Cat cat1 = (Cat)HibernateUtil.getSession().get(Cat.class, "8a6cc5a34c77d08f014c77d0a0490003");
// System.out.println(cat1.getId());
//
// Set<Hobby> hobbies = cat1.getHobby();
// for (Hobby hobby : hobbies) {
// System.out.println(hobby.getName());
// }
//
// // delete
// HibernateUtil.delete(Cat.class, "8a6cc5a34c77d08f014c77d0a0490003"); // 通过hobby加载cat
// Hobby hobby = (Hobby)HibernateUtil.getSession().get(Hobby.class, "8a6cc5a34c77d08f014c77d09fbb0001");
// System.out.println(hobby.getId());
//
// Set<Cat> cats = hobby.getCat();
// for (Cat cat : cats) {
// System.out.println(cat.getCat_name());
// }
}
}
环境:JDK1.6,MAVEN,tomcat,eclipse
源码地址:http://files.cnblogs.com/files/xiluhua/hibernate%40ManyToMany_JoinTable.rar
Hibernate,JPA注解@ManyToMany_JoinTable的更多相关文章
-
Java、Hibernate(JPA)注解大全
1.@Entity(name=”EntityName”) 必须,name为可选,对应数据库中一的个表 2.@Table(name=””,catalog=””,schema=””) 可选,通常和@Ent ...
-
hibernate jpa 注解 @Temporal(TemporalType.DATE) 格式化时间日期,页面直接得到格式化类型的值
1.日期: @Temporal(TemporalType.DATE) @Column(name = "applyDate", nullable = false, length = ...
-
【hibernate/JPA】注解方式实现 复合主键【spring boot】
1>hibernate/JPA实现复合主键的思路:是将所有的主键属性封装在一个主键类中,提供给需要复合主键的实体类使用. 2>主键类的几点要求: . 使用复合主键的实体类必须实现Seria ...
-
hibernate自带的注解和jpa注解的冠希
hibernate是实现了JPA规范,在我们使用hibernate框架的时候,我们引入了hibernate3或者4这个核心包.hibernate-jpa-2.0-api-1.0.0.Final.jar ...
-
Hibernate 和 JPA 注解
转载请注明:Hibernate 和 JPA 注解 | 言曌博客 1.@Entity(name="EntityName") 必须, name为可选,对应数据库中一的个表 2.@Tab ...
-
jpa 注解使用说明
1.@Entity(name="EntityName") 必须,name为可选,对应数据库中一的个表 2.@Table(name="",catalog=&quo ...
-
Hibernate基于注解方式配置来实现实体和数据库之间存在某种映射关系
实体和数据库之间存在某种映射关系,hibernate根据这种映射关系完成数据的存取.在程序中这种映射关系由映射文件(*.hbm.xml)或者java注解(@)定义. 本文以java注解的形式总结映射关 ...
-
Hibernate+JPA (EntityMange讲解)
近年来ORM(Object-Relational Mapping)对象关系映射,即实体对象和数据库表的映射)技术市场人声音鼎沸,异常热闹, Sun在充分吸收现有的优秀ORM框架设计思想的基础上,制定了 ...
-
spring+hibernate+jpa+Druid的配置文件,spring整合Druid
spring+hibernate+jpa+Druid的配置文件 spring+hibernate+jpa+Druid的完整配置 spring+hibernate+jpa+Druid的数据源配置 spr ...
随机推荐
-
post和get请求
get请求:不安全,参数在url地址中的参数的长度不能大于1024字节 post请求:安全,参数都是凤凰族昂在data里的,参数长度不限
-
linux同步系统时间
命令:ntpdate 路径:/usr/sbin/ntpdate 例子:ntpdate us.pool.ntp.org 查看日期时间命令:date 修改日期时间命令:date -s "2012 ...
-
li ul 说明
复制代码代码如下: <div id="menu"> <ul> <li><a href="#">首页</ ...
-
js压缩、混淆和加密
最近看到有些论坛在讨论js压缩.混淆和加密的问题,特意找了些资料看了下,现在总结一下: 1.关于三者的定义与区别 压缩:删除 Javascript 代码中所有注释.跳格符号.换行符号及无用的空格,从而 ...
-
linux一些常用指令整理
set number:设置行号 set list:区分tab和空格 按w:一个字一个字跳转 按b:一个字一个字回跳 shift+6:行首 shift+4:行尾 ctrl+v:选中块,再按shift+i ...
-
JNI加载Native Library 以及 跨线程和Qt通信
Part1 Java Native Interface-JNI-JAVA本地调用 JNI标准是Java平台的一部分, 允许Java代码和其他语言进行交互; 开始实现-> Step 1) 编写Ja ...
-
Stem Cell 华人科学家
Jianping Fu 密歇根大学机械工程系生物医学工程专业 PhD, Massachusetts Institute of Technology, 2007MS, University of Cal ...
-
linux批量压缩当前目录中文件后,删除原文件
linux批量压缩当前目录中文件后,删除原文件 for i in `ls|awk -F " " '{print $NF}'`; do tar -zcvf $i.tar.gz $i ...
-
输出第n个丑数
方法一:暴力法 代码如下: 判断是否是丑数 public static boolean isUgly(int n){ while(n!=1){ if(n%2 == 0){ n /= 2; }else ...
-
lua的String
基础字符串函数 字符串库中有一些函数非常简单,如: 1). string.len(s) 返回字符串s的长度: 2). string.rep(s,n) 返回字符串s重复n次的结果: 3 ...