Skip to main content

Posts

Showing posts with the label Hibernate

Hibernate: How to Save Entity With User Specified Id

Spoiled by Hibernate, we usually let Hibernate to generate the id for the entity object, like the following: @MappedSuperclass public abstract class GuidEntity { @Id @GeneratedValue ( generator = "uuid2" ) @GenericGenerator ( name = "uuid2" , strategy = "uuid2" ) @Column ( unique = true , nullable = false ) private String id ; //getter, setter, ... } When you calls .save or .persist via Hibernate session or EntityManager, an id is generated automatically for the entity object using the specified generator by Hibernated. This is a neat feature but also means you don’t have control on what the value of the id is. What if you want Hibernate to use your specified id to persist the entity object? It requires a little twist. 1. Why do you even want to do this? Simple, imagine your application has tons of data and it support bulk data import/export via xls, csv, whatever format you like. Your customer pl...