hibernate inheritance save child after parent

Viewed 383

I'm using Joined Hibernate Inheritance Mapping in my entity stucture in this way:

@Getter
@Setter
@Entity
@Table(name= "app_user")
@Inheritance(strategy = InheritanceType.JOINED)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    //some other fields
}



@Getter
@Setter
@Entity
@Table(name= "app_customer")
public class Customer extends User {
    //some other fields
}

I want to to save a user first, and after a while save a customer in another api and map that customer to first user. So I try to save a new customer with existing user id in this way:

User user = ... //find already saved user
Customer customer = new Customer();
customer.setId(user.getId());
...
customerRepository.save()

But, hibernate generates customer with new generated id(rather than fixed passed id) and also generates a new user. Here is my question: How can I save a child after its parent? or Is there anyway to save child without saving parent again?

1 Answers

Try to change second entity:

@Getter
@Setter
@Entity
@Table(name= "app_customer")
public class Customer{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @OneToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    User user;

    //some other fields
}
Related