Home > Enterprise >  How to automatically generate id in sequence in spring jpa?
How to automatically generate id in sequence in spring jpa?

Time:05-25

I need to make a one-to-many sequence as follows:

for example:

category sub category
1 1
1 2
2 1
2 2
2 3
3 1

Data model:

enter image description here

Java code/Mapping:

Category class

package br.com.bank.adapter.repository.entity;

import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Entity
@Getter
@Setter
@Table(name = "category")
public class CategoryEntity {

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

@Column(name = "name", nullable = false)
private String name;

@Column(name = "update_at")
private LocalDateTime update;

@OneToMany(mappedBy = "category", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<SubCategoryEntity> subCategoryEntity = new HashSet<>();

}

SubCategory class

package br.com.bank.adapter.repository.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Getter
@Setter
@Table(name = "sub_category")
public class SubCategoryEntity {

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

@Column(name = "name", nullable = false)
private String name;

@Column(name = "update_at")
private LocalDateTime update;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", nullable = false)
private CategoryEntity category;

}

With the code above, I'm getting the following result:

category sub category
1 1
1 2
2 3
2 4
2 5
3 6

CodePudding user response:

Try with the following config to have your own sequence set up by JPA Vendor (ex Hibernate).

public class SubCategoryEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceSubCategoryId")
    @SequenceGenerator(name = "SequenceSubCategoryId", sequenceName = "SUB_CATEGORY_SEQ")
    private Long id;

    ....
    }

This way the id would be retrieved from the same sequence created in database and will always be increased by 1 in every new request.

This would work if you have set up the property

spring.jpa.hibernate.ddl-auto with one of the following values create, create-drop, update so that hibernate is allowed to create this sequence in the schema automatically for you.

If you don't have this property configured this way you also need to execute the DDL script in your database to create the sequence named SUB_CATEGORY_SEQ

  • Related