在做课设的时候:
出现异常:org.hibernate.PropertyAccessException: IllegalArgumentException,搞了好半天。原来是Restrictions.eq()中的第二个参数出问题了,下面是另一个人写的。和我的错误时一样的
看看Exception信息:
- org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.lssrc.pams.model.User.userId
- ......
- Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
- ......
我是用Criteria的方式,按用户查找任务信息。下面是我的代码:
User.java
- @Entity
- @Table(name = "pams_user")
- public class User extends BasePOJO {
- private static final long serialVersionUID = 1L;
- private String userId;
- private String userName;
- // getter, setter
- }
Task.java
- @Entity
- @Table(name = "pams_task")
- public class Task extends BasePOJO {
- private static final long serialVersionUID = 1L;
- private String taskId;
- private String taskEndTime;
- private User user;
- // getter, setter
- }
TaskDAOImpl.java
- @SuppressWarnings("unchecked")
- public List<Task> findByUser(User user, int beginIndex, int count) {
- try {
- session = getSessionFactory().getCurrentSession();
- transaction = session.beginTransaction();
- tasks = session.createCriteria(Task.class).add(Restrictions.eq("userId", user.getUserId())).list();
- transaction.commit();
- } catch (Exception e) {
- transaction.rollback();
- e.printStackTrace();
- return null;
- }
- return tasks;
- }
反复测试之后,其实是下面这句话的原因:
- tasks = session.createCriteria(Task.class).add(Restrictions.eq("userId", user.getUserId())).list();
原因在于Restrictions.eq("userId", user.getUserId())这个方法中,匹配的并不是像sql写的那样,某个字段等于某个值,在这里,而是要看Task.java中user对象的类型。因为在Task.java中user是User类型的,所以,这个地方并不需要getUserId()。要修改成:
- tasks = session.createCriteria(Task.class).add(Restrictions.eq("userId", user)).list();
修改之后,又会出现新的错误:
- org.hibernate.QueryException: could not resolve property: userId of: com.lssrc.pams.model.Task
这个问题,还是Restrictions.eq("userId", user)的问题,userId,应该改成user。因为在Task.java中,User对象的名字是user。再测试时,终于通过了。。。
Hibernate学的还是不够精细。做事还需谨慎认真。切记!