简体   繁体   中英

Basic CRUD operations with entitymanager

I made a REST service project where i was performing CRUD operations via DriverManager.getConnection(url,user,pass).

Now my asignment changed to defining the connection in Jboss 7.1.1 and that is working (Testing the datasource in the Jboss admin console returns positive and the sqljdbc driver also appears active in the Activity Monitor of MS SQL Server Management Studio).

I am suposed to use the EntityManager to run the native querys i used with the old project without generating entities or writing queries using entities(Thats for the next asignment).

I wrote a small test code from what i found in my research, the following:

public class Test {

 @PersistenceContext(unitName="InternshipIS") protected EntityManager entityManager;
public void getQuerys(){

    String sqlQuery = "SELECT * from InternshipIS.dbo.Employee";
    Query q = entityManager.createNativeQuery(sqlQuery);
    System.out.println(q.getResultList().get(2));
}

When it reaches the following line, it throws a NullPointerException.

Query q = entityManager.createNativeQuery(sqlQuery);

Please let me know where i'm screwing up and if the full stacktrace / persistence.xml / standalone.xml or anything else is needed in order to add them to my post.

PS: This is not a maven project. It was a Dynamic Web Project that i converted to JPA when this asignment started.

I fixed the problem by making the following adjustments:

public class Test {
public void getQuerys(){
    EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("InternshipIS");
    EntityManager em = emFactory.createEntityManager();
    String sqlQuery = "SELECT * FROM Employee";
    Query q =   em.createNativeQuery(sqlQuery); 
 }
}
 String sqlQuery = "SELECT * from InternshipIS.dbo.Employee";

In this query, Select * from InternshipIS is understandable for sql. But I think you are concatenating database name with table in query. Which is not working and query returning null value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM