0

I am showing a grid table whit the service names with the last price register. The problem is happen when I use the @Transient in my Service class.

In this case:

enter image description here

I do this:

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;
    }
}

If I leave @Transient both save and select work but ALL prices come as zero. The currentPrice is coming null.

If I remove @Transient the select comes right. It loads the services with the last registered price for each one.

But when I save to the bank, it returns an error saying that it did not find the currentPrice column (Because it really doesn't exist).

I searched here in the forum and on the internet but I didn't find a solution.

How can I solve this problem?

Donadon
  • 113
  • 11

1 Answers1

1

Thanks to the @M.Prokhorov Tip, I was able to solve my problem as follows:

In my ServiceDaoImpl class, I stopped using the findAllWithPrice method to use findAll only:

public List<Service> findAll() {
    return this.getCurrentSession().createQuery("from Service", Service.class).getResultList();
}

In my Service class I created a formula to fetch the last recorded price

@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;
    }
}
Donadon
  • 113
  • 11