Overwrite Primary Hibernate Key Generator

Asked

Viewed 400 times

0

I would like to know if you can overwrite the generator of a primary key in Hibernate, in my case I make a superior class where the id, and the rest extend from her.

In my case this subclass, which extends from this that contains the primary key, will receive the key as input by the user.

The problem is that after sending the dice to save by Hibernate, the sequence Postgresql inserts a value in the database, which is sequence generator.

Does anyone have any suggestions for me to work around this problem if it interferes with class structure?

1 answer

1


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 of Hibernate, I will check because it may be an interesting solution and I will post to colleagues how to do...

  • Just one question, and in case I have implemented the get and set of Id in the parent class as final?

  • 1

    If this is the end of the id method in the parent class you can only use the last solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.