1

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 ?

5
  • 1
    Can you show how you are saving object? Commented Jul 17, 2018 at 5:04
  • I solve this by @Entity class implements Persistable Commented Jul 17, 2018 at 5:29
  • and who knows what is Persistable? Commented Jul 17, 2018 at 6:21
  • JPA has no such "save" method. JPA has "persist" and "merge" Commented Jul 17, 2018 at 7:36
  • Does this answer your question? Force Hibernate Insert Without Select Statements Commented Oct 15, 2020 at 8:14

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

But my Repository class extends JpaRepository<T, Long> , JpaSpecificationExecutor<T> , but JpaRepository and JpaSpecificationExecutor does not provide persist() ? while it provide save()
1

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.

Comments

1

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.

1 Comment

I undelete the answer so somebody may get benifitted..thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.