Home > Software design >  Hibernate how to get Identity field value before save when using a custom ID generator?
Hibernate how to get Identity field value before save when using a custom ID generator?

Time:01-20

I've seen similar questions but not got my answer.

I was using Hibernate @SequenceGenerator to generate value for the id field of an Entity, and the id field value was only available after save, which makes sense as the sequence value is got at DB level when saving then returned to the application.

Now I created a custom ID generator to generate SnowFlake ID. The ID generator works in application layer without any dependency, and works properly when saving an entity. However I noticed that the id value is still not assigned until saved. Is there a way to tell Hibernate to assign the value as soon as the Entity is instantiated?

ShipmentEntity.java

@Entity
@Table(name = "shipment")
public class ShipmentEntity {

    @Id
    @GenericGenerator(name = "shipment", strategy = "com.example.domain.id.SnowFlakeIdGenerator")
    @GeneratedValue(generator = "shipment")
    @Column(name = "id")
    private Long id;
    ...
}

In service I new a ShipmentEntity and expected to get the Id value before saving but it's null:

ShipmentService.java

@Service
@AllArgsConstructor
public class ShipmentService {

    private ShipmentRepository shipmentRepository;

    public ShipmentEntity createShipment(CreateShipmentParam createShipmentParam) {
        ShipmentEntity shipment = new ShipmentEntity();
        System.out.println(shipment.getId()); // prints `null` here
        shipment.setShippingDate(createShipmentParam.getShippingDate());
        ...
        return shipmentRepository.save(shipment);
    }

Update: I know I can call the ID generator and set the Id value manually after instantiate the entity, I just thought those fancy annotations might do it for me. If it's impossible, please let me know.

CodePudding user response:

id will be available after save, because id will generated on save entity.

Another way. You can create separate method for generating id, then call it and set id manually.

Or you can use uuid as id. And you always cant generate and set it manually

CodePudding user response:

If you want the identifier assigned before calling persist(), then just do it yourself when you instantiate the object! You don't need a Hibernate id generator for that. Just get rid of @GeneratedValue and @GenericGenerator.

And Hibernate doesn't know about anything your object until you call persist(), so how could it possibly assign an id to it?

  • Related