skinnybrit51
skinnybrit51

Reputation: 4927

is it possible to stop joins in jpa?

I have joins defined in my entity class. When I do a query the join entities come back also.

Is it possible to stop these joins or will they always occur? In some instances I would like to stop them occurring so that I dont transfer unnecessary associated entities in my transfer objects. Or is the practice to strip out what you only need for transfer object?

Thanks

Upvotes: 2

Views: 415

Answers (3)

Selvasuriya Nadar
Selvasuriya Nadar

Reputation: 41

You can use the @JsonIgnore annotation to ignore the field from being serialized by Jackson which spring uses internally.

Upvotes: 0

Bagira
Bagira

Reputation: 2243

Better approach would be you create a new Transfer Object and get that from the Database. So, for Eg: If you have Person class and you need some of its properties to transfer, consider doing following

Original Person class will look some thing like

Class Person {
    private String firstName;
    private String lastName;
    Private Set<User> users
}

Create a new Class which will be your Transfer Object, assuming you only need to transfer some of the properties of person class.

Class PersonDTO {
   private String firstName;
   private String lastName;

   public PersonDTO(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName; 
   }
}

Now you can write your query as

Select new PersonDTO(firstName, lastName) from Person p;

Note: Corresponding constructor in the PersonDTO is important.

Hope this helps.

Upvotes: 1

stzoannos
stzoannos

Reputation: 938

If you don't need to fetch all the join entities on every request, you may use lazy fetching. This fetch parameter can be added optionally to the annotations: @Basic, @OneToMany, @ManyToOne, @OneToOne, and @ManyToMany.

e.g. @ManyToOne(fetch = FetchType.LAZY)

By setting FetchType.LAZY you don't retrieve all those joined fields from the DB, until they are explicitly accessed.

Upvotes: 2

Related Questions