0

I have a java.lang.NullPointerException when I'm trying to insert data in my database.

Here is my configuration Spring and my code:

applicationContext.xml:

 <bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
 
    <property name="jndiName" value="jdbc/userDb"/>
     
  </bean>



<bean class="com.example.UserDB" id="user">
        <property name="dataSource" ref="myDataSource"/

UserDB.java:

public class UserAccountLog {

    protected JdbcTemplate jdbcTemplate;
    
    public void setDataSource(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }
      public void insertNewUser(String username){

        jdbcTemplate.update( connection -> {
            PreparedStatement ps = connection.prepareStatement(sqlUserInsert, new String[]{"id"});
            int i =1;
            ps.setString(i++, username);
        
            return ps;});

    }

}

And I have this error when he tries to do jdbcTemplate.update( connection:

java.lang.NullPointerException
    at com.example.UserDB.insertNewUser

I tried already to make @Autowired annotation in variable Jdbc but not work too,

Please anyone has idea?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Gohan
  • 1
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – user207421 May 05 '21 at 09:38
  • Please provide a [mre] and post the entire exception stacktrace. – Mark Rotteveel May 07 '21 at 16:15

1 Answers1

0

DI works just in container managed objects. If you want to autowire the jdbcTamplate field in UserDB by the container, you must bring container into the game. You must create UserDB class instance by the container (@Autowire UserDB userDB; or UserDB userDB = context.getBean(UserDB);) and not "by hand" (UserBd userDB = new UserDB();)

The Bitman
  • 1,279
  • 1
  • 11
  • 25
  • Thanks for your reply but it still doesn't work, I tried to add @Autowired Annotation, and I don't need this property "private Datasource datasource" because it defines in application context : – Gohan May 05 '21 at 08:18
  • Inside my Class when I call insertNewUser() method, I make like this before : @Autowired public UserDB userDB; public UserDB userDB() { return userDB(); } And after, I call the insertUser Method like this : userDB.insertNewUser(params); But i have still exception... – Gohan May 05 '21 at 12:38
  • There doesn't need to be a field `dataSource` for property injection to work. The property `dataSource` maps to the setter `setDataSource`. – Mark Rotteveel May 07 '21 at 15:21
  • @MarkRotteveel OK. I have removed the section aboute the `dataSource` property. – The Bitman May 07 '21 at 16:14