
在这篇文章中,我们将探讨投影在 spring data jpa 中的工作原理,讨论不同的类型,并通过示例来演示它们如何简化数据访问。
对于本指南,我们使用:
注意:有关更详细的示例,请访问我的 github 存储库
@setter
@getter
@entity(name = "tbl_address")
public class address {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string street;
private string city;
private string state;
private string country;
private string zipcode;
}
@setter
@getter
@entity(name = "tbl_user")
public class user {
@id
@generatedvalue(strategy = generationtype.identity)
private long id;
private string firstname;
private string lastname;
private string email;
private string status;
@onetoone(cascade = cascadetype.all)
@joincolumn(name = "address_id", referencedcolumnname = "id")
private address address;
}
通常,您的应用程序仅需要实体字段的子集,加载不必要的数据可能会导致:
投影使您能够仅以所需的确切格式获取所需的数据,从而帮助我们避免出现问题。当为 restful api 获取数据时,这特别有用,其中响应不需要实体的所有字段。
spring data jpa 提供多种类型的投影:
2.1 - 基于界面的投影
基于接口的投影允许我们为要检索的字段定义带有 getter 方法的接口。然后,spring data jpa 将使用这些 getter 将实体的字段映射到接口。
定义投影接口和存储库类:
@repository
public interface userrepository extends jparepository<user, long> {
@query("""
select
concat(u.firstname, ' ', u.lastname) as fullname,
u.email as email,
concat( a.street, ', ', a.city, ', ', a.state) as fulladdress,
a.country as country,
a.zipcode as zipcode
from tbl_user u
left join tbl_address a on u.address.id = a.id
""")
list<userinfoprojection> findalluserinfo();
interface userinfoprojection {
string getfullname();
string getemail();
string getfulladdress();
string getcountry();
string getzipcode();
}
}
定义一个 dto 类以从投影传输到 dto。
@builder
@setter
@getter
public class userdto {
private string fullname;
private string email;
private string address;
private string country;
private string zipcode;
public static userdto of(userrepository.userinfoprojection entity) {
if (objects.isnull(entity))
return null;
return userdto.builder()
.fullname(entity.getfullname())
.email(entity.getemail())
.address(entity.getfulladdress())
.country(entity.getcountry())
.zipcode(entity.getzipcode())
.build();
}
}
@springboottest
@autoconfiguremockmvc
class querytypesapplicationtests {
@autowired
private userrepository userrepository;
@test
public void testderivedquerymethods() {
list<userdto> results = userrepository.findalluserinfo()
.stream()
.map(userdto::of)
.tolist();
assertequals(10, results.size(), "expected 10 users");
}
}
通过基于类的投影,我们可以使用自定义 dto 直接映射结果。这种方法可以让您更好地控制数据的结构,如果您需要在构造函数中自定义逻辑,这种方法会很有用。
定义 dto:
@setter
@getter
public class userprojectiondto {
private final string fullname;
private final string email;
private final string address;
private final string country;
private final string zipcode;
public userprojectiondto(string fullname, string email, string address, string country, string zipcode) {
this.fullname = fullname;
this.email = email;
this.address = address;
this.country = country;
this.zipcode = zipcode;
}
}
定义存储库类并编写sql查询来获取用户信息。
@repository
public interface userrepository extends jparepository<user, long> {
@query(
"""
select new com.davidnguyen.querytypes.user.userprojectiondto(
concat(u.firstname, ' ', u.lastname),
u.email,
concat(a.street, ', ', a.city, ', ', a.state),
a.country,
a.zipcode
)
from tbl_user u left join tbl_address a on u.address.id = a.id
"""
)
list<userprojectiondto> findalluserinfo();
}
spring data jpa 执行一个查询,为每行数据构造一个 dto,仅选择构造函数中指定的字段。
@SpringBootTest
@AutoConfigureMockMvc
class QueryTypesApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void testDerivedQueryMethods() {
List<UserProjectionDTO> users = userRepository.findAllUserInfo();
assertEquals(10, users.size(), "Expected 10 users");
}
}
每种投影类型都有其用例:
性能说明:
仅选择您需要的字段:无论使用基于类还是基于接口的投影,始终将选择限制为仅必要的字段以优化数据库负载。
对 dto 使用不变性:对于基于类的投影,创建不可变的 dto(最终字段,无 setter)以使其安全稳定。
考虑复杂联接的本机查询:如果您的投影涉及复杂联接或计算字段,请考虑使用带有 @sqlresultsetmapping 和 @constructorresult 注释的本机 sql 查询以获得更多控制。
分析性能查询:特别是对于大型数据集,使用分析工具(如 jpa/hibernate 日志记录)来监视查询性能并确保您的投影不会无意中加载额外的数据。
spring data jpa 中的投影提供了强大的选项来控制从查询返回的数据。通过使用基于接口、基于类和动态投影,您可以微调数据检索以满足应用程序的要求。请记住,有效地实施投影可以提高数据处理的效率,尤其是在具有大型数据集的应用程序中。
下一篇文章见。快乐编码!
访问我的博客以获取更多帖子。
以上就是如何在 Spring Data JPA 中使用 DTO 投影获取数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号