JPA persist a new entity with or without a set id

Viewed 3489

I am using JPA to persist entities to my database. The Id column is represented by the Persistable class

@MappedSuperclass
public class Persistable {

@Id
@GeneratedValue(generator = "CustomGenerator")
@GenericGenerator(name="CustomGenerator", strategy = "parohia.imported.domain.UseExistingOrGenerateIdGenerator")
Long id;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

}

My custom generator is this:

public class UseExistingOrGenerateIdGenerator extends IdentityGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SessionImplementor session, Object object)
        throws HibernateException {
    // TODO Auto-generated method stub
    Serializable id = session.getEntityPersister(null, object)
            .getClassMetadata().getIdentifier(object, session);
    return id != null ? id : super.generate(session, object);
}

}

My goal is to persist entities which have an id using that id and entities which do not have an id with a generated id. Is this possible?

 EntityManager entityManager = databaseService.getEntityManager();
 entityManager.getTransaction().begin();
 entityManager.persist(new Persoana(5000L,"test","test"));
 entityManager.getTransaction().commit();
 entityManager.close();

When persisting an entity with no set id everything works fine. But when an id is set I get

org.hibernate.PersistentObjectException: detached entity passed to persist

0 Answers
Related