hibernate里两张表的多对多关系映射... 希望详细描述下这么弄 最好能举个例子. 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 http://dev.csdn.net/article/61/61933.shtmA表和B表 这两张表有一个字段关联。那在pojo里,A对象是B对象的一个属性。。Hibernate关联对象的Lazy属性设置了true,当你利用Hibernate查询出一个对象A以后,如果A还有其他的Set对象,此时是没有初始化的。当在程序中调用A.get集合对象时Hibernate才会查询数据库,初始化其集合属性。而如果你查询A以后Session会关闭只知道这些 Hibernate中多对多关系映射2007-05-12 00:23 说明:本文在一个java项目中实现hibernate多对对映射环境:eclipse3.1,oracle10g,hibernate21 新建三张表:categories,category_item,item;categories存储类别,item存储类别下的具体item,category_item存储categories和item两张表中的记录映射关系;sql语句如下:categories表create table WORK.CATEGORIES( ID NUMBER not null, NAME VARCHAR2(32))tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited );alter table WORK.CATEGORIES add constraint CATEGORIES_ID primary key (ID) using index tablespace USERS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited ); category_item表 create table WORK.CATEGORY_ITEM( CATEGORY_ID NUMBER, ITEM_ID NUMBER)tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited );alter table WORK.CATEGORY_ITEM add constraint CATEGORIES_IITEM_ID foreign key (CATEGORY_ID) references WORK.CATEGORIES (ID) on delete cascade;alter table WORK.CATEGORY_ITEM add constraint ITEM_CATEGORIES_ID foreign key (ITEM_ID) references WORK.ITEM (ID) on delete cascade;item表create table WORK.ITEM( ID NUMBER not null, NAME VARCHAR2(32), BASE_PRICE LONG)tablespace USERS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited );alter table WORK.ITEM add constraint ITEM_ID primary key (ID) using index tablespace USERS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K minextents 1 maxextents unlimited );2 在eclipse中新建一个java项目,再新建一个源文件夹src,再在其下新建包:hibernate.manytomany,除hibernate.cfg.xml文件位于src下,其它文件均位于此包下 持久类及其对应的映射文件:Category.java package hibernate.manytomany;import java.util.HashSet;import java.util.Set;public class Category { Long id;String name;Set items = new HashSet(); public Category() {}public Long getId() { return id;}public void setId(Long id) { this.id = id;}public Set getItems() { return items;}public void setItems(Set items) { this.items = items;}public String getName() { return name;}public void setName(String name) { this.name = name;}}Category.hbm.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" ><hibernate-mapping><class name="hibernate.manytomany.Category" table="categories"> <id name="id" type="long" column="ID"> <generator class="increment" /> </id> <property name="name" type="string" column="name" /> <set name="items" table="category_item" lazy="true" cascade="save-update"> <key column="category_id" /> <many-to-many class="hibernate.manytomany.Item" column="item_id" /> </set></class></hibernate-mapping>Item.javapackage hibernate.manytomany;import java.util.HashSet;import java.util.Set;public class Item {Long id;String name;double basePrice;Set category = new HashSet();public Item() {}public Item(String name, double basePrice) { this.name = name; this.basePrice = basePrice;}public double getBasePrice() { return basePrice;}public void setBasePrice(double basePrice) { this.basePrice = basePrice;}public Set getCategory() { return category;}public void setCategory(Set category) { this.category = category;}public Long getId() { return id;}public void setId(Long id) { this.id = id;}public String getName() { return name;}public void setName(String name) { this.name = name;}}Item.hbm.xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" ><hibernate-mapping><class name="hibernate.manytomany.Item" table="item" > <id name="id" type="long" column="ID"> <generator class="increment" /> </id> <property name="name" type="string" column="name" /> <property name="basePrice" type="double" column="BASE_PRICE" /> <set name="category" table="category_item" lazy="true" inverse="true" cascade="save-update"> <key column="ITEM_ID" /> <many-to-many class="hibernate.manytomany.Category" column="CATEGORY_ID" /> </set></class></hibernate-mapping>3 session管理类:HibernateUtil.javapackage hibernate.manytomany;import net.sf.hibernate.*;import net.sf.hibernate.cfg.Configuration;public class HibernateUtil {private static SessionFactory sessionFactory;public static final ThreadLocal session = new ThreadLocal();static { try { // 实例化一个SessionFactory对象 //System.out.println("通过静态模块创建一个SessionFactory"); sessionFactory = new Configuration().configure() .buildSessionFactory(); } catch (HibernateException ex) { throw new RuntimeException("Configuration problem:" + ex.getMessage(), ex); }} public static Session currentSession() throws HibernateException { Session s = (Session) session.get(); // 当原session为空或已关闭时,打一个新的Session if (s == null || !s.isOpen()) { s = sessionFactory.openSession(); session.set(s); } return s;}public static void closeSession() throws HibernateException { Session s = (Session) session.get(); session.set(null); if (s != null) { s.close(); }}}4.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-2.0.dtd"><hibernate-configuration><session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="hibernate.connection.username">work</property> <property name="hibernate.connection.password">caecaodb</property> <property name="hibernate.show_sql">true</property> <property name="dialect">net.sf.hibernate.dialect.OracleDialect</property> <property name="hibernate.jdbc.batch_size">0</property> <property name="hibernate.connection.isloation">2</property> <mapping resource="hibernate/manytomany/Category.hbm.xml"/> <mapping resource="hibernate/manytomany/Item.hbm.xml"/></session-factory></hibernate-configuration>5 测试类Test.javapackage hibernate.manytomany;import net.sf.hibernate.HibernateException;import net.sf.hibernate.Session;import net.sf.hibernate.Transaction;public class Test {public static void main(String[] args) throws HibernateException { // TODO 自动生成方法存根 new Test().saveCategory();}public void saveCategory() throws HibernateException { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); Item item1 = new Item("NEC500", 1000); Item item2 = new Item("BELL4560", 1800); Category category1 = new Category(); category1.setName("CellPhone"); category1.getItems().add(item1); category1.getItems().add(item2); Category category2 = new Category(); category2.setName("NECSeries"); category2.getItems().add(item1); session.save(category1); session.save(category2); tx.commit(); session.close();}}运行Test.java,观察数据库中三张表的记录,体现出了多对多关系注意:1.多对多关系要通过一个中间表来存储记录的多对多关系2.要把其中一方的映射文件中的set标签中的inverse设为true 这方面的例子网上蛮多的就是通过<many-to-many>来操作,两表之间再加个关联表即可! 多对多共有四种形式:角色表 js 用户表 yh 用户角色表 yhjs 第一种形式 : 三张表分别对应一个持久化类,自动生成一个复合主键类,js 和yh 各要配置一个set,yhjs中有一个复合主键类的对象,还有yh 和js的id,还有yh 和js的对象。复合主键类有个变量分别是js 和yh的id。 第二种 :比较简单的一种,就是三个表对应两个持久化类,js 和yh 各要配置一个set,每个set都配置成<many-to-many>详细说太多了,我写不完了~~ java技术群:69705156欢迎加入 eg:学生和课程的关系多对多课程public class Cource { private long id; private String name; private Set students; public long getId() { return id; } private void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getStudents() { return students; } public void setStudents(Set students) { this.students = students; } }<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping> <class name="com.java.model.Cource" table="hiber_cource"> <id name="id"> <column name="cid"></column> <generator class="increment"></generator> </id> <property name="name"></property> <set name="students" cascade="all" table="hiber_stu_cour"> <key column="cid"></key> <many-to-many class="com.java.model.Student" column="sid"></many-to-many> </set> </class></hibernate-mapping>学生package com.java.model;import java.io.Serializable;import java.util.Set;public class Student implements Serializable{ private long id; private String name; private Teacher teacher; private Set cources; public long getId() { return id; } private void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public Set getCources() { return cources; } public void setCources(Set cources) { this.cources = cources; }}<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" ><hibernate-mapping> <class name="com.java.model.Student" table="hiber_student"> <id name="id"> <column name="sid"></column> <generator class="increment"></generator> </id> <property name="name"> <column name="name" ></column> </property> <set name="cources" cascade="all" table="hiber_stu_cour"> <key column="sid"></key> <many-to-many class="com.java.model.Cource" column="cid"></many-to-many> </set> </class></hibernate-mapping> java实现长文章分页 Spring上传文件问题 jsp 中包的使用 问题 如何合并两个XML文件的问题 修改url-pattern后出错 js如何往xml指定位置子写入节点? 问一个hibernate查询的线程问题 如何实现JSR168 java调用一个WebService的短信接口,该如何实现发送短信功能呢? servlet上下文是不是就是webapps那个目录啊!? 哪位高手可以告诉小弟javamail群发邮件如何实现,要jsp版的,希望界面要友好 最重要的 10 几个J2EE 最佳实践[z] --- 有的内容过时了
说明:本文在一个java项目中实现hibernate多对对映射
环境:eclipse3.1,oracle10g,hibernate2
1 新建三张表:categories,category_item,item;categories存储类别,item存储类别下的具体item,category_item存储categories和item两张表中的记录映射关系;sql语句如下:
categories表
create table WORK.CATEGORIES
(
ID NUMBER not null,
NAME VARCHAR2(32)
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
alter table WORK.CATEGORIES
add constraint CATEGORIES_ID primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
category_item表
create table WORK.CATEGORY_ITEM
(
CATEGORY_ID NUMBER,
ITEM_ID NUMBER
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
alter table WORK.CATEGORY_ITEM
add constraint CATEGORIES_IITEM_ID foreign key (CATEGORY_ID)
references WORK.CATEGORIES (ID) on delete cascade;
alter table WORK.CATEGORY_ITEM
add constraint ITEM_CATEGORIES_ID foreign key (ITEM_ID)
references WORK.ITEM (ID) on delete cascade;
item表
create table WORK.ITEM
(
ID NUMBER not null,
NAME VARCHAR2(32),
BASE_PRICE LONG
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
alter table WORK.ITEM
add constraint ITEM_ID primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
2 在eclipse中新建一个java项目,再新建一个源文件夹src,再在其下新建包:hibernate.manytomany,除hibernate.cfg.xml文件位于src下,其它文件均位于此包下
持久类及其对应的映射文件:
Category.java
package hibernate.manytomany;import java.util.HashSet;
import java.util.Set;public class Category {
Long id;
String name;
Set items = new HashSet();
public Category() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set getItems() {
return items;
}
public void setItems(Set items) {
this.items = items;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Category.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" ><hibernate-mapping>
<class name="hibernate.manytomany.Category" table="categories">
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="name" type="string" column="name" />
<set name="items" table="category_item" lazy="true" cascade="save-update">
<key column="category_id" />
<many-to-many class="hibernate.manytomany.Item" column="item_id" />
</set>
</class>
</hibernate-mapping>Item.java
package hibernate.manytomany;import java.util.HashSet;
import java.util.Set;public class Item {
Long id;
String name;
double basePrice;
Set category = new HashSet();
public Item() {
}
public Item(String name, double basePrice) {
this.name = name;
this.basePrice = basePrice;
}
public double getBasePrice() {
return basePrice;
}
public void setBasePrice(double basePrice) {
this.basePrice = basePrice;
}
public Set getCategory() {
return category;
}
public void setCategory(Set category) {
this.category = category;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Item.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" ><hibernate-mapping>
<class name="hibernate.manytomany.Item" table="item" >
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="name" type="string" column="name" />
<property name="basePrice" type="double" column="BASE_PRICE" />
<set name="category" table="category_item" lazy="true" inverse="true" cascade="save-update">
<key column="ITEM_ID" />
<many-to-many class="hibernate.manytomany.Category" column="CATEGORY_ID" />
</set>
</class>
</hibernate-mapping>
3 session管理类:HibernateUtil.java
package hibernate.manytomany;import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static final ThreadLocal session = new ThreadLocal();
static {
try {
// 实例化一个SessionFactory对象
//System.out.println("通过静态模块创建一个SessionFactory");
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Configuration problem:"
+ ex.getMessage(), ex);
}
}
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// 当原session为空或已关闭时,打一个新的Session
if (s == null || !s.isOpen()) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null) {
s.close();
}
}
}
4.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-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">work</property>
<property name="hibernate.connection.password">caecaodb</property>
<property name="hibernate.show_sql">true</property>
<property name="dialect">net.sf.hibernate.dialect.OracleDialect</property>
<property name="hibernate.jdbc.batch_size">0</property>
<property name="hibernate.connection.isloation">2</property> <mapping resource="hibernate/manytomany/Category.hbm.xml"/>
<mapping resource="hibernate/manytomany/Item.hbm.xml"/>
</session-factory>
</hibernate-configuration>5 测试类Test.java
package hibernate.manytomany;import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
public class Test {
public static void main(String[] args) throws HibernateException {
// TODO 自动生成方法存根
new Test().saveCategory();
}
public void saveCategory() throws HibernateException {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Item item1 = new Item("NEC500", 1000);
Item item2 = new Item("BELL4560", 1800); Category category1 = new Category();
category1.setName("CellPhone");
category1.getItems().add(item1);
category1.getItems().add(item2); Category category2 = new Category();
category2.setName("NECSeries");
category2.getItems().add(item1);
session.save(category1);
session.save(category2);
tx.commit();
session.close();
}
}
运行Test.java,观察数据库中三张表的记录,体现出了多对多关系
注意:
1.多对多关系要通过一个中间表来存储记录的多对多关系
2.要把其中一方的映射文件中的set标签中的inverse设为true
角色表 js 用户表 yh 用户角色表 yhjs
第一种形式 : 三张表分别对应一个持久化类,自动生成一个复合主键类,js 和yh 各要配置一个set,yhjs中有一个复合主键类的对象,还有yh 和js的id,还有yh 和js的对象。复合主键类有个变量分别是js 和yh的id。
第二种 :比较简单的一种,就是三个表对应两个持久化类,js 和yh 各要配置一个set,每个set都配置成<many-to-many>详细说太多了,我写不完了~~
欢迎加入
private long id;
private String name;
private Set students;
public long getId() {
return id;
}
private void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getStudents() {
return students;
}
public void setStudents(Set students) {
this.students = students;
}
}<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.java.model.Cource" table="hiber_cource">
<id name="id">
<column name="cid"></column>
<generator class="increment"></generator>
</id>
<property name="name"></property>
<set name="students" cascade="all" table="hiber_stu_cour">
<key column="cid"></key>
<many-to-many class="com.java.model.Student" column="sid"></many-to-many>
</set>
</class>
</hibernate-mapping>学生package com.java.model;import java.io.Serializable;
import java.util.Set;public class Student implements Serializable{
private long id;
private String name;
private Teacher teacher;
private Set cources;
public long getId() {
return id;
}
private void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public Set getCources() {
return cources;
}
public void setCources(Set cources) {
this.cources = cources;
}
}<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.java.model.Student" table="hiber_student">
<id name="id">
<column name="sid"></column>
<generator class="increment"></generator>
</id>
<property name="name">
<column name="name" ></column>
</property>
<set name="cources" cascade="all" table="hiber_stu_cour">
<key column="sid"></key>
<many-to-many class="com.java.model.Cource" column="cid"></many-to-many>
</set>
</class>
</hibernate-mapping>