我已经很久没有使用Java了,所以我决定创建一个小应用程序来管理一个项目。我正在调用数据库以插入新用户。我创建了存储过程。我调用了存储过程,并使用MySQL MySQL成功添加了一个新用户。但是,当我使用SimpleJdbcCall从应用程序调用时,它没有插入新用户。它也没有抛出异常。为了消除连接到数据库的问题,我能够调用一个不同的存储过程来返回现有电子邮件的总数。我也不知道为什么。我将感谢任何关于这个问题的原因的指导。
不工作的代码:更新
@Repository
@RequiredArgsConstructor
@Slf4j
public class UserRepository implements IUser<User> {
private SimpleJdbcCall sj;
private final BCryptPasswordEncoder encoder;
@Bean
public SimpleJdbcCall setDataSource(DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setResultsMapCaseInsensitive(true);
sj = new SimpleJdbcCall(jdbcTemplate);
return sj;
}
private boolean emailExists(String email) {
SqlParameterSource in = new MapSqlParameterSource()
.addValue("email", email);
Map<String, Object> out =
sj.withProcedureName(ApplicationConstant.APPLICATION_EMAIL_COUNT)
.execute(in);
Integer count = (Integer) out.get("total_email");
return count > 0;
}
@Override
public User create(User user) {
if(emailExists(user.getEmail().trim().toLowerCase())) throw new ApiException("Email already in use. Please login using your email.");
try {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String email = user.getEmail();
String password = user.getPassword();
SqlParameterSource in = new MapSqlParameterSource()
.addValue("firstName", firstName,Types.NVARCHAR)
.addValue("lastName", lastName,Types.NVARCHAR)
.addValue("email", email,Types.NVARCHAR)
.addValue("password", password,Types.NVARCHAR)
.addValue("user_id", 0, Types.BIGINT);
Map<String, Object> out =
sj.withProcedureName("UspUserUpsert")
.withCatalogName("manageproject")
.withoutProcedureColumnMetaDataAccess()
.declareParameters(
new SqlParameter("firstName", Types.NVARCHAR),
new SqlParameter("lastName", Types.NVARCHAR),
new SqlParameter("email", Types.NVARCHAR),
new SqlParameter("password", Types.NVARCHAR),
new SqlOutParameter("user_id", Types.BIGINT)
)
.execute(in);
Long userId = (Long) out.get("user_id");
} catch(Exception e) {
throw new ApiException("An error occurs. Please try again.");
}
return user;
}
}
参数值:
MapSqlParameterSource {firstName=John, lastName=Doe, [email protected], password=123456.}
存储过程
DELIMITER //;
CREATE PROCEDURE UspUserUpsert(
IN firstName VARCHAR(50),
IN lastName VARCHAR(50),
IN email VARCHAR(100),
IN `password` VARCHAR(255),
OUT user_id INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
SELECT
id
INTO user_id
FROM
`user`
WHERE
email = @email;
START TRANSACTION;
IF (user_id > 0) THEN
UPDATE
`user` u
SET
u.address = 'TESTING'
WHERE
u.user_id = user_id;
END IF;
IF (ISNULL(user_id) = 1 OR user_id = 0) THEN
INSERT INTO User (
first_name,
last_name,
email,
`password`
)
VALUES(
firstName,
lastName,
email,
`password`
);
SELECT
last_insert_id()
INTO user_id;
END IF;
COMMIT;
END //
DELIMITER ;
1条答案
按热度按时间gzjq41n41#
以下是我为使代码工作而做的更改。