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 8996481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T23:45:37+00:00 2026-06-15T23:45:37+00:00

I’m working on a Spring MVC + Hibernate + JPA app with a user

  • 0

I’m working on a Spring MVC + Hibernate + JPA app with a user registration form and I decided to use a JSR-303 validator to check whether the username already existed in the DB:

public class UniqueUsernameValidator implements ConstraintValidator<VerifyUniqueUsername, String> {

    @Autowired
    UserService userService;

    @Override
    public void initialize(VerifyUniqueUsername constraintAnnotation) {     
    }

    @Override
    public boolean isValid(String username, ConstraintValidatorContext context) {                       

        return  username!=null &&  userService.findByUsername(username) == null;        
    }
}

It is very straightforward and validation worked great on my controller:

....
    public String signup(@Valid @ModelAttribute("newUser") User user, BindingResult newUserBeanResult)
.....

The current problem I’m facing is that after I get my User object validated and I call:

userService.save(user);

Which implements CrudRepository, I get a NullPointerException. For some reason UserService is injected during validation on the controller but not when I call CrudRepository.save().

I saw similar posts such as this:
@Autowired bean null in ConstraintValidator when invoked by Sessionfactory.getCurrentSession.merge
and this:
hibernate validator without using autowire
but I was wondering if someone has run into this before. I would think that injecting beans to access the database on a validator is fairly common.

As a workaround I added a check for null on userService but it doesn’t feel right.

  1. Is this expected behaviour? Are these validations supossed to fire before calling CrudRepository.save()?
  2. Am I suppossed to handle “manually” hibernate events? In this case pre-insert
  • 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-06-15T23:45:38+00:00Added an answer on June 15, 2026 at 11:45 pm

    I ended up solving this issue by instructing Spring’s EntityManagerFactoryBean to use my validator bean (more accurately, hibernate will now be using Spring’s validator):

    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
            </property>        
            <property name="packagesToScan" value="some.packages"/>
            <property name="jpaPropertyMap">
                <map>
                    <entry key="javax.persistence.validation.factory" value-ref="validator"  />           
                </map>
            </property>
            <property name="jpaProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.max_fetch_depth">3</prop>
                    <prop key="hibernate.jdbc.fetch_size">50</prop>
                    <prop key="hibernate.jdbc.batch_size">10</prop>
                    <prop key="hibernate.show_sql">true</prop>              
                </props>        
            </property>
        </bean>  
    

    However, this threw a StackOverflow error 🙂

    Apparently the cause of this issue was that my validator was using a finder method (findByUsername) and finder methods trigger a hibernate flush, which in turn triggers a validation. This loops indefinitely until you get the most famous exception there is.

    So…I fixed this by changing the validators to use the EntityManager directly (instead of the CRUD repository) and temporarily change the FlushModeType to COMMIT. Here is the example:

    public class UniqueUsernameValidator implements ConstraintValidator<UniqueUsername, String> {
    
        @PersistenceContext
        private EntityManager em;
    
        @Autowired
        UserService userService;
    
        @Override
        public void initialize(UniqueUsername constraintAnnotation) {       
        }
    
        @Override
        public boolean isValid(String username, ConstraintValidatorContext context) {
            try { 
                em.setFlushMode(FlushModeType.COMMIT);          
                return userService.findByUsername(username) == null;
    
                } finally { 
               em.setFlushMode(FlushModeType.AUTO);
               }    
        }
    }
    

    This solves the issue where the validator was using the finder function which triggered a hibernate flush which in turn was triggering the validator causing a StackOverflowError.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have an MVC Razor view @{ ViewBag.Title = Index; var c = (char)146;
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I am writing an app with both english and french support. The app requests

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.