Override Hibernate Primary Key Generator

0

I would like to know if you can override the generator of a primary key in Hibernate, in my case I make a top class where id is, and the rest extend it.

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

The problem is that after sending the data saved by Hibernate, the sequence of PostgreSQL inserts a value in the database, which is sequence generator .

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

    
asked by anonymous 03.04.2014 / 03:17

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 to none (in this case you'll add it in hand). In this case you do not have to create a IdGenerator on 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 you have to create a IdGenerator recommend the following: Extend an existing and change your parent class to generates the id exclusively for the class you want. But I do not 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();
    }
}
    
03.04.2014 / 14:46