Reputation: 822
I'm trying to insert a value into a database with type String in ID.
@Entity
@Table(name = "xpto_version_map")
public class XptoVersionMap implements Serializable {
@Id
@Column(name = "uniq_name", unique = true, nullable = false)
private String uniq_name;
...
When trying to save a new XptoVersionMap() like:
XptoVersionMap xptoVersionMap = new XptoVersionMap();
xptoVersionMap.setUniqName("XPTO-1");
xptoVersionMap.setValue("value2");
xptoVersionMapRepository.save(xptoVersionMap);
Will throw:
org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find xxx.api.database.entity.XptoVersionMap with id XPTO-1; nested exception is javax.persistence.EntityNotFoundException: Unable to find xxx.api.database.entity.XptoVersionMap with id XPTO-1.
I've tried different solutions, but unless I can make a native query to insert the value, I can't have a way to tell Hibernate that I want to just check if the @Id (uniq_name) exists, if not insert the new value and not to throw an exception.
Upvotes: 0
Views: 834
Reputation: 7071
That's how Hibernate works by default. It assigns an automated generated ID when you do save method and ID is not set. If there is an ID it tries to update it (what happens in your case).
save Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.
You can do a workaround for example by using persist and @PrePersist
@PrePersist
void generateId() {
if (uniq_name == null) {
uniq_name = GENERATE_SOME_UNIQUE_ID_SO_IT_DOESN'T_BREAK();
}
}
And then use xptoVersionMapRepository.persist(xptoVersionMap);
Or you can write your own generator with something like that:
@GenericGenerator(name = "my_generator", strategy = "package.CustomGenerator")
@GeneratedValue(generator = "my_generator")
And then create a class CustomGenerator that implements IdentifierGenerator and create the required methods.
Upvotes: 1