无法将事务Springboot提交到Mysql

时间:2018-08-02 04:26:37

标签: java mysql spring spring-boot mysql-workbench

我制作一个这样的项目:https://grokonez.com/spring-framework/spring-boot/use-spring-jpa-mysql-spring-boot并正常运行

但是当我在MYSQL中用column(name =“ id”)更改“ id”时。我对邮递员进行测试时出错。

{
"timestamp": 1533183310810,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.transaction.UnexpectedRollbackException",
"message": "JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction.",
"path": "/save"
}

我更改了Customer类:

@Id
@Column(name="id")
private long id;

public Customer(long id , String firstName, String lastName){
    this.id=id;
    this.firstName=firstName;
    this.lastName=lastName;
}

在WebController类中,我用id,名字,姓氏保存了一个客户

@RequestMapping("/save")
public String process(){
    repository.save(new Customer(1,"Jack", "Smith"));
    return "Done";
}

如何保存具有ID的客户?

2 个答案:

答案 0 :(得分:0)

在该文章中,他们将GenerationType.AUTO策略用于ID列。这意味着ID列中的值将自动生成。因此,要保存记录,您无需显式提供ID。

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

保存应如下:

repository.save(new Customer("Jack", "Smith"));

这样做的好处是,您无需担心要分配的ID是否已分配给任何其他记录。 JPA负责为所有新记录分配一个新ID。

答案 1 :(得分:0)

您可能会收到此错误,因为您要插入的ID可能已经在数据库中。如果您尝试插入具有不同ID的数据,则代码将起作用。

尽管我们通常遵循上述共享方法(@GeneratedValue(strategy = GenerationType.AUTO))。