You can remove the generator from the entity.
@Entity
public class Entidade{
@Id
//@GeneratedValue <-- Remover
private Long id;
...
Another simpler solution would be to change the class to annotate the method and not the property and change the IdGenerator
for none ( in case you will add on hand ).
In this case you don’t need to take the trouble to create a IdGenerator
in hand.
@Entity
public class Pai {
private Long id;
@Id
public Long getId() {
return id;
}
}
public class Filho extends Pai {
@Override
@Id
public Long getId() {
return super.getId();
}
}
If I have to create one IdGenerator
recommend the following:
Extend an existing one and change its parent class to generate the id exclusively for the class you want. But I don’t recommend this solution because of the coupling.
@Entity
public class Pai {
@Id
@GeneratedValue(generator = "mygenerator")
@GenericGenerator(
name = "mygenerator",
strategy = "br.MyGenerator")
private Long id;
public Long getId() {
return id;
}
}
class MyGenerator extends SequenceGenerator {
@Override
public Serializable generate(SessionImplementor session, Object obj) {
if (!obj.getClass().equals(Filho.class)) {
return super.generate(session, obj);
}
return ((Filho) obj).getId();
}
}
Guy found something in the sense of rewriting himself
generator
ofHibernate
, I will check because it may be an interesting solution and I will post to colleagues how to do...– Macario1983
Just one question, and in case I have implemented the
get
andset
of Id in the parent class as final?– Macario1983
If this is the end of the id method in the parent class you can only use the last solution.
– Leonardo Otto