I have 2 classes
@Entity
public class User implements Serializable {
@Id
@Column(name = "user_id")
private String id;
@Column(name = "name")
private String name;
@Column(name = "age")
private String age;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private List<Address> addresses= new ArrayList<>();
}
@Entity
public class Address implements Serializable {
@Id
@Column(name = "address_id")
private String id;
@Column(name = "actualAddress")
private String actualAddress;
@Column(name = "code")
private String code;
@Column(name = "country")
private String country;
}
I need to get a list of User that has a list of Address in each user. The problem is if I do the sql like this:
@Query("select u from User where u.id = :userId")
List<User> getUserAndAddress(@Param("userId") String userId);
Hibernate will get all of Address fields because of the onetomany relationship, any idea how to write sql query to get the user list that only contain the Addresses that have id and code? I am using JPA and postgres. Thank you the net!
To query specific columns in a one-to-many relationship using Spring Data JPA, you typically fetch the parent entity and then navigate through its collection of child entities.
Let's assume you have two entities: Parent and Child, where Parent has a one-to-many relationship with Child.
Using JPQL
Using Query Methods