这是我第一次使用SpringMVC + Hibernate,如果我问一个菜鸟问题,请原谅我。
我想要实现的是搜索属于某些用户的 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)
有谁能弄清楚为什么会这样? 提前谢谢!
答案 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))