-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
I want to add a feature that is not published by the documentation.
This feature is only valid for JPA queries. We can choose the columns we want according to the DTO model. An alternative to interface based projection.
If you want to check it out, I share the medium and github links:
medium
github
In code, the feature is as follows:
Entity User:
public class User {
@Id
@SequenceGenerator(name = "user_sequence", sequenceName = "sq_user", allocationSize = 1_000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence")
private Long id;
@column
private String email;
@column
private String password;
@manytoone(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@ToString.Include(name = "id")
private Adress adress;
/*
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + ", password=" + password + ", adress=" + this.getAdress().getId() + "]";
}
*/}
Entity Adress:
public class Adress {
@ToString.Include
@EqualsAndHashCode.Include
@Id
@SequenceGenerator(name = "adres_sequence", sequenceName = "sq_adres", allocationSize = 1_000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "adres_sequence")
private Long id;
@Column
private Integer no;
@Column
private String house;
public Adress(Long id) {
this.id = id;
}}
DTO AdressDTO1:
@Data @AllArgsConstructor public class AdressDTO1 { private Long id; private int no; private String house; }
DTO UserDto1:
@Data
public class UserDto1 {
private Long id;
private String email;
private String password;
private AdressDTO1 adressDTO;
public UserDto1(Long id, String email, String password, Long adressId, int adressNo, String adressHouse) {
this.id = id;
this.email = email;
this.password = password;
this.adressDTO = new AdressDTO1(adressId, adressNo, adressHouse);
}}
//Repository Class Method: public <T> List<T> findBy(Class<T> clazz);
//Service Layer Method: userRepository.findBy(UserDto1.class);
Select Query:
select
user0_.id as col_0_0_,
user0_.email as col_1_0_,
user0_.password as col_2_0_,
adress1_.id as col_3_0_,
adress1_.no as col_4_0_,
adress1_.house as col_5_0_
from
user user0_
left outer join
adress adress1_
on user0_.adress_id=adress1_.id