在我的Spring项目中,我想根据url更新mysql表字段:
我的网址如下:
localhost:9191/access/name/article?key=xyz
我想从url中获取文章,然后更新相应的mysql表的状态和文章字段
在我的数据库中,我有表名“user”。
user(stu_id,name,email,article,status)
mysql查询是:
UPDATE user
SET article='null', status=true
WHERE article='xyz'; here xyz=user.getArticle()
为实现这一点,我已经完成了以下
User.java是:
public User(String article, String status) {
super();
this.article = article;
this.status = status;
}
UserDao.java
public interface UserDao {
public void updateUser(User user);
}
UserDaoImpl.java是:
@Transactional
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
public void updateUser(User user) {
String hql = "update user set article = null,status=true"
+"where article=:key1";
sessionFactory.getCurrentSession().createQuery(hql)
.setParameter("key1", user.getArticle());
}
}
UserService.java是:
public interface UserService {
User updateUser(String article, String status);
}
UserServiceImpl.java是:
@Service("userService")
@Transactional(propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements UserService {
public User updateUser(String article, String status) {
User user = new User(article,status);
userDao.updateUser(user);
return user;
return user;
}
UserController.java是:
//localhost:9191/access/name/article?key=xyz
@RequestMapping(value="/access/name/id", method=RequestMethod.GET)
public @ResponseBody String byParameter( User user, HttpServletRequest request) {
boolean ps=true;
String foo= request.getParameter("key");
userService.updateUserinfo(foo, ps);
return "signupLogin";
}
但显示错误:
ERROR [] (ErrorCounter.java:56) - line 1:51: unexpected token: key
ERROR [] (ErrorCounter.java:56) - line 1:58: unexpected token: =
java.lang.IllegalArgumentException:要遍历的节点不能为空!
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1760)
at com.student.dao.UserDaoImpl.updateUser(UserDaoImpl.java:40)
at com.student.service.UserServiceImpl.updateUserinfo(UserServiceImpl.java:66)
问题出在哪里?我做错了什么?
答案 0 :(得分:1)
对sql查询进行以下更正,使用User
代替user
进行查询。
String hql = "update User set article = null, status = true where article = :key1";
如果您不想更改此方法,则可以使用createSqlQuery
方法代替createQuery
方法。
这个解决方案可能有所帮助。
答案 1 :(得分:1)
at com.student.dao.UserDaoImpl.updateUser(UserDaoImpl.java:40)
您正在执行错误的查询。您应该执行以下代码:
@Transactional
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
public void updateUser(User user) {
String hql = "update user set article = null,status=true"
+"where article=:key1";
sessionFactory.getCurrentSession().createSQLQuery(hql)
.setParameter("key1", user.getArticle());
}
}
语法如下: 其中用户(这是数据库表)和文章,状态是字段