我有一个Spring实体,其中有一个用@NotNull注释的字段来自javax.validation.constraints
@Entity
public abstract class IdentifiableNamedEntity {
@NotNull
@Column(unique = true)
private String name;
}
问题是如果为name字段设置null值,它将存储在数据库中.但是,如果我按照以下方式更改类,则会引发我希望收到的异常:
@Entity
public abstract class IdentifiableNamedEntity {
@Column(unique = true, nullable=false)
private String name;
}
有没有办法可以避免指定nullable = false,但让@NotNull按照我的意愿行事?是否存在依赖于标准Java注释的nullable = false的替代方法,例如:一些Hibernate配置?
这是我的弹簧配置:
的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持久性
<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>
由于我使用的是存储库,我还报告了相应的实体存储库:
@Repository
public interface IdentifiableNamedEntityRepository extends JpaSpecificationExecutor<IdentifiableNamedEntity>, JpaRepository<IdentifiableNamedEntity, Long> {
}
解决方法:
@NotNull是JSR 303 Bean Validation批注.它与数据库约束本身无关.此注释旨在用于验证. @Column(nullable = false)是声明列不为空的方法.最后一个注释用于指示数据库架构详细信息