Hibernate的多对多实现:
hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1/testdb root 1 org.hibernate.dialect.MySQL5Dialect thread org.hibernate.cache.internal.NoCacheProvider true update
mapping配置:
Bank.hbm.xml
User.hbm.xml
POJO
package com.my.bean;import java.util.Set;public class Bank { private long bankID; private String bankName; private Setusers; public long getBankID() { return bankID; } public void setBankID(long bankID) { this.bankID = bankID; } public String getBankName() { return bankName; } public void setBankName(String bankName) { this.bankName = bankName; } public Set getUsers() { return users; } public void setUsers(Set users) { this.users = users; }}
package com.my.bean;import java.util.Set;public class User { private long userID; private String userName; private Setbanks; 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 Set getBanks() { return banks; } public void setBanks(Set banks) { this.banks = banks; }}
测试:
package com.my.init;import java.util.HashSet;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 { // create user User userRobin = new User(); userRobin.setUserName("Robin"); userRobin.setBanks(new HashSet()); User userBen = new User(); userBen.setUserName("Ben"); userBen.setBanks(new HashSet ()); // create bank Bank bankCBC = new Bank(); bankCBC.setBankName("CBC"); bankCBC.setUsers(new HashSet ()); Bank bankBBC = new Bank(); bankBBC.setBankName("BBC"); bankBBC.setUsers(new HashSet ()); // add relationship userRobin.getBanks().add(bankCBC); userRobin.getBanks().add(bankBBC); userBen.getBanks().add(bankCBC); userBen.getBanks().add(bankBBC); session.save(userRobin); session.save(userBen); session.save(bankCBC); session.save(bankBBC); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } session.close(); }}
上面测试例子会自动生成一张表:card,这张是bank和user表的映射表。里头是bank_id和user_id两个组合字段。
如果想在这张映射表中加入额外的字段,那么hibernate似乎无法做到。因为这需要把多对多写成两个一对多的关系。事实上这样加额外字段到映射表,好像也是违反了DBMS的设计原则。