SSH多对一之便捷之道

SSH整合中,有了多对一后,很多朋友插入对象的时候都觉得很麻烦,下面给大家介绍一个很方便实用的方法,来简化大家的操作。来看下面这样一个例子 :


新闻类(其中新闻和类别形成了多对一的关系)。

package com.qianyan.model;

public class Question{
	
	private Long id;
	private String title;
	private String answer;

       private Long catelogId;   //简单之处在于添加此字段
        private Catelog catelog;
	
	get,set();
	
}

下面看配置文件:Question.hbm.xml

<?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.qianyan.model.Question" table="question">
  
    <id name="id" type="java.lang.Long">
      <generator class="identity"/>
    </id>
    
    <property name="title">
    	<column name="title" length="100"></column>
    </property>
    
    <property name="answer">
    	<column name="answer" length="2000"></column>
    </property>
    
    <!-- 对应同一column="cateloigId" -->
    <property name="catelogId" type="java.lang.Long">
        <column name="catelogId"></column>
    </property>
    
    <!-- 对应同一column="cateloigId" -->
    <many-to-one name="catelog" column="catelogId" insert="false" update="false" lazy="false"></many-to-one> 

  </class>
</hibernate-mapping>
由于catelogId,和catelog对象指向的都上同一个字段column,所以并不产生冗余字段 。



下面来看Action中add的方法,惊喜之处在于此:

package com.qianyan.action;

import java.util.List;

public class QuestionAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Long questionId;
	private Question question = new Question();
	private QuestionService questionService;
        

        private Long catelogId;
        private CatelogService catelogService;

        public String addInput(){
          List<Catelog> list = catelogService.findList();
          request.setAttribute("list", list);
          return "Question_addInput";
        }

        public String add(){
  
          //加上Long catelogId字段的话,不需要再查找类别,然后set(catelog)]
          //这时候就可以直接调用save(question),显得更整洁更简单

          /*
          Catelog catelog = catelogService.findById(catelogId);
          catelog.setCatelog(catelog);
          */

         questionService.save(question);
         return "Question_add_success";

        }
}



你可能感兴趣的:(Hibernate,ssh,J2EE,多对一)