当前位置: 首页 > 知识库问答 >
问题:

自定义唯一约束注释Spring MVC

周通
2023-03-14

我试图创建自定义注释来检查唯一的字段值。例如,检查唯一的电子邮件地址等。

但无法自动关联“customerDAO”对象。它抛出异常组织。springframework。网状物util。NestedServletException:请求处理失败;嵌套的异常是javax。验证。ValidationException:isValid调用期间发生意外异常。

我在哪里犯错?请建议。

顾客JAVA

@Entity
@Component
public class Customer {

    @Id
    @GeneratedValue
    int id;



    @Unique(value = Customer.class, property = "emailAddress")
    String emailAddress;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
}

唯一的JAVA

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueConstraintValidator.class)
@Documented
public @interface Unique {

    String message() default "{Not Unique}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String property() default "id";

    Class<?> value();

}

UniqueConstraintValidator.java

public class UniqueConstraintValidator implements ConstraintValidator<Unique, String> {

    Class<?> aClass;
    String fieldName;
    Unique unique;

    @Autowired
    CustomerDAO customerDAO;

    @Override
    public void initialize(Unique unique) {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        System.out.println(unique.property());
        System.out.println(unique.value());
        aClass = unique.value();
        this.unique = unique;
        fieldName = unique.property();
    }

    @Override
    @Transactional
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        System.out.print("Valid :: ");
        List<Customer> customerList = customerDAO.findByEmailAddress(s);
        if(customerList!=null && customerList.size()>0){
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate("Please enter unique email address.").addConstraintViolation();
            return false;
        }
        else
            return true;
    }
}

自定义DAO. java

public interface CustomerDAO {

    public void save(Customer customer);

    public Customer get(int id);

    public List<Customer> list();

    public void update(Customer customer);

    public void delete(int id);

    public List<Customer> findByEmailAddress(String emailAddress);
}

CustomerDAOImpl。JAVA

@Repository("customerDAO")
@Transactional(propagation = Propagation.REQUIRED)
public class CustomerDAOImpl implements CustomerDAO {

    @Autowired
    private SessionFactory sessionFactory;
    @Autowired
    HibernateTransactionManager txManager;

    private Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(Customer customer) {
        sessionFactory.getCurrentSession().save(customer);
    }

    @Override
    public Customer get(int id) {
        return null;
    }

    @Override
    public List<Customer> list() {
        return getCurrentSession().createCriteria(Customer.class).list();
    }

    @Override
    public void update(Customer customer) {

    }

    @Override
    public void delete(int id) {

    }

    @Override
    public List<Customer> findByEmailAddress(String emailAddress) {
        return getCurrentSession().createCriteria(Customer.class).add(Restrictions.eq("emailAddress",emailAddress)).list();
    }


}

mvc调度器servlet。xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.springapp.mvc" />
    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="dataSource"
          class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springdemo"/>
        <property name="username" value="root" />
        <property name="password" value="root" />

    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"/>

        <!--<property name="packagesToScan" value="com.springapp.mvc.model" />-->

        <property name="annotatedClasses">
            <list>
                <value>com.springapp.mvc.model.Customer</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="current_session_context_class">thread</prop>
            </props>
        </property>

    </bean>

    <bean id="txManger" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="txManger" />

    <bean id="persistenceExceptionTranslationPostProcessor"
            class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />


</beans>

波姆。xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springapp</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</name>

    <properties>
        <spring.version>3.2.0.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- Spring AOP dependency -->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.16</version>
        </dependency>

        <!-- Hibernate framework -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
                   <groupId>org.javassist</groupId>
                   <artifactId>javassist</artifactId>
                   <version>3.18.0-GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.1.Final</version>
            <classifier>tests</classifier>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-dbcp</artifactId>
            <version>7.0.41</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>SpringDemo</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Tests.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

共有1个答案

章永安
2023-03-14

您应该检查以下问题:Autowired Repository在Custom Constraint Validator中为空

你似乎也有同样的问题。您需要采取更多步骤使验证器成为Springbean并自动连接依赖项

 类似资料:
  • 问题内容: 我正在使用这些注释将数据输入数据库表。我想使userId字段唯一。但是当我这样做时,它向我显示错误 问题答案: 或者,如果它是数据库生成的ID,您也可以执行此操作

  • 我有一个名为的下拉字段,其中包含电话、电子邮件等值,还有一个名为的输入字段。如果选择了下拉值,我想验证输入字段的有效电子邮件地址。。。 我试图创建一个自定义约束,将验证字段对电子邮件正则表达式,如果字段将具有值 我有以下自定义约束的代码 验证器就像 问题是它没有在表单上触发...我使用模型对话框,其中要验证的bean被呈现 参考:使用Hibernate验证器进行跨域验证(JSR 303) 期待您的

  • 我在项目中使用bean验证,我想为现有的约束注释编写一个自定义验证器。 例如,我有一个类,它表示一个名为CustomDateTime的日期/时间。在使用此类作为例如出生日期的类中,我想用过去的日期对字段进行注释: 然后,我通过实现ConstraintValidator创建一个自定义验证器 我知道您通常会创建这样的单独注释: 但对我来说,这似乎是双重代码;-) 如何注册要与一起使用的自定义验证器?

  • 问题内容: 以下模型是一个事件的简单邀请,从一个用户发送到另一个用户。我想确保邀请在以下三列中是唯一的:to_user,from_user和event。 我尝试使用本专栏,但它不起作用。该约束应在SQLite以及生产中的MySQL上均有效。如何定义此唯一约束? 问题答案: 您需要将约束添加到表,而不是模型。为此,请使用声明式: 如果已经在数据库中创建了表,则需要删除该表并再次运行,或者使用Alem

  • 主要内容:在创建表时设置唯一约束,在修改表时添加唯一约束,删除唯一约束MySQL 唯一约束(Unique Key)是指所有记录中字段的值不能重复出现。例如,为 id 字段加上唯一性约束后,每条记录的 id 值都是唯一的,不能出现重复的情况。如果其中一条记录的 id 值为‘0001’,那么该表中就不能出现另一条记录的 id 值也为‘0001’。 唯一约束与主键约束相似的是它们都可以确保列的唯一性。不同的是,唯一约束在一个表中可有多个,并且设置唯一约束的列允许有空值,但