mysql - 存储实体时出现 DataIntegrityViolationException

标签 mysql spring-mvc spring-boot spring-data spring-data-jpa

我正在使用 Spring Boot 和 MySQL 作为数据库编写简单的 Web 应用程序。代码如下

我有一个实体用户:

@Entity
@IdClass(UserKey.class)
public class User {

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Item> items;
    private String fullName;
    @Id
    private String principalId;
    @Id
    @Enumerated(EnumType.STRING)
    private LoginProvider loginProvider;
}

我还有一个 UserService:

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    public User getCurrentUser() {
        try {
            return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }

    @Transactional
    public void addItemToUser(Item item) {
        User currentUser = getCurrentUser();
        if (!currentUser.getItems().contains(item)) {
            currentUser.getItems().add(item);
            userRepository.save(currentUser);
        }
    }
}

还有一个 Controller :

@Controller
public class UserController {
PostMapping(value = "/addItem/{id}")
    @ResponseStatus(value = HttpStatus.OK)
    public void addItemToUser(Map<String, Object> model, @PathVariable int id) {
        userService.addItemToUser(itemService.getItem(id));
    }
}

这是我的 Item 类:

@Entity
public class Item {

    @Id
    @GeneratedValue
    private int id;
    @Enumerated
    private Category category;


    public Item() {
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Category getCategory() {
        return category;
    }

    public void setCategory(Category category) {
        this.category = category;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Item item = (Item) o;

        return id == item.id;
    }

    @Override
    public int hashCode() {
        return id;
    }
}

这是我的存储库:

public interface UserRepository extends CrudRepository<User, Integer> {}

Controller 和一切工作正常,但有时当我尝试使用我的用户项目更新列表时会出现以下错误:

    2018-04-03 17:09:53.814 ERROR 24265 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '23942983472937-FACEBOOK-2' for key 'PRIMARY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_121]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_121]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_121]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_121]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.42.jar:5.1.42]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490) ~[mysql-connector-java-5.1.42.jar:5.1.42]

如何消除这个错误?

最佳答案

如果您发布了您的Item,将会有所帮助。类(class)。我的猜测是您需要实现 equals(Object obj) & hashCode()方法让您的Set<Item>没有重复项。

关于mysql - 存储实体时出现 DataIntegrityViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49632768/

相关文章:

php - 如果不存在则创建否则更新表

java - 如何将 Spring MVC 重定向到类似 url 的 {...}

mysql - 条件连接 MySQL

java - Spring 发布订阅?

java - Spring MVC 404 错误

gradle - Spring Boot Gradle插件,应用程序插件和Gradle 2.3包装器

spring-boot - WebSocketDeploymentInfo,将使用默认的worker

java - 使用 Spring Boot 进行多个 REST 调用

mysql - 在 SQL oracle 中对特定列使用 replace with select 语句

mysql - mysql 列值中的 (NULL) 和空值之间的区别