简体   繁体   中英

Posting just the id of unidirectional many to one relationship

I am submitting a POST request (JSON) to create a new instance of a Person and each Person has to have a Status associated with them. There is a prepopulated Status table that has a limited number of statuses. Is just submitting the entity id of the status the best approach here?

Currently, I submit just the id of the Status entity in my request, but this means loading a Status from the DB using the id and adding it to the transient Person before it's persisted beforehand to satisfy the JPA/DB constraints, but this is inefficient.

Request body (truncated for brevity) unmarshalled to PersonDTO:

{
    "name" : "Dave",
    "statusId" : "1",
    ::
}

Status entity

@Entity
public class Status {

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

    @Column
    private String status;
}

Person entity

@Entity
public class Person {

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

    @ManyToOne(optional = false)
    @JoinColumn(name = "status_id")
    private Status status;
    ::

Is the best approach actually submitting the status object in the JSON request so I don't have to perform any sort of lookup on the status id?

{
    "name" : "Dave",
    "status" : {
      "id" : 1
      "status" : "AVAILABLE"
    },
    ::
}

I appreciate that I can preload the statuses at startup into a singleton so they are accessible or cache a service class method that returns a status using the id, but I am wondering what the best approach is here because if I was using native SQL I could just insert the Person into the database with a status id and not perform any lookup of the status beforehand.

1) Once you start using Native SQL, you will start using it in more and more places. Eventually, you will lose the database provider independence that JPA gives you. I am not saying it is 100% bad, I am just saying..

2) You can apply the second-level-cache for the Status as it seems to be a sort of dictionary table:

@Entity
@Cacheable

3) If you are not expecting to make any changes to the status object itself, you should load it not using the findById , which goes to the database, but use the getOne instead which only creates a reference and should be sufficient in your case.

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