Springboot和mysql DB如何处理重复键入口

时间:2018-02-03 03:07:20

标签: java mysql hibernate jpa spring-boot

我有一个spring-boot API,我想用它将我的数据库连接到我的iOS应用程序,但是我不知道如何处理重复的键异常。在我的实体中,我有4个独特的字段,如电子邮件,电话,用户名和ID。我的目的是在用户尝试输入重复密钥时收到如下错误消息:

"message"= "Error saving data, dublicate keys were found on username and phone number" 

或类似的东西:

"message"= "Error saving data, dublicate keys were found on username " 

目前我在控制台中收到此错误,但我想将其作为错误响应消息显示给用户:

enter image description here

这是我目前的代码:

 public ResponseMerchantQuery createMerchant(Merchant merchant) {
         String returnMessage = "";
         String merchantNumberMsg = "";

       if( merchant == null || merchant.getMerchantID()== null){
          throw new ResourceNotFoundException("Empty", "Missing Data Exception");
      } else {
           try{

          merchant.setPassword(passwordEncoder.encode(merchant.getPassword()));
          merchant.getDirectors().stream().forEach(director -> director.setMerchant(merchant));
          merchantRepository.save(merchant);
          String merchantNum = Long.toString(merchant.getMerchantNumber());
          returnMessage = "Merchant Created Successfully";
          merchantNumberMsg = merchantNum;

           }catch (DataIntegrityViolationException ex) {

            returnMessage = ex.getCause().getMessage();
             merchantNumberMsg = "Unable to issue a Merchant Number";
           }

       return new ResponseMerchantQuery(merchantNumberMsg, returnMessage);
}

}

商家实体:

 @Entity
    @Table(name = "Merchant", 
    uniqueConstraints = 
              {
                    @UniqueConstraint(columnNames = "userName"),
                    @UniqueConstraint(columnNames = "phoneNumber"),
                    @UniqueConstraint(columnNames = "merchantID"),
                    @UniqueConstraint(columnNames = "email")
            }
    )
    public class Merchant implements Serializable{
         @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private int merchantNumber;

    @Cascade({org.hibernate.annotations.CascadeType.ALL}) 
    @OneToMany(mappedBy = "merchant")
     private List<Director> directors;

    @NotBlank
    private String userName;

    @NotBlank
    private String phoneNumber;

    @NotBlank
    @Size(min = 5, max = 20, message = "Please enter between {min} and {max} characters.")
    private String password;

    @org.hibernate.validator.constraints.Email(message = "Invalid Email")
    @Size(max = 254, message = "Your email address is too long")
    @Column @NotNull(message = "Please, enter the user email")
    private String email;
  ...

 }

Merchant Repository:

public interface MerchantRepository extends CrudRepository<Merchant, String> {

}

0 个答案:

没有答案