Hibernate not correctly saving an Object in the db (?, ?, ?, ?)

那年仲夏 提交于 2020-03-25 13:44:14

问题


Following from this question. (I'm using Hibernate 4.)

As suggested in one of the answers I tried using the FeedbackDto-Feedback approach.

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();
}

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?

Output from hibernate:

Hibernate: 
    insert 
    into
        feedback
        (preferred, score, textnote, product) 
    values
        (?, ?, ?, ?)

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)
)

回答1:


The problem with your code is the call of the product constructor:

new Product(feedbackDto.getProductId())

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).

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.

So this should be something like this :

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
     }
}


来源:https://stackoverflow.com/questions/60227870/hibernate-not-correctly-saving-an-object-in-the-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!