java - 如果在尝试将对象保存在数据库中时由休眠生成 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()
方法。此外,我对其他类使用完全相同的方法,并且插入工作完美。知道为什么在这种情况下我会收到此错误吗?
解决方案
这可能是因为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 {
...
推荐阅读
- r - 在 R 中计算标准偏差时忽略 NA 值
- java - Java JTable 在高分辨率屏幕上打印太小
- scala - 如何从数据框中子集数据框
- react-native - 反应本机版本构建是否使用捆绑器?
- notepad++ - 每组 3 个十进制数字的 NOTEPAD++ 换行符
- c++ - 如何使用 ffmpeg 将 3840 nb_samples 编码为要求 1024 的编解码器
- java - 匹配模板的 OpenCV 坐标
- powershell - 尝试在 Powershell 中运行“C:\Program Files\VERITAS\NetBackup\bin\bpdown.exe”-f -v
- angularjs - 如何解决 Angular $timeout 中的承诺
- ios - iPad youtube iframe embed pwa 在 youtube 应用程序中打开?