Skip to content
Advertisement

Spring jpa database connection for native query

I have a spring application that have to connect to a sql server db. There are no @Entity class and there ate no @Repository because the tables and the columns of the tables are unknown to the application. I have created a class and used an entity manager to execute queries, but I’m not sure this is the best choice in this case:

@Service
public class MyRepo {
private final EntityManager entityManager;

public MyRepo(@Qualifier("myEntityManagerFactory") EntityManager _entityManager){
    entityManager = _entityManager;
}

public void execQuery(){
    String queryStr = "select TOP (10) * from [MyTable]";
    Query query = entityManager.createNativeQuery(queryStr);
    List<Object> queryRes = query.getResultList();
}

}

My question is if it is more correct, in my scenario, to create a “classic” connection to the db instead of create an entity manager (since there are no entities);
something like:

Connection con=DriverManager.getConnection("connection string","user","password");
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select TOP (10) * from [MyTable]");  

Thanks a lot for any suggestion.

Advertisement

Answer

You are misusing JPA just to hold the connection.

You should go for JdbcTemplate instead.

Don’t use the starter for Spring Data JPA, instead use the spring-boot-starter-jdbc (Not Spring Data JDBC). Get a JdbcTemplate or a NamedParameterJdbcTemplate injected and use them to execute your SQL code.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement