Home > Back-end >  Hibernate error: ids for this class must be manually assigned before calling save()
Hibernate error: ids for this class must be manually assigned before calling save()

Time:04-03

I am new to hibernate and spring in general. And trying to create a food delivery application. I've two classes as below Restaurant and CustomerOrder mapped with oneToOne Association.

CustomerOrder.java

@Entity
@Table
@Getter
@Setter
public class CustomerOrder {

    @Id
    Long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "restaurant_id", nullable = false)
    Restaurant restaurant;
}

Restaurant.java

@Entity
@Table
@Getter
@Setter
public class Restaurant {

    @Id
    Long id;
    String name;
    String address;
    
    @OneToOne(mappedBy = "restaurant")
    CustomerOrder customerOrder;
}

i have pre populated postgres database. I am using import.sql for it, which loads the values in the database at the boot time of the app.

import.sql

insert into customer("id", "location", "name") values (1, 'cg road', 'kunal');
insert into customer("id", "location", "name") values (2, 'delux avenue', 'tirth');
insert into customer("id", "location", "name") values (3, 'sp road', 'parth');

insert into restaurant("id", "address", "name") values(1, 'divine circle', 'grand thaker');
insert into restaurant("id", "address", "name") values(2, 'alpha mall', 'honest');
insert into restaurant("id", "address", "name") values(3, 'acropolish mall', 'starbucks');

application.properties

spring.datasource.url=jdbc:postgresql://localhost:5432/zomato1?createDatabaseIfNotExist=true
spring.datasource.username=
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true

when i do the post request to create the new entry for CustomerOrder with the body

{
"id" : 1,
"restaurant_id" : 2
}

I am getting the above error.

CodePudding user response:

maybe you should add @GeneratedValue(strategy = GenerationType.IDENTITY) to your both classes

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

maybe this Hibernate: ids for this class must be manually assigned before calling save() can also help

CodePudding user response:

Although hkmaarouf's answer would fix the problem, It will only apply in case the responsibility of generating the ID is given to the database.

The other approach is to generate the ids before the entities are persisted. The following example shows one way of doing it for one of your entities:

CustomerOrder customerOrder = ...; // Obtain an instance of your entity
customerOrder.setId(getNextId()); // getNextId() returns the potencial entity ID
customerOrderRepository.save(customerOrder);
  • Related