我有一个 Spring 实体,其字段用 javax.validation.constraints 中的 @NotNull 注释
@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 配置?
这是我的弹簧配置:
应用程序上下文
<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>
应用程序上下文持久性
<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> {
}