小弟正在用Hibernate+struts练习一个投票项目。
1)建表如下:create table question
(
  id int not null primary key,
  questionName varchar(255),
  questionType char(10)
);
create table item
(
  id int not null primary key,
  item varchar(255),
  count int,
  questionId int,
  idx int,
  foreign key item(questionId) references question(id)
)2)Question.javapackage com.hibernate.model;import java.util.ArrayList;
import java.util.List;public class Question
{
private Integer id;
private String questionName;
private String questionType;
private List items = new ArrayList();
public Question(String questionName,String questionType,List items)
{
this.questionName = questionName;
this.questionType = questionType;
this.items = items;
}
public Question()
{

}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getQuestionName()
{
return questionName;
}
public void setQuestionName(String questionName)
{
this.questionName = questionName;
}

public String getQuestionType()
{
return questionType;
}
public void setQuestionType(String questionType)
{
this.questionType = questionType;
}
public List getItems()
{
return items;
}
public void setItems(List items)
{
this.items = items;
}
}3)Question.hbm.xml<?xml version="1.0"?>
<!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.hibernate.model.Question" table="question">
<id name="id" column="id" type="int">
<generator class="increment"></generator>
</id>
<property name="questionName" column="questionName" type="string"></property>
<property name="questionType" column="questionType" type="string"></property> <list name="items" table="item" cascade="all">
<key column="questionId"></key>
<!-- idx 字段用来记录 保存的数据的顺序  -->
            <index column="idx" type="int"></index>
<one-to-many class="com.hibernate.model.Item"/>
</list>
</class>
</hibernate-mapping>
4)Item.javapackage com.hibernate.model;public class Item
{
private int id;
private String item;
private int count;
private Question question;
public Item(String item,Question question)
{
this.item = item;
this.question = question;
}
public Item()
{

}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getItem()
{
return item;
}
public void setItem(String item)
{
this.item = item;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public Question getQuestion()
{
return question;
}
public void setQuestion(Question question)
{
this.question = question;
}
}5)Item.hbm.xml<?xml version="1.0"?>
<!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.hibernate.model.Item" table="item">
<id name="id" column="id" type="int">
<generator class="increment"></generator><!-- 主键id的生成方式为自增,这里也可以在数据库中设置 -->
</id>
<property name="item" type="string">
<column name="item"></column>
</property>
<property name="count" type="int">
<column name="count"></column>
</property>
<many-to-one name="question" column="questionId" class="com.hibernate.model.Question"></many-to-one>
</class>
</hibernate-mapping>
6)createPoll.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html>
  <head>
    <title>创建投票项目</title>
    <script type="text/javascript">
function additem()
{
     var items = document.getElementById("items");
    var input = document.createElement("input");
    input.name="item";
     input.type="text";
     input.size="55";
     var delButton = document.createElement("input");
     delButton.type="button";
     delButton.value="删除";
     delButton.onclick=function del()
     {
        this.parentNode.parentNode.removeChild(this.parentNode);
     }
     var div = document.createElement("div");
     div.appendChild(input);
     div.appendChild(delButton);
     items.appendChild(div);
}
</script>
  </head>
  <body>
    <h1 align="center">&nbsp;&nbsp;&nbsp;创建投票项目</h1>
    <form action="createPoll.action" method="post">
    <table align="center" width="60%" border="1">
     <tr>
     <th width="30%">是否多选:</th>
     <td align="center" width="70%">
     单选<input type="radio" name="questionType" value="radio" checked>
     多选<input type="radio" name="questionType" value="checkbox">
     </td>
     </tr>
     <tr>
     <th>投票问题:</th>
     <td align="center"><input type="text" name="questionName" size="61"></td>
     </tr>
     <tr>
     <th>投票选项:</th>
     <td align="center">
     <table>
     <tr>
     <td>
     <input type="text" name="item" size="45">&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="增加选项" onclick="additem()">
             <div id="items"></div>
     </td>
     </tr>
     </table>
     </td>
     </tr>
    </table>
    <table align="center" width="60%">
     <tr height="20"><td></td></tr>
     <tr>
     <td align="center" colspan="2"><input type="submit" value="下一步">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     <input type="reset" value="重置">
     </td>
     </tr>
    </table>
    </form>
  </body>
