首页 > 解决方案 > Spring 瞬态注释适用于保存,但不适用于选择

问题描述

我正在显示一个网格表,其中包含最后一个价格寄存器的服务名称。当我在 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 列(因为它真的不存在)。

我在论坛和互联网上搜索了这里,但没有找到解决方案。

我怎么解决这个问题?

标签: javahibernatejpa

解决方案


感谢@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;
    }
}

推荐阅读