gpt4 book ai didi

java - 如果在尝试将对象保存在数据库中时由 hibernate 生成 SQL 语法错误,如何解决?

转载 作者:行者123 更新时间:2023-11-29 07:21:14 25 4
gpt4 key购买 nike

我正在尝试使用 hibernate 中的 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() 方法。此外,我对其他类使用完全相同的方法,并且插入工作完美。知道为什么在这种情况下会出现此错误吗?

最佳答案

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

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

尝试将您的 table 命名为其他名称或尝试此处建议的...

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

例如

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

关于java - 如果在尝试将对象保存在数据库中时由 hibernate 生成 SQL 语法错误,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56273844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com