Issue
I'm not sure how to fix this since I just started doing spring boot project last Thursday. Unfortunately today is the deadline of my project so frankly I'm quite panicking right now :/
Here is my sample problem code:
@Override
public Integer getCountByEmail(String email) {
return jdbcTemplate.queryForObject(SQL_COUNT_BY_EMAIL, new Object[]{email}, Integer.class);
}
@Override
public User findById(Integer userId) {
return null;
}
Here is the overall code of the Java Class:
package com.example.Spring.boot.Repositories;
import com.example.Spring.boot.Entity.User;
import com.example.Spring.boot.Exceptions.EtAuthException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import java.sql.PreparedStatement;
import java.sql.Statement;
@Repository
public class UserRepositoryImpl implements UserRepository {
private static final String SQL_CREATE = "INSERT INTO SB_USERS(USER_ID,
FIRST_NAME, LAST_NAME, EMAIL," +`"PASSWORD) VALUES(NEXTVAL('SB_USERS_SEQ'), ?, ?, ?, ?)";`
private static final String SQL_COUNT_BY_EMAIL = "SELECT COUNT(*) FROM SB_USERS WHERE EMAIL = ?";
private static final String ID = "SELECT USER_ID, FIRST_NAME, LAST_NAME, EMAIL, PASSWORD " +`"FROM SB_USERS WHERE USER_ID = ?";`
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public Integer create(String firstName, String lastName, String email, String password) throws EtAuthException {
try {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(SQL_CREATE, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, email);
ps.setString(4, password);
return ps;
}, keyHolder);
return (Integer) keyHolder.getKeys().get("USER_ID");
}catch (Exception e) {
throw new EtAuthException("Invalid details. Failed to create account");
}
}
@Override
public User findByEmailAndPassword(String email, String password) throws EtAuthException {
return null;
}
@Override
public Integer getCountByEmail(String email) {
return jdbcTemplate.queryForObject(SQL_COUNT_BY_EMAIL, new Object[]{email}, Integer.class);
}
@Override
public User findById(Integer userId) {
return null;
}
}
Solution
The following method has been deprecated and must not be used:
public <T> T queryForObject(String sql, @Nullable Object[] args, Class<T> requiredType)
Use the following equivalent method instead:
<T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args)
Example:
return jdbcTemplate.queryForObject(SQL_COUNT_BY_EMAIL, Integer.class, email);
Answered By - gkatiforis
Answer Checked By - Clifford M. (JavaFixing Volunteer)