ses
ses

Reputation: 13352

playframework catching PersistenceException

In the test I try to catch the exception:

Here I'm expecting that software comes without a title - so I'm expecting the PersistenceException would be thrown while saving this entity.

@Test
public void saveWithoutTitle() {

    Software software = ...

    try {
        software.save();
        fail("software.title should not be null");
    } catch (PersistenceException ex) {}
}

My test fails (i.e. the exception is never happening)

My Software entity class with @Column(nullable = false !):

@Entity
public class Software extends Model {

    @Column(nullable = false)
    public String title;

What I'm doing wrong?

--

I've already found this the solution how to fix it:

  import javax.validation.constraints.NotNull;

  @Entity
  public class Software extends Model {

    @NotNull
    String title;

But again, what's the point to have:

@Column(nullable = false)

if it does not work?

Upvotes: 0

Views: 350

Answers (2)

ses
ses

Reputation: 13352

I figured out:

I had a mistake, while building the Software instance. So, it works and throws the exception. I should have used the builder instance - one builder to one test. Then everything works like expected.

@Test
public void saveWithoutTitle() {

    SoftwareTemplateBuilder builder = new SoftwareTemplateBuilder();
    Software software = builder.template1().withTitle(null).create();

    try {
        software.save();
        fail("software.title should not be null");
    } catch (ConstraintViolationException ex) {}
}

Upvotes: 0

Jayamohan
Jayamohan

Reputation: 12924

javax.persistence.Column is used to specify the details of the database column. The nullable attribute is generally only used when generating the table definitions, and not used at runtime for validation.

javax.validation.constraints.NotNull is used at runtime to validate the data before persisting it.

That is why you are receiving PersistenceException when using @NotNull. And no exception when you use @Column(nullable = false)

Upvotes: 1

Related Questions