1

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)

2
  • The school you 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. Commented Mar 30, 2020 at 9:41
  • check this out stackoverflow.com/questions/21233853/… Commented Mar 30, 2020 at 9:49

2 Answers 2

2

use below annotation on entity class

@SelectBeforeUpdate(value=false) 
Sign up to request clarification or add additional context in comments.

1 Comment

on which entity class? User or School?
1

You need to use getReference method to avoid this issue

School school = entityManager.getReference(School.class, 2); 

If you are using Spring Data JPA, this method is exposed as getOne on the repository.

See How do find and getReference EntityManager methods work when using JPA and Hibernate

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.