Hibernate未生成正确的ID

e0uiprwp  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(122)

我正在开发我的Spring Boot 项目,并使用data.sql文件加载一些测试数据到我的数据库。我使用的是H2内存数据库。问题是,当我试图使用我的应用程序添加一些数据时,hibernate在id应该在的地方设置了default参数。因此,我有这个例外:

Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.COMPANY_BRANCH(ID) ( /* key:1 */ CAST(1 AS BIGINT), '500000 RUB', 'Rosebank', 'South Africa', '987-364-9956', 'Bultman', '7945')"; SQL statement:
insert into company_branch (company_branch_budget,company_branch_city,company_branch_country,company_branch_street,company_branch_zip_code,company_branch_phone_number,id) values (?,?,?,?,?,?,default) [23505-214]

这是查询休眠生成

insert 
    into
        company_branch
        (company_branch_budget,company_branch_city,company_branch_country,company_branch_street,company_branch_zip_code,company_branch_phone_number,id) 
    values
        (?,?,?,?,?,?,default)

看起来它设置为默认id 1,但这个id已经被data.sql文件中的第一行所采用。
下面是我的一个例子:

@Entity
@Table(name = "COMPANY_BRANCH")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CompanyBranch {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Convert(
            converter = MoneyConverter.class
    )
    @Column(name = "COMPANY_BRANCH_BUDGET", length = 63)
    private Money budget;

    @Embedded
    @NotNull
    @AttributeOverrides({
            @AttributeOverride(name = "city",
                column = @Column(name = "COMPANY_BRANCH_CITY")),
            @AttributeOverride(name = "zipCode",
                column = @Column(name = "COMPANY_BRANCH_ZIP_CODE")),
            @AttributeOverride(name = "street",
                column = @Column(name = "COMPANY_BRANCH_STREET")),
            @AttributeOverride(name = "country",
            column = @Column(name = "COMPANY_BRANCH_COUNTRY"))
    })
    private Address companyBranchAddress;

    @NotNull
    @NotBlank(message = "Номер телефона не должен быть пустым")
    @Pattern(regexp = "^(\\+\\d{1,3}( )?)?((\\(\\d{1,3}\\))|\\d{1,3})[- .]?\\d{3,4}[- .]?\\d{4}$",
            message = "Неверный формат номера!")
    @Column(name = "COMPANY_BRANCH_PHONE_NUMBER")
    private String phoneNumber;

    @OneToMany(mappedBy = "companyBranch", cascade = CascadeType.ALL)
    private Set<Department> departments = new HashSet<>();

    public void addDepartment(Department department) {
        this.departments.add(department);
        department.setCompanyBranch(this);
    }

    public void removeDepartment(Department department) {
        this.departments.remove(department);
        department.setCompanyBranch(null);
    }
}

这是我的dto类

@NoArgsConstructor
@AllArgsConstructor
@Data
public class CompanyBranchDTO {
    private Long id;

    @NotNull
    @Valid
    private Money budget;

    @NotNull
    @Valid
    private Address companyBranchAddress;

    @NotNull
    @NotBlank(message = "Номер телефона не должен быть пустым")
    @Pattern(regexp = "^(\\+\\d{1,3}( )?)?((\\(\\d{1,3}\\))|\\d{1,3})[- .]?\\d{3,4}[- .]?\\d{4}$",
            message = "Неверный формат номера!")
    private String phoneNumber;
    private Set<DepartmentDTO> departments;
}

我的控制器就是这样工作的

@GetMapping("/new")
    public String createBranch(Model model) {
        CompanyBranchDTO companyBranchDTO = new CompanyBranchDTO();

        model.addAttribute("companyBranchDTO", companyBranchDTO);
        return "createCompanyBranch";
    }

    @PostMapping("/new")
    public String createBranchPost(@ModelAttribute("companyBranchDTO") @Valid CompanyBranchDTO companyBranchDTO,
                                   BindingResult bindingResult) {
        if (bindingResult.hasErrors()) return "createCompanyBranch";

        CompanyBranch companyBranchEntity = companyBranchMapper.toEntity(companyBranchDTO);
        companyBranchService.createOrUpdateCompanyBranch(companyBranchEntity);

        return "redirect:/companyBranches";
    }

它是从html表单中获取dto,然后将其转换为实体。这是实体在我的服务类中保存的方式

public CompanyBranch createOrUpdateCompanyBranch(CompanyBranch companyBranch) {
        return  companyBranchRepository.saveAndFlush(companyBranch);
    }

我认为这个问题是连接到我的data.sql文件不知何故,但我不知道如何。也许有人知道答案。我会很感激的

envsm3lx

envsm3lx1#

感谢Evgenij Ryazanov和Mar-Z提供的有用链接(首先是second)。正如我在评论中所说,问题出在我的data.sql文件中,简而言之-我需要从那里删除id插入,因为它不允许生成正确的id。

相关问题