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 {
  constructor(
    public productId: number,
    public score: number,
    public preferred: boolean,
    public textNote: string
  ) {
  }
}

The class Feedback.java, server side:

@Entity
@Table(name = "feedback")
public class Feedback implements Serializable {
    @Id
    @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.

[Edit]

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

 @Configuration
 public static class Config {
   @Bean
   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> {
    @Override
    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