1.使用原生sql查询。自定义接受类为对象,(貌似不支持对象属性)。
@Repository
public interface UserRepository extends JpaRepository<User,String> {
@Query(value = "select * from User",nativeQuery = true)
List<IUserDTO> selectIUserDTO();
}
package com.example.test1.dto;
public interface IUserDTO {
String getId();
String getName();
String getAge();
}
参考
https://my.oschina.net/xiwanglr/blog/3067932
https://blog.youkuaiyun.com/kuangniaokuang/article/details/105249490
https://www.baeldung.com/spring-data-jpa-projections
2.hql。
@Query("select new com.example.test1.dto.UserDTO(u.id,u.age,u.name) from User u where u.id=1")
UserDTO selectUserDTO();
package com.example.test1.dto;
public class UserDTO {
private String id;
private String age;
private String name;
@Override
public String toString() {
return "UserDTO{" +
"id='" + id + '\'' +
", age='" + age + '\'' +
", name='" + name + '\'' +
'}';
}
public UserDTO(String id, String age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public UserDTO() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}