Home > Blockchain >  JPA reusable entity and relationship
JPA reusable entity and relationship

Time:06-06

I am trying to build an app with Spring Boot and PostgreSQL where I want to store a Game entity.

The Game has a Setting which has many variation but still limited. I think its worth storing as separate Entity and reuse it for games with the same setting.

@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Game {

    @Id
    @GeneratedValue
    @Type(type = "pg-uuid")
    private UUID id;
    private Setting setting;
    // etc, players and game result related stuff
}
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Setting {

    @Id
    @GeneratedValue
    @Type(type = "pg-uuid")
    private UUID id;
    private String format;
    // etc, other customizable settings
}

Want I would like to achive is

  • To create the Setting entity only if it does not exist. What is the best way to do this validation?
  • To setup the right relationship between the Game and Setting. One Setting entity can belong to any number of Game but one Game can only have one Setting.

Thank you

CodePudding user response:

  1. To create the Setting entity only if it does not exist. What is the best way to do this validation?

Adding a new row to your Setting table only if it does not exist needs more specification

  • You could take this literally and once you get a Setting in a request check your whole Setting table for one that matches all of the values of the Setting that you received, if it exists OK, if it does not exist you save a new one.
  • However, since you said the settings are limited I would suggest presenting the user with a list of available settings and letting them pick one of those, and having an option to add a new setting if they wish so. If you really want to validate if an exact match to that setting does not exist already, then you can do your validation at this point as well.
  1. To setup the right relationship between the Game and Setting. One Setting entity can belong to any number of Game but one Game can only have one Setting.
  • This simply requires you to have a setting foreign key in your Game table

Your Game entity class would look like this:

@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Game {

    @Id
    @GeneratedValue
    @Type(type = "pg-uuid")
    private UUID id;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="setting_id")
    private Setting setting;
    // etc, players and game result related stuff
}
  • Related