Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3724332
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T06:36:11+00:00 2026-05-19T06:36:11+00:00

I have a field, say, user_name , that should be unique in a table.

  • 0

I have a field, say, user_name, that should be unique in a table.

What is the best way for validating it using Spring/Hibernate validation?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T06:36:12+00:00Added an answer on May 19, 2026 at 6:36 am

    One of the possible solutions is to create custom @UniqueKey constraint (and corresponding validator); and to look-up the existing records in database, provide an instance of EntityManager (or Hibernate Session)to UniqueKeyValidator.

    EntityManagerAwareValidator

    public interface EntityManagerAwareValidator {  
         void setEntityManager(EntityManager entityManager); 
    } 
    

    ConstraintValidatorFactoryImpl

    public class ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory {
    
        private EntityManagerFactory entityManagerFactory;
    
        public ConstraintValidatorFactoryImpl(EntityManagerFactory entityManagerFactory) {
            this.entityManagerFactory = entityManagerFactory;
        }
    
        @Override
        public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
            T instance = null;
    
            try {
                instance = key.newInstance();
            } catch (Exception e) { 
                // could not instantiate class
                e.printStackTrace();
            }
    
            if(EntityManagerAwareValidator.class.isAssignableFrom(key)) {
                EntityManagerAwareValidator validator = (EntityManagerAwareValidator) instance;
                validator.setEntityManager(entityManagerFactory.createEntityManager());
            }
    
            return instance;
        }
    }
    

    UniqueKey

    @Constraint(validatedBy={UniqueKeyValidator.class})
    @Target({ElementType.TYPE})
    @Retention(RUNTIME)
    public @interface UniqueKey {
    
        String[] columnNames();
    
        String message() default "{UniqueKey.message}";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    
        @Target({ ElementType.TYPE })
        @Retention(RUNTIME)
        @Documented
        @interface List {
            UniqueKey[] value();
        }
    }
    

    UniqueKeyValidator

    public class UniqueKeyValidator implements ConstraintValidator<UniqueKey, Serializable>, EntityManagerAwareValidator {
    
        private EntityManager entityManager;
    
        @Override
        public void setEntityManager(EntityManager entityManager) {
            this.entityManager = entityManager;
        }
    
        private String[] columnNames;
    
        @Override
        public void initialize(UniqueKey constraintAnnotation) {
            this.columnNames = constraintAnnotation.columnNames();
    
        }
    
        @Override
        public boolean isValid(Serializable target, ConstraintValidatorContext context) {
            Class<?> entityClass = target.getClass();
    
            CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    
            CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
    
            Root<?> root = criteriaQuery.from(entityClass);
    
            List<Predicate> predicates = new ArrayList<Predicate> (columnNames.length);
    
            try {
                for(int i=0; i<columnNames.length; i++) {
                    String propertyName = columnNames[i];
                    PropertyDescriptor desc = new PropertyDescriptor(propertyName, entityClass);
                    Method readMethod = desc.getReadMethod();
                    Object propertyValue = readMethod.invoke(target);
                    Predicate predicate = criteriaBuilder.equal(root.get(propertyName), propertyValue);
                    predicates.add(predicate);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
    
            TypedQuery<Object> typedQuery = entityManager.createQuery(criteriaQuery);
    
            List<Object> resultSet = typedQuery.getResultList(); 
    
            return resultSet.size() == 0;
        }
    
    }
    

    Usage

    @UniqueKey(columnNames={"userName"})
    // @UniqueKey(columnNames={"userName", "emailId"}) // composite unique key
    //@UniqueKey.List(value = {@UniqueKey(columnNames = { "userName" }), @UniqueKey(columnNames = { "emailId" })}) // more than one unique keys
    public class User implements Serializable {
    
        private String userName;
        private String password;
        private String emailId;
    
        protected User() {
            super();
        }
    
        public User(String userName) {
            this.userName = userName;
        }
            ....
    }
    

    Test

    public void uniqueKey() {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default");
    
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        ValidatorContext validatorContext = validatorFactory.usingContext();
        validatorContext.constraintValidatorFactory(new ConstraintValidatorFactoryImpl(entityManagerFactory));
        Validator validator = validatorContext.getValidator();
    
        EntityManager em = entityManagerFactory.createEntityManager();
    
        User se = new User("abc", poizon);
    
           Set<ConstraintViolation<User>> violations = validator.validate(se);
        System.out.println("Size:- " + violations.size());
    
        em.getTransaction().begin();
        em.persist(se);
        em.getTransaction().commit();
    
            User se1 = new User("abc");
    
        violations = validator.validate(se1);
    
        System.out.println("Size:- " + violations.size());
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Say I have a table with a unique positive integer field. I currently have
Say I have a table with a field called ordernum that denotes the order
Say I have a 'user_log' table with the following field: id user_id status_text timestamp
I have this problem where after a field (say Field3 in table MyTable) is
I have a field in a table which contains bitwise flags. Let's say for
say i have a nvarchar field in my database that looks like this 1,
Let's say I have a Customer table which has a PrimaryContactId field and a
Let's say I have an Order table which has a FirstSalesPersonId field and a
Let's say I have a Student and a School table. One operation that I
I my index lets say I have field field named full_name. I'm doing following

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.