How to override @SequenceGenerator(name = “idGenerator”, sequenceName = “HIBERNATE_SEQUENCE”, allocationSize = 50)

[亡魂溺海] 提交于 2021-01-27 23:56:03

问题


Normally Id column is as follows and it works perfectly fine and generated sequence values

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idGenerator")
@SequenceGenerator(name = "idGenerator", sequenceName = "HIBERNATE_SEQUENCE", allocationSize = 50)
@Column(name = "ID")
public Long getId()
{ return mId; }

Now what I want is if in program I set xyz.setId(200) it should save Id as 200 instead of one generated by sequence.Now how can I acheive this? I also want to use both attributes sequenceName = "HIBERNATE_SEQUENCE", allocationSize = 50.


回答1:


Finally after 1 day of utilized time I digged into the jar and I got the solution. I used @GenericGenerator(name = "idGenerator", strategy = "com.jayash.domain.UseExistingOrGenerateIdGenerator")

public class UseExistingOrGenerateIdGenerator extends SequenceHiLoGenerator {
    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);
        return id != null ? id : super.generate(session, object);
    }

    @Override
    public void configure(Type type, Properties params, Dialect dialect) throws MappingException {

        params.put(org.hibernate.id.SequenceGenerator.SEQUENCE, "HIBERNATE_SEQUENCE");


        params.put(SequenceHiLoGenerator.MAX_LO, String.valueOf("49"));

        super.configure(type, params, dialect);
    }

}

And Yipee Its working great




回答2:


That's a tricky problem. Generally speaking the IDs are generated at the time the transaction commits. Which is one reason JPA's persist() doesn't return a database PK.

I suppose you could at a @PostPersist listener to change the ID of the object if there is a manual ID. You'd have to commit that change and reread the oject to get it into a consistent state if you want to use the object after that.

Spec reference: "3.2.4 Synchronization to the Database: The state of persistent entities is synchronized to the database at transaction commit. This synchronization involving writing to the database any updates to persistent entities... including assignment of a new value to a persistent property or field... The flush method can be used by the application to force synchronization."



来源:https://stackoverflow.com/questions/30194845/how-to-override-sequencegeneratorname-idgenerator-sequencename-hiberna

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!