Reputation: 621
I have a class defined as follows:
import org.hibernate.validator.constraints.NotBlank;
public class Game {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
@Column(name = "id")
Long id;
@NotBlank
@Column(name = "title")
String title;
...
However, when I execute the following test, no validation exception is thrown:
@Test(expected = ConstraintViolationException.class)
public void thatExistingGameGivenBlankTitleCannotBeSaved(){
Game game = new Game("SimCity 2000");
gameDAO.save(game);
game.setTitle(" "); //game.setTitle(null) doesn't work either
gameDAO.save(game);
}
How can I make the validator trigger when saving an already persisted object? Preferably through Java configuration.
My validation dependencies:
<!-- validation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>5.1.0.Final</version>
</dependency>
Upvotes: 3
Views: 1203
Reputation: 7868
Your JPA implementation has to integrate bean validation. If you're using Hibernate this will happen automatically by putting the validation provider in the class path. If not read 10.1.3. JPA. Given your tags I assume you're using JPA/Hibernate and it should work.
I don't know what gameDAO.save()
is calling on your JPA implementation. Hibernate's integration is event based. If your save()
is none of these events there will be no validation by default:
Upvotes: 1