【问题标题】:org.springframework.orm.hibernate4.HibernateQueryException with Query (Spring mvc)org.springframework.orm.hibernate4.HibernateQueryException with Query (Spring mvc)
【发布时间】:2016-02-27 03:12:45
【问题描述】:

我有一个查询。 (这是我完整的 DAO 方法)

@Override
public void addUserRole(UserRole userRole) {
    Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
    String query = "insert into 'user_roles'('role','username') values(%s,%s)"; 
    Session session = this.sessionFactory.getCurrentSession();
    List roleAdd = session.createQuery(String.format(query, "'ROLE_USER'", "'acid'")).list();

    tx.commit();

}

它给了我一个例外

type Exception report message Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateQueryException: expecting IDENT, found ''user_roles'' near line 1, column 13 

[insert into 'user_roles'('role','username') values('ROLE_USER','acid')]; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT, found ''user_roles'' near line 1, column 13 

[insert into 'user_roles'('role','username') values('ROLE_USER','acid')] description The server encountered an internal error that prevented it from fulfilling this request.

【问题讨论】:

  • 这段代码不应该编译。我认为您在某处犯了复制粘贴错误?您定义了变量“查询”两次。
  • @mhlz,哦!非常感谢! Query query = sessionFactory.getCurrentSession().createSQLQuery("insert into spring_social_db.user_roles(role,username) - 这个字符串不能在这里!
  • 尝试去掉表名的单引号。
  • @bcholmes,感谢您的回答!但这无济于事
  • 代码变了,看起来String query = 开头的那行已经不适用了。现在有不同的异常消息吗?

标签: java mysql spring hibernate spring-mvc


【解决方案1】:

你的方法应该是这样的:

@Override
public void addUserRole(UserRole userRole) {
    Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
    String query = "insert into 'user_roles'('role','username') values(%s,%s)"; 
    Session session = this.sessionFactory.getCurrentSession();
    int resultCount = session.createSQLQuery(String.format(query, "'ROLE_USER'", "'acid'")).executeUpdate();

    tx.commit();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-21
    • 2018-03-29
    • 2014-11-27
    • 2015-11-11
    • 2019-02-08
    • 2020-02-22
    • 2021-03-05
    • 1970-01-01
    相关资源
    最近更新 更多