springrest没有按正确的顺序设置id值

nwlls2ji  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(220)

我的api使用spring5版本,产品实体与productsupplier和category有一个二对一的关系,我不得不提到我使用jpa进行crud操作。我没有问题提出一个产品对象与两个依赖,但问题发生时,我再次发布另一个对象,下一个产品id值没有正确的顺序开始,下一个id是3倍大的最后一个一样(1,4,7,10),而不是(1,2,3,4) 当我的api在生产中时,这就产生了一个问题,我想知道如何解决它
产品

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @ManyToOne( cascade = CascadeType.ALL)
    @JoinColumn
    private Category category;
    private int price;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn
    private ProductSupplier productSupplier;

//setters and getters

类别

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String CategoryName;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,mappedBy = "category")
@JsonBackReference
private List<Product> products;
//setters and getters

产品供应商

@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @JsonBackReference
    @OneToMany(mappedBy="productSupplier",fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<Product> product;
//setters and getters

post方法

@PostMapping
    @ResponseStatus(HttpStatus.ACCEPTED)
    public ResponseEntity<Product> postProduct(@RequestBody Product product){
        productRepository.save(product);
       return ResponseEntity.ok(product) ;
    }

我发布的2个对象

[
    {
        "id": 1,
        "name": " micro type charger",
        "category": {
            "id": 2,
            "categoryName": "phone"
        },
        "price": 0,
        "productSupplier": {
            "id": 3,
            "name": "samsung"
        }
    },
    {
        "id": 4, //id of new product must be 2 not 4
        "name": " micro type charger",
        "category": {
            "id": 5,
            "categoryName": "phone"
        },
        "price": 0,
        "productSupplier": {
            "id": 6,
            "name": "samsung"
        }
    }
jm2pwxwz

jm2pwxwz1#

如果您没有从数据库中提供任何自定义序列名称,hibernate将使用其默认的db序列来生成主键值。
在您的例子中,使用默认的db序列休眠,因为您没有提供任何自定义序列名称。每当您在数据库中持久化一个新的产品对象时,category和productsupplier的另外两个对象也会并行地持久化。这就是为什么,为产品生成的id是1,那么category的id将生成为2,productsupplier的id将生成为3。
当您正在分配第二个产品对象时,hibernate序列的计数器现在是4。因此,它显示4而不是2。

zlhcx6iw

zlhcx6iw2#

您应该使用@generatedvalue(strategy=generationtype.identity)。在Hibernate5中,应该避免generationtype.auto。请看这篇文章。

相关问题