Man*_*anu 3 java spring jpa notnull
我有一个Spring实体,其中有一个用@NotNull注释的字段来自javax.validation.constraints
@Entity
public abstract class IdentifiableNamedEntity {
@NotNull
@Column(unique = true)
private String name;
}
Run Code Online (Sandbox Code Playgroud)
问题是如果为name字段设置null值,它将存储在数据库中.但是,如果我按照以下方式更改类,则会引发我希望收到的异常:
@Entity
public abstract class IdentifiableNamedEntity {
@Column(unique = true, nullable=false)
private String name;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以避免指定nullable = false,但让@NotNull按照我的意愿行事?是否有任何替代nullable = false依赖于标准Java注释,例如一些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>
Run Code Online (Sandbox Code Playgroud)
的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>
Run Code Online (Sandbox Code Playgroud)
的applicationContext-JPA
<beans ...>
<jpa:repositories base-package="com.lh.clte.repository" />
</beans>
Run Code Online (Sandbox Code Playgroud)
由于我使用的是存储库,我还报告了相应的实体存储库:
@Repository
public interface IdentifiableNamedEntityRepository extends JpaSpecificationExecutor<IdentifiableNamedEntity>, JpaRepository<IdentifiableNamedEntity, Long> {
}
Run Code Online (Sandbox Code Playgroud)
@NotNull是一个JSR 303 Bean Validation注释.它与数据库约束本身无关.此注释旨在用于验证. @Column(nullable = false)是声明列不为null的方法.最后一个注释用于指示数据库架构详细信息
| 归档时间: |
|
| 查看次数: |
6598 次 |
| 最近记录: |