Hibernate: saving an entity with foreign primary key

I have a database with two entities (Product and Feedback). Feedback has a single foreign key that refers to Product, whose primary key is an integer. They are therefore in a one-to-one relationship.

I want to add a new Feedback entry to the database with my web application. To do so I'm trying to perform a PUT request to my Spring server from my Angular client application.

The client has an Object of class Feedback with the following attributes (content of Feedback.ts)

export class Feedback {
    public productId: number,
    public score: number,
    public preferred: boolean,
    public textNote: string
  ) {

The class Feedback.java, server side:

@Table(name = "feedback")
public class Feedback implements Serializable {
    @JoinColumn(name = "product", unique = true)
    @OneToOne(cascade = CascadeType.ALL)
    private Product product;

    @Column(name = "score")
    private double score;

    @Column(name = "preferred")
    private boolean preferred;

    @Column(name = "textnote")
    private String textNote;

    // ... getters, setters, constructor


As you can see there is a non-matching attribute: productId is a number, while product is of class Product. How can I give the Spring application the correct object in order to save it in the database?

I'm trying to follow the Hibernate guidelines and as far as I understood it would be a bad practice to use an attribute in the java class of type int instead of Product. What should I do?

You create a new Product with the productId from the FE. Now you can create a new Feedback object with all types set. This you can then store in the database.


Usually, you have data transfer object (DTO)in the backend. Those will as the name suggests transport data do nothing else. Endpoints in the backend will always get DTOs which are the same as in the FE. In your case create a FeedbackDto.

public class FeedbackDto {
   Long productId;
   Double score;
   Boolean preferred;
   String textNote;

The Endpoint will receive this Object which has the same fields as the Feedback from the FE. Spring will create and fill you the object from the values in the JSON body of the request

From the FeedbackDto you create now a Feedback entity:

new Feedback(new Product(feedbackDto.productId), feedbackDto.score, feedbackDto.preferred, feedbackDto.textNote)

Now you can save this Feedback entity into your database.

Cascading save Entity objects with Foreign Key as a part of , And as a part of this primary key I have also foreign key to another entity. Why are you mixing jpa and hibernate annotations ? jpa annotations alone should be enough. Try with @Entity @Table(name = "question_completion") public class � You can then use the primary key to load the entity, and Hibernate sets the primary key value automatically. And if you want to persist a new entity, you need to set the primary key value programmatically. But with JPA and Hibernate you can do much more than that. You can: choose between different strategies to generate unique primary key values,

I had a similar issue as you had, and this blog post helped me solve it: https://www.baeldung.com/spring-data-rest-relationships. This works very well if you are also using the Spring Data REST, but I think you can adapt it to your usage.

Basically, after you create your Feedback entry (with an initial POST request), you should perform another PUT request to associate the Feedback entry to your Product. For your example, you could have something like:

curl -i -X PUT 
 -d "http://localhost:8080/feedback/1" 
 -H "Content-Type:text/uri-list" http://localhost:8080/product/1/feedbackProduct

Hibernate Foreign Key Example, Then check out our detailed example on Hibernate Foreign Key! You can also download 2 – By Saving Collections using @ElementCollection. In this article we will 2 – Data type of Primary key defined within Entity class. Always use singular names for entities. It's Book, not Books; and Author, not Authors.. Always get the ID. Get the surrogate key, not the business key, from the UI. You can use Session.load to set up foreign key relations without querying the DB.

You can extend a DefaultConversionService and implement a custom converter to convert id to product

 public static class Config {
   public ConversionService conversionService () {
      DefaultConversionService service = new DefaultConversionService();
      service.addConverter(new IdToProductConverter());
      return service;

Then the IdToProductConverter will receive the id and can lookup the product from the DB

class IdToProductConverter implements Converter<String, Product> {
    public Product convert(String source) {

Hibernate One-to-One Mapping with Foreign Key Annotations , This is similar to the tutorial Hibernate One-to-One With Foreign Key XML Mapping The following diagram recalls the one-to-one entity relationship: @ Id and @GeneratedValue: are used in conjunction for a field that maps to the primary key. Hibernate: insert into AUTHOR (email, name) values (?, ?) Actually, it is default Hibernate behavior to only load the foreign key instead of the message object if the FetchType is LAZY. This is why there are proxies to the objects to be loaded when you specify LAZY FetchType. The foreign key is not visible directly, but it is of course the key of the object at the "one" end of the OneToMany relationship.

Chapter 39. Mapping One-to-Many/Many-to-One Bi-directional , The foreign key from the child entity table to the parent entity table is correct. date, checkout date not null, BORROWER_ID integer not null, primary key (id) ); .. . alter table testOneToManyBiFK *** -persisting borrower Hibernate: insert into � Then I save/persist/merge "ne" in the usual way. Note, don't try and set any other property of your foreign object (AnotherObject) except its primary key field and Hibernate won't try and persist it to the DB. HTH, Rob Hills[/code]

Hibernate Community • View topic, I am creating a POJO from a flat file which has a foreign-key relation with its primary key field and Hibernate won't try and persist it to the DB. In JPA, we use the @Id annotation to designate a field to be the table's primary key. The primary key is required to be a Java primitive type, a primitive wrapper, such as Integer or Long , a

Mapping Java Entities for Persistence With Hibernate (Part 4), PERSIST). protected Address address; } @Entity. public class Address { By default, Hibernate generates and uses a foreign key column to There are two foreign keys in the join table, each referencing the primary tables. PrimaryKeyJoinColumn indicates that the primary key of the Student entity is used as a foreign key to the Address entity.Together these two annotation indicates that both the source and target share the same primary key values.Also note the use of cascade = CascadeType.ALL.Since Address entity can not exist without Student entity, with this

  • Why product field in Java class has @Id annotation? Do you really want to use Product instance as ID for Feedback?
  • The entity Feedback has only one key: the foreign key that references to the product. The point is I want to store in Feedback some information that refers one-to-one to the product. I may simply expand the attributes of the Product entity, but as the information in Feedback is really rare I don't want hundreds of empty cells in my database. :) I hope given those considerations you will agree that I put @Id in the correct place (unless I'm missing some point on Hibernate)
  • So I should define also a class Product in typescript and use it as the data type of the product attribute in Feedback class? In BE Spring will automatically understand what to do if I do so?
  • No not really I would let the front end part be as it is and change the backend a bit. I will edit my answer
  • Thank you, I just did as you suggested but when I do the save() and subsequent flush() I get nothing in the database :( . I tried to print what's inside the feedback and feedbackDto objects and I get what I was expecting, but when I run save() I get the following from Hibernate: Hibernate: insert into feedback (preferred, score, textnote, product) values (?, ?, ?, ?)
  • I asked another question referring to this problem in more detail: stackoverflow.com/questions/60227870/…