</html>7)CreatePollAction.javapackage com.hibernate.action;import java.util.ArrayList;
import java.util.List;import org.hibernate.Session;
import org.hibernate.Transaction;import com.hibernate.model.Item;
import com.hibernate.model.Question;
import com.hibernate.util.HibernateUtil;
import com.opensymphony.xwork2.ActionSupport;public class CreatePollAction extends ActionSupport
{
private String questionType;
private String questionName;
private String[] item;
private int count;
public String getQuestionType()
{
return questionType;
}
public void setQuestionType(String questionType)
{
this.questionType = questionType;
}
public String[] getItem()
{
return item;
}
public void setItem(String[] item)
{
this.item = item;
}
public String getQuestionName()
{
return questionName;
}
public void setQuestionName(String questionName)
{
this.questionName = questionName;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public String createPoll() throws Exception
{
//将由页面提交的数组转化为List
List items = new ArrayList();
for(int i=0;i<item.length;i++)
{
items.add(item[i]);
}

System.out.println(items);


Session session = HibernateUtil.currentSession();
Transaction tx = null; //开启事务
try
{
tx = session.beginTransaction();
Question question = new Question(questionName, questionType, items);

Item item = new Item();
for(int i=0;i<this.item.length;i++)
{
item.setItem(this.item[i]);
item.setCount(count);
System.out.println("选择个数:"+count);
item.setQuestion(question);
}

session.save(question);
tx.commit();

}
catch(Exception ex)
{
System.out.println("增加用户异常发生!");
ex.printStackTrace();
if(null != tx)
{
tx.rollback();
}
}
finally
{
HibernateUtil.closeSession(session);
}
return SUCCESS;
}
}
以上为相关的代码,数据没能插入数据库
增加用户异常发生!抛出的异常为:
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.hibernate.model.Item.id
另外,web.xml和struts.xml都没有问题,在这里就不贴出来了。自己也上网查过,还是没有能找出是哪儿的问题,不过我怀疑是Question.hbm.xml中的list映射弄出的问题,请各位大大帮助小弟!谢谢!

解决方案 »

  1.   

    补充一下,CreatePollAction.java中session.save(question);语句之前都能执行到,就是到了这一句抛出了异常!
      

  2.   

    LZ,你解决这个问题了么?你是北大青鸟的学员吧?我也是,我也在做这个项目呢!这个问题困扰我一整晚了,烦死人了!
    大家也帮忙解决一下!
    我是用Hibernate的传播性持久化做级联时添加数据报错的,我先看了Hibernate的API,但还是没发现问题所在,也上网查了好多,网上好多人都遇到过这个问题,照着做,但没一个解决方法是可以的:有说类型与配置文件的不匹配(如Integer类型),有说配置文件要加cascade="all",有说getter,setter方法不一致等等。这些我都没做错,每个文件我都很细心的检查了,都没发现问题所在,请大家帮忙解决一下,先谢啦!这个项目有两个框架Struts2、Hibernate集成(都是最新版本)报错内容:
    22:44:41,680 ERROR [org.hibernate.property.BasicPropertyAccessor] IllegalArgumentException in class: com.jbit.entity.VoteOption, getter method of property: voId
    org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.jbit.entity.VoteOption.voId
    at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:195)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:199)
    at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:3605)
    at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:3321)....不全贴出了实体类(投票主题类):
    package com.jbit.entity;import java.util.HashSet;
    import java.util.Set;/**
     * VoteSubject entity. @author MyEclipse Persistence Tools
     */public class VoteSubject implements java.io.Serializable { // Fields /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer vsId;
    private String vsTitle;
    private Integer vsType;
    @SuppressWarnings("rawtypes")
    private Set voteOptions = new HashSet(0);
    @SuppressWarnings("rawtypes")
    private Set voteItems = new HashSet(0); // Constructors /** default constructor */
    public VoteSubject() {
    } /** minimal constructor */
    public VoteSubject(String vsTitle, Integer vsType) {
    this.vsTitle = vsTitle;
    this.vsType = vsType;
    } /** full constructor */
    public VoteSubject(String vsTitle, Integer vsType, @SuppressWarnings("rawtypes") Set voteOptions,
    @SuppressWarnings("rawtypes") Set voteItems) {
    this.vsTitle = vsTitle;
    this.vsType = vsType;
    this.voteOptions = voteOptions;
    this.voteItems = voteItems;
    } // Property accessors public Integer getVsId() {
    return this.vsId;
    } public void setVsId(Integer vsId) {
    this.vsId = vsId;
    } public String getVsTitle() {
    return this.vsTitle;
    } public void setVsTitle(String vsTitle) {
    this.vsTitle = vsTitle;
    } public Integer getVsType() {
    return this.vsType;
    } public void setVsType(Integer vsType) {
    this.vsType = vsType;
    } @SuppressWarnings("rawtypes")
    public Set getVoteOptions() {
    return this.voteOptions;
    } public void setVoteOptions(@SuppressWarnings("rawtypes") Set voteOptions) {
    this.voteOptions = voteOptions;
    } @SuppressWarnings("rawtypes")
    public Set getVoteItems() {
    return this.voteItems;
    } public void setVoteItems(@SuppressWarnings("rawtypes") Set voteItems) {
    this.voteItems = voteItems;
    }}
    实体类(投票选项类):
    package com.jbit.entity;import java.util.HashSet;
    import java.util.Set;/**
     * VoteOption entity. @author MyEclipse Persistence Tools
     */public class VoteOption implements java.io.Serializable { // Fields /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer voId;
    private VoteSubject voteSubject;
    private String voOption;
    @SuppressWarnings("rawtypes")
    private Set voteItems = new HashSet(0); // Constructors /** default constructor */
    public VoteOption() {
    } /** minimal constructor */
    public VoteOption(VoteSubject voteSubject, String voOption, Integer voId) {
    this.voteSubject = voteSubject;
    this.voOption = voOption;
    this.voId=voId;
    } /** full constructor */
    public VoteOption(VoteSubject voteSubject, String voOption,
    Integer voId, @SuppressWarnings("rawtypes") Set voteItems) {
    this.voteSubject = voteSubject;
    this.voOption = voOption;
    this.voId=voId;
    this.voteItems = voteItems;
    } // Property accessors public Integer getVoId() {
    return this.voId;
    } public void setVoId(Integer voId) {
    this.voId = voId;
    } public VoteSubject getVoteSubject() {
    return this.voteSubject;
    } public void setVoteSubject(VoteSubject voteSubject) {
    this.voteSubject = voteSubject;
    } public String getVoOption() {
    return this.voOption;
    } public void setVoOption(String voOption) {
    this.voOption = voOption;
    } @SuppressWarnings("rawtypes")
    public Set getVoteItems() {
    return this.voteItems;
    } @SuppressWarnings("rawtypes")
    public void setVoteItems(Set voteItems) {
    this.voteItems = voteItems;
    }}
    实体类(投票主题)配置文件:
    <?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">
    <!-- 
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="com.jbit.entity.VoteSubject" table="VOTE_SUBJECT" schema="VOTE">
            <id name="vsId" type="java.lang.Integer">
                <column name="VS_ID" precision="10" scale="0" />
                <generator class="sequence">
                 <param name="sequence">SEQ_VS_ID</param>
                </generator>
            </id>
            <property name="vsTitle" type="java.lang.String" lazy="false">
                <column name="VS_TITLE" length="200" not-null="true" />
            </property>
            <property name="vsType" type="java.lang.Integer" lazy="false">
                <column name="VS_TYPE" precision="6" scale="0" not-null="true" />
            </property>
            <set name="voteOptions" inverse="true" lazy="false" cascade="all">
                <key>
                    <column name="VS_ID" precision="10" scale="0" not-null="true" />
                </key>
                <one-to-many class="com.jbit.entity.VoteOption" />
            </set>
            <set name="voteItems" inverse="true" lazy="false" cascade="all">
                <key>
                    <column name="VS_ID" precision="10" scale="0" />
                </key>
                <one-to-many class="com.jbit.entity.VoteItem" />
            </set>
        </class>
    </hibernate-mapping>
    实体类(投票选项)配置文件:
    <?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">
    <!-- 
        Mapping file autogenerated by MyEclipse Persistence Tools
    -->
    <hibernate-mapping>
        <class name="com.jbit.entity.VoteOption" table="VOTE_OPTION" schema="VOTE">
            <id name="voId" type="java.lang.Integer">
                <column name="VO_ID" precision="10" scale="0" />
                <generator class="sequence">
                 <param name="sequence">SEQ_VO_ID</param>
                </generator>
            </id>
            <many-to-one name="voteSubject" class="com.jbit.entity.VoteSubject" fetch="select" lazy="false" cascade="all">
                <column name="VS_ID" precision="10" scale="0" not-null="true" />
            </many-to-one>
            <property name="voOption" type="java.lang.String" lazy="false">
                <column name="VO_OPTION" length="100" not-null="true" />
            </property>
            <set name="voteItems" inverse="true" lazy="false">
                <key>
                    <column name="VO_ID" precision="10" scale="0" not-null="true" />
                </key>
                <one-to-many class="com.jbit.entity.VoteItem" />
            </set>
        </class>
    </hibernate-mapping>
    页面代码:
    <body>
    <jsp:include page="top.jsp" />
    <div id="voteManage" class="box">
    <h2>添加新投票</h2>
    <div class="content">
    <form method="post" action="sendOrSaveAction.action">
    <dl>
    <dt>投票内容:</dt>
    <dd>
       <input type="hidden" name="vs.vsId" value="<s:property value='vs.vsId'/>"/>
       <input type="text" class="input-text" name="vs.vsTitle"  value="<s:property value='vs.vsTitle'/>"/>
    </dd>
    <dt>投票类型:</dt>
    <dd>
          <input type="radio" name="vs.vsType"<s:if test="vs==null">checked="checked"</s:if> <s:if test="vs.vsType==1"> checked="checked" </s:if>value="1" />单选
       <input type="radio" name="vs.vsType" <s:if test="vs.vsType==2"> checked="checked" </s:if>value="2" />多选
    </dd>
    <dt>投票选项:</dt>
    <s:if test="vs==null">
    <dd id="voteoptions">
    <p><input type="text" class="input-text" name="vs.voteOptions" /></p>
    <p><input type="text" class="input-text" name="vs.voteOptions" /></p>
    </dd>
    </s:if>
    <s:else>
    <dd id="voteoptions">
    <input type="hidden" name="voId" value="<s:property value='vs.vsId'/>"/>
    <s:iterator value="vs.voteOptions" status="status">
    <p><input type="text" class="input-text" name="vs.voteOptions" value="<s:property value='voOption'/>"/><s:if test="#status.index>1"><a class="del" href="javascript:;" onclick="DelOption()">删除</a></s:if></p>
    </s:iterator>
    </dd>
    </s:else>
    <dt></dt>
    <dd class="button">
    <input type="image" src="images/button_submit.gif" />
    <a href="javascript:;" onclick="AddOption()">增加选项</a>
    <a href="indexAction.action">取消操作</a>
    </dd>
    </dl>
    </form>
    </div>
    </div>
    <div id="footer" class="wrap">
    北大青鸟 &copy; 版权所有
    </div>
    </body>
    Action:
    public String sendOrSave(){//发布或保存投票
    try {
    boolean con = false;
    con = session.get("state").equals("add") ? vb.subjectSend(vs) : vb.subjectSave(vs);
    return con ? SUCCESS : ERROR;
    } catch (Exception e) {
    e.printStackTrace();
    return ERROR;
    }
    }
    业务实现:
    @Override
    public boolean subjectSend(VoteSubject vs) {//发布投票主题
    return add.ADU(vs, MarkerADU.add);
    } @Override
    public boolean subjectSave(VoteSubject vs) {//保存投票主题
    return add.ADU(vs, MarkerADU.update);
    }
    数据库实现:
    public boolean ADU(Object entity,MarkerADU m) {
    Session s = HibernateUtil.getSession();
    Transaction tx = s.beginTransaction();
    try {
    if (m.equals(MarkerADU.add)) {
    s.save(entity);
    } else if (m.equals(MarkerADU.delete)) {
    s.delete(entity);
    } else if (m.equals(MarkerADU.update)) {
    s.update(entity);
    }
    tx.commit();
    return true;
    } catch (HibernateException e) {
    tx.rollback();
    e.printStackTrace();
    return false;
    }finally{
    HibernateUtil.closeSession();
    }
    }
    大家请多多帮忙一下,也让遇到这个问题的伙伴们学习学习