2

I'm working on a play framework application, where ebean is included. So I decided to give it a try. I have a model where I use the @Formula annotation to fetch a sum into the enty like so:

@Entity
public class Note extends Model {

    private static final long serialVersionUID = -2384288983980432586L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(insertable = false, updatable = false)
    private Long id;
    @Transient  
    @Formula(select = "case a.upvotes when null then 0 else a.upvotes end case", join = "left outer join (select v.note_id, count(*) as upvotes from notevote v where v.noteval > 0 group by v.note_id) as a on a.note_id = ${ta}.id")
    private Integer upvotes;
    ....

This query compiles and everything seems to work except for the fact that the upvotes field is always null. So I read somewhere that this field should be included whenever I query for something using the ebean.finder. So to get by id, I need to write:

Ebean.find(Note.class).select("id, upvotes").setId(id).findUnique();

Instead of

Ebean.find(Note.class).setId(id).findUnique();

The problem is that it does not matter what I write in the select part above, it is ignored.

Runar Halse
  • 3,528
  • 10
  • 39
  • 59

2 Answers2

2

Before doing any more sophisticated debugging, try to remove @Transient annotation over upvotes field.

From javadocs:

You may also put use the Transient annotation with the Formula annotation. The effect of the Transient annotation in this case is that the formula will NOT be included in queries by default

That way you wan't need to explicitly mention it in select.

If then won't help, please enable EBean SQL logs as described here and see whether your formula SQL is executed or not.

Knowing that, we'll think what to do next.

Community
  • 1
  • 1
Piotr Sobczyk
  • 6,443
  • 7
  • 47
  • 70
1

I tracked down a ebean documentation file where there was a demo of how this could be done with a much simpler query:

@Formula(select = "(select count(*) from Notevote v where v.noteval > 0 AND v.note_id = ${ta}.id)")

using this syntax, and removing the transient annotation fixes the problem. As I removed the transient annotation I do not have to request the field whenever I read the entity either...

Runar Halse
  • 3,528
  • 10
  • 39
  • 59