I have a Spring Entity with a field annotated with @NotNull from javax.validation.constraints
@Entity
public abstract class IdentifiableNamedEntity {
@NotNull
@Column(unique = true)
private String name;
}
The issue is that if a set a null value for the name field, it gets stored in the database. However, if I change the class as follow, it raises the exception I would like to receive:
@Entity
public abstract class IdentifiableNamedEntity {
@Column(unique = true, nullable=false)
private String name;
}
Is there a way I can avoid to specify nullable=false, but getting @NotNull to behave as I would like? Is there any alternative to nullable=false that relies on standard Java annotations, e.g. some Hibernate configuration?
This is my spring configuration:
ApplicationContext
<beans ...>
<context:property-placeholder location="classpath*:spring/database.properties" />
<context:component-scan base-package="com.lh.clte" />
<import resource="classpath:spring/applicationContext-persistence.xml" />
</beans>
applicationContext-persistence
<beans ...>
<import resource="classpath:spring/applicationContext-jpa.xml" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
<property name="initialSize" value="3" />
<property name="maxActive" value="10" />
</bean>
<tx:annotation-driven mode="proxy"
transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
applicationContext-jpa
<beans ...>
<jpa:repositories base-package="com.lh.clte.repository" />
</beans>
Since I am using repositories, I also report the corrisponding entity repository:
@Repository
public interface IdentifiableNamedEntityRepository extends JpaSpecificationExecutor<IdentifiableNamedEntity>, JpaRepository<IdentifiableNamedEntity, Long> {
}
@NotNull is a JSR 303 Bean Validation annotation. It has nothing to do with database constraints itself. This annotation is intended for validation. @Column(nullable = false) is the way of declaring a column to be not-null. This last annotation is intended for indicating database schema details