我正在显示一个网格表,其中包含最后价格寄存器的服务名称。当我在 Service 类中使用 @Transient 时,就会出现问题。
在这种情况下:
我这样做:
public List<Service> findAllWithPrice() {
NativeQuery<Service> query =
this.getCurrentSession()
.createSQLQuery(
"select s.*, FORMAT((select ps.price from priceServices ps where ps.idService = s.id order by ps.dateRegister DESC limit 1),2) as currentPrice from service s");
query.addEntity( Service.class );
return query.getResultList();
}
/*********************/
@Entity
@Table(name = "service")
public class Service {
/****/
@Transient
private String currentPrice;
public String getCurrentPrice() {
if ( currentPrice == null ) {
return "$ 0.0";
}
return currentPrice;
}
}
如果我离开@Transient,则保存并选择工作,但所有价格都为零。 currentPrice 即将为空。
如果我删除@Transient,选择就会正确。它会加载每项服务的最后注册价格。
但是当我保存到银行时,它返回一个错误,指出它没有找到 currentPrice 列(因为它确实不存在)。
我在论坛和互联网上搜索过,但没有找到解决方案。
如何解决这个问题?
最佳答案
感谢 @M.Prokhorov 提示,我能够按如下方式解决我的问题:
在我的 ServiceDaoImpl 类中,我停止使用 findAllWithPrice 方法,仅使用 findAll:
public List<Service> findAll() {
return this.getCurrentSession().createQuery("from Service", Service.class).getResultList();
}
在我的服务类中,我创建了一个公式来获取最后记录的价格
@Entity
@Table(name = "service")
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
/****/
@Formula("(FORMAT((select ps.price from priceServices ps where ps.idService = id order by ps.dataRegister DESC limit 1),2))")
private String currentPrice;
public String getCurrentPrice() {
if ( currentPrice == null ) {
return "$ 0.0";
}
return currentPrice;
}
}
关于java - Spring transient 注释适用于保存但不适用于选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823675/