十万火急啊!struts+hibernate实现多对多的插入
首先获得checkbox的值,并传入数组中 ,然后将数组值转化为字符串 ,就可以存入数据库了。麻烦的地方在于是插入的中间表中,而中间表里面只有paperId和choiceId两个字段.
JSP页面:
       <input type="text" name="check" value=${paper.paperId}>
  	<input type="checkbox" name="check" value="${choice.choiceId}" />
PaperChoice.hbm.xml
<hibernate-mapping>
     <class name="bean.PaperChoice" table="paper_choice" schema="dbo" catalog="onlineexam">
         <composite-id name="id" class="bean.PaperChoiceId">
             <key-many-to-one name="paper" class="bean.Paper">
                 <column name="paperId" />
             </key-many-to-one>
             <key-many-to-one name="choice" class="bean.Choice">
                 <column name="choiceId" />
             </key-many-to-one>
         </composite-id>
         <many-to-one name="choice" class="bean.Choice" update="false" insert="false" fetch="select">
             <column name="choiceId" not-null="false" />
         </many-to-one>
         <many-to-one name="paper" class="bean.Paper" update="false" insert="false" fetch="select">
             <column name="paperId" not-null="false" />
         </many-to-one>
     </class>
</hibernate-mapping>
数据库操作:
public int addPaperChoice(int id) {
		int result = 0;
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(session.get(PaperChoice.class, id));
			tx.commit();
			result = 1;
		} catch (
HibernateException e) {
			result = 0;
			e.printStackTrace();
			if (tx != null) {
				tx.rollback();
			}
			throw e;
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return result;
	}
action:
//试卷中添加选择题
	public String addPaperChoice(){
		String[] checks=check.split(",");		
		for (int i=0; i<checks.length;i++){		
		paperService.addPaperChoice(new Integer(checks[i].trim()));
		}			
		return "success";
	}
------解决方案--------------------哎 还是没整出来啊!!1
------解决方案--------------------多对多分解成两个一对多啦,这个先放一边 ,其他的呢?
------解决方案--------------------难道就我一个碰到这个问题了?来个基友来讨论下也好哇
------解决方案--------------------
按照你上面的信息来看,你是否想做paper和choice对象的多对多映射关联,hibernate一般针对多对多都是拆解成一对多的关系进行关联映射,也就是说这里边有一个中间表paperchoice;即paper与paperchoice是一对多的关系,这个choice对paperchoice也是一个多对多的关系;由于写下来篇幅太多,这里有一个和你情况差不多的案例,也许对你有一些帮助。
http://lavasoft.blog.51cto.com/62575/39344
------解决方案--------------------这个案例仔细的看过了 非常感谢!!! 有个问题比较郁闷,为什么他的中间表没有实体类?
------解决方案--------------------果断没有么