Hibernate无法将对象正确保存在数据库中(?,?,?,?) [英] Hibernate not correctly saving an Object in the db (?, ?, ?, ?)
问题描述
根据此问题进行. (我正在使用Hibernate 4.)
Following from this question. (I'm using Hibernate 4.)
如我在尝试使用FeedbackDto-Feedback方法的答案之一中所建议的.
As suggested in one of the answers I tried using the FeedbackDto-Feedback approach.
在我的RequestsController.java
内部,我有这个:
Inside my RequestsController.java
I have this:
@PostMapping("/feedback")
public void postFeedback(@RequestBody FeedbackDto feedbackDto) {
Feedback feedback = new Feedback(new Product(feedbackDto.getProductId()), feedbackDto.getScore(), feedbackDto.isPreferred(), feedbackDto.getTextNote());
Session session = HibernateUtil.getSessionFactory().openSession();
session.save(feedback);
session.flush();
session.close();
}
如果我尝试打印feedback
和feedbackDto
的内容,我会得到预期的结果,但是运行save()
和flush()
时,我没有在数据库中插入任何数据.为什么?
If I try to print the content of feedback
and feedbackDto
I get what I was expecting, but running save()
and flush()
I get no data inserted in the database. Why?
休眠的输出:
Hibernate:
insert
into
feedback
(preferred, score, textnote, product)
values
(?, ?, ?, ?)
这是我用来创建反馈表的create语句:
Here's the create statement I used to create the feedback table:
CREATE TABLE feedback(
product INTEGER PRIMARY KEY,
score NUMERIC,
preferred INTEGER,
textnote VARCHAR(255),
FOREIGN KEY(product) REFERENCES product(id)
)
推荐答案
您的代码存在问题是产品构造函数的调用:
The problem with your code is the call of the product constructor:
new Product(feedbackDto.getProductId())
您应该首先从数据库中获取产品对象(如果不存在并且产品ID足以创建它,则创建它).
You should first fecth the product object from the database (or create it if doesn't exists and the product's id is enough to create it).
另一个问题是您的数据库表示形式.您应该为反馈表主键使用整数ID,并有另一个字段来记录外键.比混合ID和外键是更好的方法.
Another problem is in your database representation. You should use an integer ID for your feedback table primary key and have another field to record the foreign key. It is a better approach than mixing ID and foreign key.
所以应该是这样的:
CREATE TABLE feedback(
feedbackid INTEGER PRIMARY KEY,
score NUMERIC,
preferred INTEGER,
textnote VARCHAR(255),
productid INTEGER
FOREIGN KEY(productid) REFERENCES product(id)
)
然后您的方法应如下所示:
And then your method should be like this :
@PostMapping("/feedback")
public void postFeedback(@RequestBody FeedbackDto feedbackDto) {
// I assume you have a field productDao in your class
Product product = productDao.findById(feedbackDto.getProductId());
if (product != null) {
// Assuming the product should exists
Feedback feedback = new Feedback(feedbackDto.getProductId()), feedbackDto.getScore(), feedbackDto.isPreferred(), feedbackDto.getTextNote(), product);
Session session = HibernateUtil.getSessionFactory().openSession();
session.save(feedback);
session.flush();
session.close();
} else {
// return an error code
}
}
这篇关于Hibernate无法将对象正确保存在数据库中(?,?,?,?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!