0

I'm writing a service with JPA and Postgres db. I have a class named Student:

public class Student {
    @id
    private String id;

    private String firstName;
    private String lastName;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "student_phone", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "phone_id"))
    private Set<Phone>;

    // Setter and Getter
}

And a Phone class:

public class Phone {
    @id
    private String id;

    private String number;

    // Setter and Getter
}

Now there will be three tables in my db, following are columns in them:

  • student: id, first_name, last_name
  • phone: id, number
  • student_phone: student_id, phone_id

Now every time I query a student from the db, the result contains the corresponding phones. Can I just get the content in student table? Some times I don't want to extend the phone information of a student.

Cong Wang
  • 769
  • 1
  • 9
  • 30

2 Answers2

0

Use lazy loading

 @OneToMany(fetch=FetchType.LAZY,

or

write native queries

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

@OneToMany is default lazy fetch

I assume that you use REST service then:

try this if you use XML in JAXB with @XmlTransient:

@XmlTransient
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "student_phone", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "phone_id"))
private Set<Phone>;

or if you use json you can add this @JsonIgnore

Piotr Rogowski
  • 3,642
  • 19
  • 24
  • Hi Abihabi87, I don't want to use @JsonIgnor because: 1. Sometime I don't want to show phone info bu sometime I want. 2. As I know when I add this annotation, the phone info is still quired from db, but just be ignored by spring-boot. Is it possible that do not retrieve it from db, which could improve the performance. – Cong Wang Jun 02 '17 at 08:55