Skip to content
Advertisement

Get Value Joined 2 Table with Getter in Spring boot

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?

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement