Spring Data JPA how to ignore select table before

2019-08-16 08:18发布

My Entity Class has id field and it using @Id and it's strategy is null. Default Strategy is @GeneratedValue(strategy = GenerationType.AUTO)).

when I call the JPA save method, it always invoke sql select before insert into ,query log is like bellow:

First Query:

Hibernate: select dataeviden0_.id as id1_0_0_, dataeviden0_.block_hash as block_ha2_0_0_ from table1 dataeviden0_ where dataeviden0_.id=?

Second Query:

Hibernate: insert into table1 (block_hash, id) values (?, ?)

I could control the id myself, I want the jpa ignore select before insert ,how to do ?

3条回答
对你真心纯属浪费
2楼-- · 2019-08-16 08:34

bulk-inserting-existing-data-preventing-jpa-to-do-a-select-before-every-insert solve my question, the entity implement Persistable,and override isNew(){ return false; } , it will ignore select before insert, because

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }

it the save method will judge entityInformation.isNew(entity) false, and reach my goal.

查看更多
做个烂人
3楼-- · 2019-08-16 08:46

You can use the persist() method rather than save().

https://forum.hibernate.org/viewtopic.php?f=1&t=1011405

However, unlike save(), persist() does not guarantee that the identifier value will be set immediately on the persisted instance.

https://forum.hibernate.org/viewtopic.php?t=951275

Taken from here Force Hibernate Insert Without Select Statements

查看更多
唯我独甜
4楼-- · 2019-08-16 08:52

The now no longer deleted answer by @Alien is basically correct. The statement comes from Spring Data JPA using merge and if you'd use persist it should go away.

For this, you'd have to expose the persist method in your repository. Which should be easy with a custom method implementation and an injected EntityManager. If you only save new instances with that repository you can even provide the custom implementation for the existing save method if you want.

查看更多
登录 后发表回答