Skip to content

Instantly share code, notes, and snippets.

@dbrugne
Last active January 4, 2019 08:27
Show Gist options
  • Save dbrugne/1fe8aeba5eeb859c68c9ac9e5672865a to your computer and use it in GitHub Desktop.
Save dbrugne/1fe8aeba5eeb859c68c9ac9e5672865a to your computer and use it in GitHub Desktop.
Run a direct SQL native query without JPA repository
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