Hibernate annotation 多对多:


下面测试例子会自动生成一张表:card,这张是bank和user表的映射表。里头是bank_id和user_id两个组合字段。

如果想在这张映射表中加入额外的字段,那么hibernate似乎无法做到。因为这需要把多对多写成两个一对多的关系。事实上这样加额外字段到映射表,好像也是违反了DBMS的设计原则。

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property>
<property name="connection.username">root</property>
<property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property> <!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property> <!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property> <mapping class="com.my.bean.User"/>
<mapping class="com.my.bean.Bank"/> </session-factory> </hibernate-configuration>

HibernateUtil.java

package com.my.dao.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
return configuration.configure().buildSessionFactory(
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
} }

Java Beans:

package com.my.bean;

import java.util.Date;
import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table; @Entity
@Table(name="user")
public class User {
@Id @GeneratedValue @Column(name="user_id", nullable=false)
private long userID; @Column(name="user_name", length=100, nullable=false)
private String userName; @Column(name="create_time", nullable=false)
private Date createTime; @ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name="card", joinColumns={@JoinColumn(name="user_id")}, inverseJoinColumns={@JoinColumn(name="bank_id")})
private Set<Bank> banks = new HashSet<Bank>(); public long getUserID() {
return userID;
} public void setUserID(long userID) {
this.userID = userID;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public Set<Bank> getBanks() {
return banks;
} public void setBanks(Set<Bank> banks) {
this.banks = banks;
}
}
package com.my.bean;

import java.util.HashSet;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import org.hibernate.annotations.Cascade; @Entity
@Table(name="bank")
public class Bank {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="bank_id")
private long bankID; @Column(name="bank_name", length=100, nullable=false)
private String BankName; @ManyToMany(mappedBy="banks", cascade={CascadeType.ALL})
private Set<User> users = new HashSet<User>(); public long getBankID() {
return bankID;
} public void setBankID(long bankID) {
this.bankID = bankID;
} public String getBankName() {
return BankName;
} public void setBankName(String bankName) {
BankName = bankName;
} public Set<User> getUsers() {
return users;
} public void setUsers(Set<User> users) {
this.users = users;
}
}

测试:

package com.my.init;
import java.util.Date; import org.hibernate.Session;
import org.hibernate.Transaction; import com.my.bean.Bank;
import com.my.bean.User;
import com.my.dao.util.HibernateUtil; public class Test { public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction(); try {
//-------------------------------------------------------
// add user
//-------------------------------------------------------
User user = new User();
user.setUserName("Robin");
user.setCreateTime(new Date()); //-------------------------------------------------------
// add bank
//-------------------------------------------------------
Bank bankBCC = new Bank();
bankBCC.setBankName("BCC");
Bank bankCBC = new Bank();
bankCBC.setBankName("CBC"); //-------------------------------------------------------
// set relcationship
//-------------------------------------------------------
user.getBanks().add(bankBCC);
user.getBanks().add(bankCBC); //-------------------------------------------------------
// save
//-------------------------------------------------------
session.save(user);
session.save(bankBCC);
session.save(bankCBC); //-------------------------------------------------------
// remove data
//-------------------------------------------------------
session.delete(user); tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} session.close();
} }

参考文档:

http://viralpatel.net/blogs/hibernate-many-to-many-annotation-mapping-tutorial/

[Hibernate] - Annotations - Many To Many的更多相关文章

  1. [Hibernate] - Annotations - One To One

    Hibernate annotation 一对一的两种实现: 1)幅表中有主表的主键ID做为引用 2)幅表的主键即为主表的ID hibernate.cfg.xml <?xml version=& ...

  2. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)

    一.结构 二.Hibernate支持的UserTypes接口  UserType —You can transform values by interacting with the plain JD ...

  3. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-005控制类型映射(Nationalized、@LOB、@org.hibernate.annotations.Type)

    一.简介 1. 2. 3. 4. to override this default mapping. The JPA specification has a convenient shortcut a ...

  4. java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataProvider

    Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/MetadataProvi ...

  5. BAE 环境下 hibernate annotations 配置

     annotations 配置 首先需要加入 hibernate-jpa-2.0-api-1.0.1.Final.jar 和 ejb3-persistence.jar 这两个包 ejb3-persis ...

  6. Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataPro

    1.错误描述 信息: MLog clients using java 1.4+ standard logging. 2014-7-12 19:29:20 com.mchange.v2.c3p0.C3P ...

  7. Hibernate Annotations 注解

    Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么 ...

  8. [Hibernate] - Annotations

    Hibernate使用Annotations最简单例子: hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8 ...

  9. [Hibernate] - Annotations - One To Many

    Hibernate使用Annotation的一对多: hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8&q ...

随机推荐

  1. 【转】Hbase shell 常用命令

    不定时更新常用好用命令. --------------------------------------------------------------------------------------- ...

  2. 2016CCPC东北地区大学生程序设计竞赛1008/HDU 5929 模拟

    Basic Data Structure Time Limit: 7000/3500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Oth ...

  3. CSS控制文本自动换行

    1.你定死表格的宽度,即给表格一个宽度值(是数值,不是百分比) 2.强制不换行 div{ //white-space:不换行;normal 默认;nowrap强制在同一行内显示所有文本,直到文本结束或 ...

  4. php归获取当前目录下的二级目录数 和文件数

    <?php        header('Content-Type: text/html; charset=gb2312');        // $baseDir = "/www/u ...

  5. 带百分号的数据转json

    今天处理前后数据传输的时候遇到了问题. 前台拼参数是这样写的 '&rowData=' + JSON.stringify(rowData); 后台解析出的对象却总是null,而且没有抛Parse ...

  6. PHP内存消耗

    由于变量占用的空间不一样,所以其消耗的内存大小也不一样,在PHP中我们可以通过使用“memory_get_usage”来获取当前PHP消耗的内存.但是根据操作系统.PHP版本以及PHP的运行方式可能输 ...

  7. hdu1269 强连通

    题意:判断给定有向图中是否所有点都能够互相到达. 就是询问是否只有一个强连通分量. #include<stdio.h> #include<string.h> #include& ...

  8. UVA10305 拓扑序

    题意:给出多个任务,以及一系列任务的关系表示某个任务必须在某个任务前完成,问一个合理的任务完成顺序 拓扑序的裸题,一开始用大白书的写法,后来发现并不好用,就换了BFS又A了一遍. 原: #includ ...

  9. console下纯字符实现的贪吃蛇

    最近简直超级无聊-- code blocks win7 64编译运行无问题,应该其他编译器也不会有问题. w:上 s:下 a:左 d:右 CS标准方向控制,AK47和M4这种高级货是没有滴-- 废话不 ...

  10. 黑马程序员——JAVA基础之List集合

    ------- android培训.java培训.期待与您交流! ---------- Collection : |--List:元素是有序的,元素可以重复.因为该集合体系有索引.         | ...