gpt4 book ai didi

java - 使用投影从子表中获取特定列

转载 作者:行者123 更新时间:2023-11-29 02:57:36 26 4
gpt4 key购买 nike

我有两张 table

Loan (id, amount, duration)

LoanStatus(id, status, loan_id) // just an example, but it has lot more fields in this table

贷款.java

public class Loan{

private int id;
private int amount;
private int duration;
private LoanStatus loanStatus;

// getter and setters

}

贷款状态.java

public class LoanStatus{   // just an example, but it has many fields than what actually given

private int id;
private String status;
private Loan loan;

//getter and setters

}

现在我只想使用投影获得 amountdurationloanStatus.status 。我已使用 createAlias() 成功获取该特定列,但将其设置为 setter 时会出现问题。

Criteria criteria = getSession().createCriteria(Loan.class,"loan");
criteria.createAlias("loan.loanStatus", "loanStatus")
.setProjection(Projections.projectionList().add(Projections.property("id"),"id")
.add(Projections.property("amount"),"amount")
.add(Projections.property("duration"),"duration")
.add(Projections.property("loanStatus.status"), "loanStatus"))
.add(Restrictions.eq("id", id))
.setResultTransformer(Transformers.aliasToBean(Loan.class));
return criteria.list();

我有一个错误如下。

IllegalArgumentException occurred while calling setter for property [com.site.dto.Loan.loanStatus (expected type = com.site.dto.LoanStatus)]; target = [com.site.dto.Loan@4083974a], property value = [Pending]

所以我得到了我预期的列值“Pending”,但问题是在将它设置为 setter 时。我见过很多关于投影的问题,但其中大部分是基于使用投影的限制,而不是使用投影获取 child 的特定列。

最佳答案

编写您自己的自定义转换器。以下实现可能正是您所需要的

https://github.com/samiandoni/AliasToBeanNestedResultTransformer .他们的文档中写的用法示例

class Person {
private Long id;
private String name;
private Car car;
// getters and setters
}

class Car {
private Long id;
private String color;
// getters and setters
}

List<Person> getPeople() {
ProjectionList projections = Projections.projectionList()
.add(Projections.id().as("id"))
.add(Projections.property("name").as("name"))
.add(Projections.property("c.id").as("car.id"))
.add(Projections.property("c.color").as("car.color"));

Criteria criteria = getCurrentSession().createCriteria(Person.class)
.createAlias("car", "c")
.setProjection(projections)
.setResultTransformer(new AliasToBeanNestedResultTransformer(Person.class));

return (List<Person>) criteria.list();
}

// each car of Person will be populated

关于java - 使用投影从子表中获取特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28796400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com