I am trying to create a custom repository in spring boot using JPA + Hibernate. I am new to JPA and Hibernate, so till now I managed to create a table in the DB and push some data to it.
I would like to know if a table exist before creating it or number of rows in a table but I am not able to find any material on it.
Following is the class to create table
package repository;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.springframework.stereotype.Repository;
@Repository
public class CustomRepository {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("TestPersistence");
public void createTable(String tableName) {
EntityTransaction txn = null;
try {
EntityManager entityManager = entityManagerFactory.createEntityManager();
txn = entityManager.getTransaction();
txn.begin();
entityManager.createNativeQuery("CREATE TABLE " + tableName + " (PersonID int, LastName varchar(255))")
.executeUpdate();
txn.commit();
} catch (Throwable e) {
if (txn != null && txn.isActive()) {
txn.rollback();
}
throw e;
}
}
}
I tried
String sqlQuery = "SELECT COUNT (*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'my_table'";
or
String sqlQuery = "SELECT TABLE_NAME, TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES"
With entityManager.createQuery(sqlQuery).getResultList();
as well but they are giving error.
Any suggestion on how to achieve this would be helpful.