Issue
Trying to get value from 2 joined tables with getter, have 2 models Customer
and Address
.
@Setter
@Getter
@Data
@Entity
@Accessors(chain = true)
@Table(name = "customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "phoneNumber")
private String phoneNumber;
@Column(name = "address")
private String address;
}
@Setter
@Getter
@Data
@Entity
@Accessors(chain = true)
@Table(name = "address")
public class Address implements Serializable {
@Id
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "address")
private String address;
@Column(name = "zipcode")
private String zipcode;
@Column(name = "number")
private Integer number;
@ManyToOne
@JoinColumn(name="customer")//
private Customer customerBean;
}
Address Repository with this query :
@Query( value = "SELECT ad FROM Address ad, Customer c WHERE ad.customer = c.id and c.id = 1)
Optional <List<Address>> getAddress();
Try to get with getter :
Optional<List<Address>> address = getAddress();
System.out.println(address.getAddress()); //success
System.out.println(address.getAddress().get().get(0).getCustomerBean().getName()) //null value
Successfully get data address from table Address
, but if get Customer
name get null
value, any suggestion?
Solution
Try the following in your @Query
definition:
@Query(value = "SELECT ad FROM Address ad JOIN FETCH ad.customer WHERE ad.customer = 1")
Optional <List<Address>> getAddress();
Answered By - João Dias