我有实体用户和实体角色。他们有很多关系。
User user = new User(password.toString(), null, email, mobileNumber,
organisation, false);
userDAO.create(user);
当我插入一个用户时,同时我用它添加一个角色,所以hibernate执行下一个:
insert into user .....
insert into user_role_link ....
问题是当我向用户插入null角色时,第一个语句成功执行,因为我希望第二个语句启动错误。虽然它启动了一个异常,但是我的代码继续运行,但是如果出现问题,我想在第二个语句中捕获此异常。我怎样才能做到这一点?谢谢!
修改
例外是com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'role_id' cannot be null
如果我发现异常,则会发送电子邮件和短信。如果在第一个插入中强制执行错误,则执行会停止,但它不会在第二个转换语句中发生。
public void registerUser(String email, String mobileNumber, Role role, String organisation) throws MessagingException {
char[] password = RandomStringUtils.random(10, 0, 0, true, true, null,
new SecureRandom()).toCharArray();
User user = new User(password.toString(), null, email, mobileNumber,
organisation, false);
password = null;
try {
userDAO.create(user);
String token = UUID.randomUUID().toString();
VerificationToken verificationToken = new VerificationToken(token, user);
verificationTokenDAO.create(verificationToken);
Map<String, Object> model = new HashMap<>();
model.put("token", token);
String bodyHTML = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/com/port80/sftp/email/confirmregistration.vm", "UTF-8", model);
String bodyTxt = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/com/port80/sftp/email/confirmregistration_plain.vm", "UTF-8", model);
emailSender.sendEmail(email, "subject", bodyTxt, bodyHTML);
smsSender.sendSMS(mobileNumber);
} catch (Exception e) {
System.out.println("-------------------Catch Exception------------------------");
}
}
答案 0 :(得分:0)
从它的外观来看,你只需要使用try-catch块(如果我正确理解你)。像这样:
User user = new User(password.toString(), null, email, mobileNumber,
organisation, false);
try
{
userDAO.create(user);
}
catch(Exception e)
{
//Handle your exception here.
//I recommend catching just your specific exception. Otherwise, you can grab exceptions and never know about them.
//I would put it here for you, but you didn't specify what was being thrown.
}