org.hibernate.QueryException:无法解析已定义列名的属性

时间:2016-05-13 08:26:18

标签: java mysql hibernate spring-mvc

这是我第一次使用SpringMVC + Hibernate,如果我问一个菜鸟问题,请原谅我。

数据库表的关系如下所示: Text in red color are my tables

我想要实现的是搜索属于某些用户 user_tasks 。所以在UserRepository的实现中我写了这个:

@Repository("userTaskRepo")
public class UserTaskRepoImpl extends AbstractDao<Integer, UserTask> implements UserTaskRepository {

    public List<UserTask> getByUserId(int userId, int startTaskId, int size) {
        List<UserTask> userTasks = getSession().createCriteria(UserTask.class)
                .add(Restrictions.eq("user_id", userId))
                .add(Restrictions.ge("task_id", startTaskId))
                .setMaxResults(size)
                .list();
        return userTasks;
    }
}

和相关的 UserTask 类定义如下:

@Entity
@Table(name = "usertask")
public class UserTask {
    //public enum TaskState {CLAIMED, FINISHED, EXPIRED};
    public static int TYPE_CLAIMED = 0;
    public static int TYPE_FINISHED = 1;
    public static int TYPE_EXPIRED = 2;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(name = "task_id", nullable = false)
    private Integer taskId;

    @Column(name = "curr_usermicrotask_id")
    private Integer currUserMicrotaskId;

    @Column(name = "state", nullable = false)
    private Integer state;

    //...some getters and setters
}

此外,我还定义了用户任务的类。

但是,当我尝试在UserTaskRepoImpl中调用该函数时发生错误 例外

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.QueryException: could not resolve property: user_id of: edu.inlab.models.UserTask
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

有谁能弄清楚为什么会这样? 提前谢谢!

1 个答案:

答案 0 :(得分:3)

好的,我自己想通了。 这是因为我把SQL列名(在@Column中定义)与HQL列名混淆了。 代码

.add(Restrictions.eq("user_id", userId))
.add(Restrictions.ge("task_id", startTaskId))

应改为

.add(Restrictions.eq("userId", userId))
.add(Restrictions.ge("userId", startTaskId))