java - Spring transient 注释适用于保存但不适用于选择

标签 java hibernate jpa

我正在显示一个网格表,其中包含最后价格寄存器的服务名称。当我在 Service 类中使用 @Transient 时,就会出现问题。

在这种情况下:

enter image description here

我这样做:

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/

相关文章:

java - Domino 10 有时无法在 Java 下解码 MIME header

Java Double 和 Float 数学表现异常

java - EntityManager JNDI 查找

java - JTA 事务中的 Hibernate session 范围与 Open-Session-In-View

java.lang.AbstractMethodError 在 createQuery 期间

java - 在 IntelliJ 中找不到类文件

java - EclipseLink 错误 : Entity class has no primary key specified. 它应该定义 @Id、@EmbeddedId 或 @IdClass

java - 使用线程同时访问Java同步块(synchronized block)?

java - 尝试使用 VBO "array vertex_buffer_object must be disabled to call this method"时出错

java - 在 JPA OneToOne 关系中更改项目后如何删除行?