WoooHaaaa
WoooHaaaa

Reputation: 20460

Playframework2 Ebean : Why doesn't fetch related objects?

Here's my User:

package models.user;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import play.data.validation.Constraints.MaxLength;
import play.data.validation.Constraints.MinLength;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;

@Entity
@Table(name = "T_USER")
public class User extends Model {
  @Id
  public Long id;

  @Required
  @MaxLength(30)
  @MinLength(4)
  public String username;

  @Required
  @MaxLength(30)
  @MinLength(4)
  public String password;

  @ManyToOne(fetch = FetchType.EAGER)
  @Column(nullable = false)
  public Role role;

  public static Finder<Long, User> find = new Finder<Long, User>(Long.class, User.class);

  public User() {
  }

  public User(String username, String password, Role role) {
    this.username = username;
    this.password = password;
    this.role = role;
  }

  @Override
  public String toString() {
    return "[Tying to login : ] [" + username + " - " + password + "]";
  }
}

In my controller, I want to get a user's role instance, so here's what I did:

public static Result modules(Long id) {
    User user = User.find.byId(id);
    if ("Super User".equalsIgnoreCase(user.role.name)) {
      return ok();
    } else {
      return forbidden();
    }
  }

The problem is, user.role.name is null, but user.role.id is correct here, why EBean doesn't help me to fetch role for users ?

Upvotes: 0

Views: 942

Answers (1)

Anton Sarov
Anton Sarov

Reputation: 3748

I have experienced this problem on different occasions. You could do the following:

First, try to replace your public fields with private ones and the add the appropriate getters and setters (this is a good pattern when using Java anyway).

Second, you can write a little helper for finding/fetching the needed information. So let's say you need to get the user by Id and the do this string check. Then in your User class you can write a method like this:

public static User findById(Long id) {
    return Ebean.find(User.class)
        .fetch("role")
        .where() 
        .eq("id", id)
        .findUnique();
}

After that, just use the method:

public static Result modules(Long id) {
    User user = User.findById(id);
    if ("Super User".equalsIgnoreCase(user.getRole().getName())) {
      return ok();
    } else {
      return forbidden();
    }
  }

Upvotes: 1

Related Questions