简体   繁体   中英

Spring boot JPA fetch specific column from crudRepository query

Im trying to get the "name" field from my user class within my Employee class so i can avoid making an additional query to get the user name.

For the moment, I've only been able to get the user_id this way

My user class

@Entity @Table(name="user", schema = "public") @Getter @Setter @NoArgsConstructor @Accessors(chain = true)
public class User implements Serializable{
    private @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "user_id") Long id;
    private @Column(unique = true) String email;
    private String name;
}

My Employee class

@Entity @Table(name = "employee",schema = "public") @Getter @Setter @NoArgsConstructor @Accessors(chain = true)
public class Employee implements Serializable {
    private @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "employee_id") Long id;
    @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "fk_user_id",insertable = false,updatable = false) private User user;
    private @Column(name="fk_user_id") Long userId;
}

i know i can not retrieve the name without selecting it so i tried using a custom query on my crudRepository

public interface EmployeeRepository extends CrudRepository<Employee, Long>{
    @Query(value = "SELECT employee.*, public.user.name FROM public.employee INNER JOIN public.user ON public.user.user_id = employee.fk_user_id ", nativeQuery = true)
    List<Employee> findEmployees();
}

The query returns what i expect but i dont know how to fetch the resulted column "name"on my Employee class

Any help or guidance is welcome, thanks for reading

In my opinion you should select the Employee only and then get the name from the fetched User . Also I dont think you need the query to be native:

@Query(value = "SELECT e FROM public.employee e INNER JOIN FETCH e.user")
    List<Employee> findEmployees();
}

Then:

for(Employee e: findEmplyees){
    String name = e.getUser.getName();
}

When you want to fetch more data then what is described in your entity class, and you don't want to fetch lazy relationships, you could create a new class, for example one DAO class that will have all the attributes you want to fetch. So in your case probably EmployeeDAO class with all the attributes of the employee entity plus userName . And then use it as a returned collection:

@Query(your query)
List<EmployeeDAO> findEmployees();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM