Last active
January 4, 2019 08:27
-
-
Save dbrugne/1fe8aeba5eeb859c68c9ac9e5672865a to your computer and use it in GitHub Desktop.
Run a direct SQL native query without JPA repository
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.innovatm.database; | |
// ... | |
@Component | |
public class NativeQuery { | |
@Autowired | |
private JpaTransactionManager jpaTransactionManager; | |
public NativeQuery() { | |
EntityManagerFactory emf = this.jpaTransactionManager.getEntityManagerFactory(); | |
EntityManager em = emf.createEntityManager(); | |
// prepare query | |
Query query = em.createNativeQuery("INSERT INTO \"public\".\"my_table\" VALUES (?)"); | |
query.setParameter(1, 1000); | |
// execute query inside a transaction | |
em.getTransaction().begin(); | |
query.executeUpdate(); | |
em.getTransaction().commit(); | |
// free up EntityManager | |
em.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment