从别处copy过来的,和我的错一样
下面是他的解决方案:
简单来说,就是parent和id类型不匹配。但是从错误的堆栈上面,很难看出是这样的错误。主要是经过hibernate封装。抛出是org.hibernate.PropertyAccessException: IllegalArgumentException错误,也就是说本来预期是某某类型,结果发现传入的不是某某类型。但是在写代码的时候编译器并不能捕捉到此错误。因为:
后面是一个object,只会程序运行时才能够做这样的检查。也许它应该抛出这样的错。castclass错误,或者说预期什么参数,结果得到什么参数。这样在定位错误的时候就会更加容易一些。
java 代码
- I have a basic model called "Group" which has a name, a reference to its parent (which is also a Group) and a collection of its children (which are Groups). I've defined the hibernate mapping like so:
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- public Long getId()
- {
- return id;
- }
- @ManyToOne
- @JoinColumn(name="group_fk", nullable=true, insertable=false, updatable=false)
- public Group getParent()
- {
- return parent;
- }
- @OneToMany(cascade = {CascadeType.ALL}, fetch=FetchType.LAZY)
- @JoinColumn(name="group_fk")
- public Collection<Group> getChildren()
- {
- return children;
- }
- When I try to save a Group using my DAO I get the following exception:
- org.springframework.orm.hibernate3.HibernateSystemException: IllegalArgumentException occurred calling getter of com.trace.model.Group.id; nested exception is org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.trace.model.Group.id
- Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.trace.model.Group.id
- at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:171)
- ....
- ....
- ....
- Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
- at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
- at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
- at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
- at java.lang.reflect.Method.invoke(Method.java:597)
- at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:145)
- Any help or hints would be greatly appreciated. Thanks in advance.
java 代码
- Alright, I figured it out. I can't believe I wasted hours on this.
- The issue was that my DAO had a method called getChildren( Long ) which took an ID of a group and would return the children of the group with that ID. The code was:
- DetachedCriteria crit = DetachedCriteria.forClass( Group.class );
- crit.add( Restrictions.eq( "parent", id ) );
- The getParent() method of Group returns a Group but I was attempting to compare it against a Long.
java 代码
- SimpleExpression org.hibernate.criterion.Restrictions.eq(String propertyName, Object value)