javasqlplayframeworkebean

Ebean not fetch oneToMany relationship


I have a Post entity that has a files attribute :

    @Entity
    public class Post extends Model {
    @Id
    private long id;
    @ManyToOne
    private PostType postType;
    @ManyToOne
    private User user;
    @ManyToOne
    private Category category;

    @OneToMany (cascade = CascadeType.PERSIST)
    private List<ImageLink> files;
    private String description;
    private int likes;
    private int messages;
    private boolean liked;
    private boolean saved;
    private Date timesTamp;

    //getters and setters

    }

I try to get the attribute files after passing a RawSql (in which I also get other attributes) :

    public Result test(){

        long user_id = 1;

        String sql =
                "SELECT p.id, p.description, p.likes, p.times_tamp, u.id, " +
                "u.name, u.phone, u.profile_url, u.rate, u.rate_count, c.id, " +
                "EXISTS ( " +
                "SELECT * " +
                "FROM likes " +
                "WHERE p.id = likes.post_id " +
                "AND likes.user_id = "+user_id +
                ") AS liked "+
                "FROM post p " +
                "JOIN user_ u ON u.id = p.user_id "+
                "JOIN category c ON c.id = p.category_id";

        RawSql rawSql = RawSqlBuilder
                .parse(sql)
                .tableAliasMapping("u", "user")
                .columnMapping("c.id", "category.id")
                .create();


        List<TestEntity> data = TestEntity.finder
                .query()
                .setRawSql(rawSql)
                .fetch("files.image", "url")
                .findList();


        return ok(Ebean.json().toJson(data));
    }

The problem is that when I return the query result using Ebean.json().tojson(data), the files attribute is not returned. This is the result returned :

{
    "id": 1,
    "user": {
        "id": 18,
        "name": "smozi_shop",
        "phone": "+22969298229",
        "profileUrl": null,
        "rate": 0.0,
        "rateCount": 0
    },
    "category": {
        "id": 1
    },
    "description": "smozi",
    "likes": 1,
    "liked": false,
    "timesTamp": 1575956493968
}

Noted that when I use json.toJson(data) to return the result, it returns all the attributes of the Post entity I could use the json.toJson(data) but it will be heavy to load data on the network.

I want to retrieve (select) only needed attributes (including the files attribute).

Thank you


Solution

  • Finaly i fix it using Ebean.PathProperties

    PathProperties fetchPath =  new PathProperties();
    fetchPath.addToPath("imagesLinks", "image");
    fetchPath.addToPath("imagesLinks.image", "url");        
    return ok(Ebean.json().toJson(data, fetchPath));
    

    I hope it will help those who have the same probleme. If there is another way to do it, i would be delighted to read you ;)