gpt4 book ai didi

java - Hibernate 序列在更新期间不会为主键 id 生成连续的数字

转载 作者:行者123 更新时间:2023-12-01 18:16:48 26 4
gpt4 key购买 nike

我有一个带有 spring 数据和 hibernate 的 spring boot 应用程序,用于将数据保存到 MySQL 数据库。我有一张用户表和一张地址表,它们之间的关系太多。当我保存数据时,自动生成的主键会正确生成,但是当我更新地址表(向用户添加第二个地址)时,为第二个用户生成的主键不连续。

这些是我的实体。

@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_generator")
@SequenceGenerator(name="user_generator", sequenceName = "user_seq")
@Column(name = "user_id")
private Long id;
@Unique
@Column(nullable = false)
private String username;
@Column(nullable = false)
private String firstname;
@Column(nullable = false)
private String lastname;
private String password;

@OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Address> address;
private Boolean active;
private String mobile;
private String home;

public User() {
}
@Entity
@Table(name = "address")
public class Address {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_generator")
@SequenceGenerator(name = "address_generator", sequenceName = "address_seq")
@Column(name = "adress_id")
private Long id;
@Column(nullable = false)
private String street1;
private String street2;
@Column(nullable = false)
private String city;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;

这是更新方法

   @Override
public UserDTO updateUser(UserDTO userDto) {

User user = userMapper.getUserEntity(userDto);
user.getAddress().forEach(a->a.setUser(user));
User updatedUser = userRepository.save(user);
return userMapper.getUserDTO(updatedUser);
}


这是我的有效负载。 id=2 的地址已保存,我添加了第二个地址。

    {
"id": 2,
"username": "test@gmail.com",
"firstname": "lana",
"lastname": "Lee",
"address": [
{
"id": 2,
"street1": "344",
"street2": "abcd",
"city": "mycity"
},
{
"street1": "7",
"street2": "cde",
"city": "mycity"
}
],
"active": false,
"mobile": "1232211441"
}

当我更新时,这就是地址表的 id 列的样子。新添加的地址是52,而不是5。

最佳答案

您必须根据 SequenceGenerator Javadoc 更改默认分配大小设置为:

allocationSize

public abstract int allocationSize (Optional)

amount to increment by when allocating sequence numbers from thesequence.

Default: 50

尝试将其设置为 1 或任何适合您需要的值。

关于java - Hibernate 序列在更新期间不会为主键 id 生成连续的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60350386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com