I have a Entity Student which is @ManyToOne with another Entity School, Where School is pre-existing in the database and is fixed.
Entity User:
@Data @Entity(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(nullable = false) private String username; @ManyToOne private School school; } Entity School:
@Data @Entity(name = "school") public class School { @Id @Column(unique = true, nullable = false) private int id; @Column(nullable = false) private String name; private String shorten; @JsonProperty(value = "logo_url") private String logoUrl; private float longitude; private float latitude; @Column(nullable = false) private boolean opened; } When adding a user, I POST the following json from Postman:
{ "username": "abcd", "school_id": 2 } Then,
School school = new School(); school.setId(2); //"school_id" above User user = new User(); user.setUsername("abcd"); user.setSchool(school); userRepository.save(user); Because I think that to add a new user, only the School id is enough, and no other School parameters are required. But every time I run, it will run the select statement to select all fields of School by id before save().
My question is: how to remove this unnecessary operation so that before the save(), there is no need to select? (I know that custom sql statements can be implemented, but I feel like this will break the object orientation of JPA)
schoolyou created is not known to the entity manager, so it first has to select it from the table so that it can link it to the user.