twes twes - 7 months ago 14
Java Question

How to validate constraints of ManyToOne relations?

I've got two models with

1:n
relation and want to use form validators.

If I choose an option from the select, the correct id of the element is stored on the database.

But if I leave it
-- Choose a game--
,
NULL
is stored although the game property is annotated with
@Constraints.Required
.

Models



@Entity
public class Server extends Model {

@Id
public Integer serverId;

@ManyToOne
@Constraints.Required
public Game game;

...
}


@Entity
public class Game extends Model {

@Id
@Constraints.Required
public Integer gameId;

@Constraints.Required
public String name;

public static Map<String,String> options() {
LinkedHashMap<String,String> options = new LinkedHashMap<String,String>();

for(Game c: Game.find.orderBy("name").findList()) {
options.put(c.gameId.toString(), c.name);
}

return options;
}

...
}


Controller



public static Result create() {
return ok(views.html.Server.create.render(form(models.Server.class)))
}


Template



@helper.select(form("game.gameId"), helper.options(Game.options), '_default -> "-- Choose a game --")





I've already tried to use a
@Valid
annotation to force
play.data.Form
to validate the
Game
-Model during the binding process, but that only causes a simple evaluation of the constraints on
Game
properties, which are not filled. Although a correct game is choosen from the list, it gives me an error that
name
is empty:

@Entity
public class Server extends Model {

@ManyToOne
@Constraints.Required
@Valid
public Game game;

@Constraints.Required
public String name;

...





Thanks for your help.

Answer

I fixed this problem by writing a validate() method like this:

public boolean validate() {
    return Game.gameId != null
}

I also looked into the Spring Binding documentation, because Play2.0 Java uses the Spring Binder. In chapter 17.2.4.11 (link) they're giving the default option the value "-". Haven't tested it, but it might be the solution.