简体   繁体   中英

Is it possible to create 2 children in a joined inheritance with Spring jpa?

I'm trying to create several children linked with the same parent.

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "USER")
public class User implements Serializable {

    @Id
    @Column(name = "ID_USER")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idUser;

    @Column
    private String email;


@Entity
@Table(name = "PRODUCT_OWNER")
@PrimaryKeyJoinColumn(name = "ID_PRODUCT_OWNER")
public class ProductOwner extends User{

}


@Entity
@Table(name = "SCRUM_MASTER")
@PrimaryKeyJoinColumn(name = "ID_SCRUM_MASTER")
public class ScrumMaster extends User{

    
}

@Entity
@PrimaryKeyJoinColumn(name = "ID_DEVELOPER")
@Table(name = "DEVELOPER")
public class Developer extends User{
            
}

How can I create a Developer and ScrumMaster with the same User ID?

dev = new Developer();
devRegistro.setIdMiembro(new Long("1"));
devRegistro.setEmail("user@email.com");

po = new ProducOwner();
po.setIdMiembro(new Long("1"));
po.setEmail("user@email.com");

developerService.saveOrUpdate(dev);
productOwnerService.saveOrUpdate(po);

It fails because in the second transaction already exists the user with ID=1.

All the examples I see in internet can't be part of two children as Animal (cat or dog), Vehicle (car or motocycle).

The short answer to your question: with your current class hierarchy it is not possible to do the save both types of children, that's why you get the exception.

So reading your code with the class hierarchy, these are the informations you pass:

  • ProductOwner is a User
  • ScrumMaster is a User
  • Developer is a User

Then, consider that joined inheritance strategy works in JPA by having one table per class with only subclasses' columns, same primary key (and sometimes discriminator column and value). This means that each saveOrUpdate will create a record in each of the tables in the class hierarcy of the entity type, each with the same primary key. So developerService.saveOrUpdate(dev); will trigger an insert in the User table and one in the Developer table. Then comes productOwnerService.saveOrUpdate(po); attempting to do the insert in the User table with a primary key that is present already thus violating the uniqueness constraint of your DB and resulting in your JPA exception.

This looks somewhat similar to the diamond problem ... Maybe redesign your classes to favor composition over inheritance: User has DeveloperAttributes and User has ProductOwnerAttributes and User has ScrumMasterAttributes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM