Spring jpa在唯一属性上重复记录插入异常

时间:2016-11-07 12:27:26

标签: jpa spring-boot

第一次personService.addPerson(person);在再次插入类似记录时工作正常,它会抛出此异常:

"com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Patient' for key 'Role'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_112]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_112]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_112]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_112]"

我想根据电子邮件,person表(电子邮件)和personrole表(角色)中的角色,在数据库中保留唯一的行。

- 表格

CREATE TABLE PersonRole(Role_ID INT PRIMARY KEY AUTO_INCREMENT,Role VARCHAR(50) unique);

并且

CREATE TABLE Person(Person_ID INT PRIMARY KEY AUTO_INCREMENT,Email VARCHAR(50) unique);

- 人物实体

@Entity

public class Person implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true, nullable = false)
private int person_ID;

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "Role_ID")
private Personrole personrole;

............. - 人员实体

@Entity

public class Personrole implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true, nullable = false)
private int role_ID;

@Column(length = 50)
private String role;

@OneToMany(mappedBy = "personrole",cascade = CascadeType.ALL)
private List<Person> persons;

.............................. - 这是我的专栏

@Controller

public class UserController {

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signUp(@Valid Person person, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
        model.addAttribute("message", result.getAllErrors() + "\n DOB is: " + person.getDob());
        return "fail";
    }

    Date date = new Date();
    person.setRegister_Date(date);

    personService.addPerson(person);

---提前致谢---

0 个答案:

没有答案