首页 > 解决方案 > 如果在尝试将对象保存在数据库中时由休眠生成 SQL 语法错误,如何解决?

问题描述

我正在尝试使用休眠中的 session.save() 方法保存对象。到目前为止,其他类的一切都运行良好,但现在我遇到了这个 SQL 语法错误,到目前为止我发现没有任何帮助。这是控制台结果:

Error update: could not execute statement
May 23, 2019 5:47:26 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option (is_answer, question_id, option_text) values (0, 97, 'asdfaoins')' at line 1

这是我的 QuestionDAO 类中的方法:

@Transactional
    public void addQuestionOption(String text, int questionId, boolean isAnswer) {

    QuestionOption newOption = new QuestionOption();

    newOption.setText(text);
    newOption.setQuestionId(questionId);
    newOption.setIsAnswer(isAnswer);

    Configuration con = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(QuestionOption.class);

    SessionFactory sf = con.buildSessionFactory();
    Session session = sf.openSession();

    try {

        Transaction tx = session.beginTransaction();

        session.save(newOption);

        tx.commit();
    } catch (Exception e) {
        System.out.println("Error update: " + e.getMessage());
        session.getTransaction().rollback(); // get
    } finally {
        session.close();
    }

这是我的 QuestionOption 模型类:

@Entity
@Table(name = "option")
public class QuestionOption {


@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "option_text")
private String text;

@Column(name = "question_id")
private int questionId;

@Column(name = "is_answer")
private boolean isCorrectAnswer;



public QuestionOption(int id, String text, int questionId, boolean isAnswer) {
    super();
    this.id = id;
    this.text = text;
    this.questionId = questionId;
    this.isCorrectAnswer = isAnswer;
}

public QuestionOption() {}

//getters & setters

我接到的电话就这么简单:

 QuestionOptionDAO odao = new QuestionOptionDAO();
     odao.addQuestionOption("asdfaoins", 97, false);

我提到如果我只是硬编码一些条目,我可以毫无问题地插入工作台。我也试过这个saveOrUpdate()方法。此外,我对其他类使用完全相同的方法,并且插入工作完美。知道为什么在这种情况下我会收到此错误吗?

标签: javamysqlhibernate

解决方案


这可能是因为option是 MySQL 中的保留字...

https://dev.mysql.com/doc/refman/5.5/en/keywords.html#keywords-5-5-detailed-O

试着给你的桌子打电话或者试试这里的建议......

https://thoughts-on-java.org/hibernate-tips-escape-table-column-names/

例如

@Entity
@Table("\"Option\"")
public class QuestionOption {
   ...

推荐阅读