5

javax.validation.constraints から @NotNull で注釈が付けられたフィールドを持つ Spring エンティティがあります

@Entity
public abstract class IdentifiableNamedEntity {
    @NotNull
    @Column(unique = true)
    private String name;
}

問題は、名前フィールドに null 値を設定すると、データベースに格納されることです。ただし、クラスを次のように変更すると、受け取りたい例外が発生します。

@Entity
public abstract class IdentifiableNamedEntity {
    @Column(unique = true, nullable=false)
    private String name;
}

nullable=false を指定せずに @NotNull を希望どおりに動作させる方法はありますか? 標準の Java アノテーションに依存する nullable=false に代わるものはありますか?

これは私の春の構成です:

アプリケーションコンテキスト

<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> {
}
4

2 に答える 2

7

@NotNullは JSR 303 Bean Validation アノテーションです。データベースの制約自体とは何の関係もありません。この注釈は、検証を目的としています。 @Column(nullable = false)は、列が非 null であることを宣言する方法です。この最後の注釈は、データベース スキーマの詳細を示すことを目的としています

于 2014-07-20T17:41:02.960 に答える