简体   繁体   中英

How to use auto increment ID to set another variable in the entity in JPA

I have an auto increment key in my entity.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;

I have another variable data in the object which is created based on the id mentioned above.

For ex:

private String data;

public String setData(String str){
   this.data = str + this.getId();
}

How can I set data variable while creating the object.

I have used PrePersist annotation before which is not useful in this case.

You can't generate the id before saving the actual document . All you can do is, save the document, set the data part and save it again eg

Document saved = jpaRepository.save(document);
saved.setData(saved.getId() + "blah");
jpaRepository.saveAndFlush(saved);

You can execute these steps under a transaction to maintain consistency.

You would have to use a database trigger as the value of an ID set through IDENTITY isn't available until after the insert occurs. You would then need to use a provider specific method to get the value set through a trigger, such as EclipseLink's eclipse.org/eclipselink/documentation/2.5/jpa/extensions/… . Or you can use persist, flush to force the insert which should obtain the ID value, and then update your field value. An alternative is to use table sequencing or some other generation type that allows preallocation, so the id value is available on persist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM