I made a class called SpecializationBean which has two private fields:
private ArrayList<SelectItem> specializationItems= new ArrayList<SelectItem>();
private String specializationName;
I have ofcourse a getter and setter for those two.
and a buildSpecializationList method which builds the specializationItems list: (I call this method in the getter):
public void buildSpecializationList(){
List<Object[]> specializations = null;
try{
Session mySession = HibernateUtil.getAdmSessionFactory().getCurrentSession();
Transaction transaction = mySession.beginTransaction();
String sql = "SELECT J_Specialization_ID, Specialization_Name_Ar FROM J_Specialization WHERE J_Department_ID = '1000001'";
Query query = mySession.createSQLQuery(sql).addScalar("id", Hibernate.LONG).addScalar("name", Hibernate.STRING);
specializations = query.list();
}
catch(Exception e){
e.printStackTrace();
}
this.specializationItems = new ArrayList<SelectItem>(90);
for(Object[] sp: specializations ){
this.specializationItems.add(new SelectItem(sp[0],(String) sp[1]));
}
}
The problem is that I get a null pointer exception which shows that the list specializations (defined in the buildSpecializationList()) is null. I have tried the query myself on the table and it returns a result. I also tried HQL query (istead):
String sqlQuery = "Select JSpecializationId, specializationNameAr FROM JSpecializationWHERE JDepartmentId = '1000001'";
Query q = mySession.createQuery(sqlQuery);
But still, I get a null pointer exception which shows that the query returns me null result. Do you have any suggestions?
For anyone who encounters this problem using Hibernate ...... creating a new class and rewriting the whole thing may actually solve the problem!!!
Related
I try to get all data in table(SELECT * FROM) mysql database, Using real time search, But not load data to table.
I called getAll("") method with empty String, But I can't get any value from my table.
public ArrayList<Titem> getAll(String text) throws SQLException, ClassNotFoundException {
Session session = HibernateUtil.openSession();
Query query = session.createQuery("FROM titem WHERE id = :id");
query.setParameter("id",text);
List<Titem> list = query.list();
ArrayList<Titem> entityList = new ArrayList<>();
for (Titem t:list
) {
Titem titem = new Titem(
t.getId(),
t.getName(),
t.getPrice()
);
entityList.add(titem);
}
return entityList;
}
You need to conditionally remove the where statement to stop filtering on that column, empty string or null values will also be matched against the data in the table. Or you could change the query to:
FROM titem WHERE (id = :id OR :id = '')
I am insert data in db is good. The problem is after inserted data i am trying to get last inserted data primary key column. But i can't how to solve this problem.
note : i am using jpql , Thanks
public void insertData(String hcpHceId) {
EntityManager em = getEntityManager();
em.getTransaction().begin();
// Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(:id)" );
Query query = em.createNativeQuery("INSERT INTO mdm_id (hcp_hce_id) VALUES(?)");
query.setParameter(1, hcpHceId);
query.executeUpdate(); // Successfully inserted data
List list = query.setMaxResults(1).getResultList(); // Error line
em.getTransaction().commit();
} catch (Exception error) {
error.printStackTrace();
logger.error(error.getMessage());
} finally {
em.close();;
}
}
You are trying to retrieve the list from the same execute query. Query is an immutable object. You must create a new query with the proper select statement, so you will be able to retrieve data from database.
After the executeUpdate, create the new query using, v.g. (as you did not show your entity graph, using native sql):
Query retQuery = em.createNativeQuery("SELECT hcp_hce_id FROM mdm_id LIMIT 1");
String id = (String) retQuery.getSingleResult();
assert(id == hcpHceId);
The method to execute a prossidure in the bank was created, but the same is giving this error:
Caused by: java.lang.IllegalArgumentException: Unknown parameter registration name [movimentoId]
public static void validaPedidoCarga(EntityManager em, String movimentoId){
StringBuilder sql = new StringBuilder()
sql.append('BEGIN ')
sql.append('ADM_SGV.SGV_SFA_PK005.VALIDA_PEDIDO_CARGA(:movimentoId); ')
sql.append('END;')
Query query = em.createNativeQuery(sql.toString())
query.setParameter("movimentoId", movimentoId)
try{
query.()
em.close()
}catch(NoResultException ex){
ex.printStackTrace()
}
}
If a procedure is already created into DB then just call that procedure passing the correct argument like,
Query query = sf.getCurrentSession()
.createSQLQuery(
"CALL Procedure_Name(:movimentoId)")
.addEntity(ClassName.class)
.setParameter("movimentoId", "ur_Id");
List result = query.list();
I am using a JPA query to get a result set, then within the same class, I would like to conditionally get more data. Here's what it looks like:
public SchoolUser getCandidatesAsJson(#PathParam("applicationId") String applicationId, #PathParam("userPassword") String userPassword ) {
EntityManager em = createEM();
Query query = em.createQuery("SELECT su FROM SchoolUser su WHERE su.applicationId LIKE :applicationId and su.userPassword LIKE :userPassword", SchoolUser.class);
query.setParameter("applicationId", applicationId);
query.setParameter("userPassword", userPassword);
List <SchoolUser> schoolUser = query.getResultList();
if(!schoolUser.isEmpty()) {
SchoolUser loginRecord = schoolUser.get(0);
int teacherId = loginRecord.getTeacherId();
int studentId = loginRecord.getStundentId();
if(teacherId!=0){
TypedQuery<Classroom> query2 = em.createQuery("SELECT c FROM Classroom c where c.teacherId = :teacherId ORDER BY c.period", Classroom.class);
query2.setParameter("teacherId", teacherId);
List <Classroom> teacherClassList = query2.getResultList();
if(!teacherClassList.isEmpty()){
//put 2nd results set in SchoolUser object - line is commented because it causes an erro
//loginRecord.setClassRooms(teacherClassList);
}
} else if(studentId!=0){
TypedQuery<ClassroomStudent> query3 = em.createQuery("SELECT cs FROM ClassroomStudent cs where cs.statusId = 1 AND cs.studentId = :studentId", ClassroomStudent.class);
query3.setParameter("studentId", studentId);
//put results in SchoolUser object
}
return loginRecord;
} else {
SchoolUser emptyRecord = new SchoolUser();
return emptyRecord;
}
}
The error comes from putting the Classroom JPA object into the SchoolUser object - since these two objects don't have a direct relationship.
Any way that I can accomplish this with JPA?
If you do not want to persist the classroom (or any other attribute for that matter) then the #Transient annotation allows you to ignore a particular field so that JPA won't try to map it.
This annotation specifies that the property or field is not
persistent. It is used to annotate a property or field of an entity
class, mapped superclass, or embeddable class.
Example:
#Entity
public class Employee {
#Id int id;
#Transient User currentUser;
...
}
I'm using JPQL Native query to join table and query result is stored in List<Object[]>.
public String getJoinJpqlNativeQuery() {
String final SQL_JOIN =
"SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username,
t1.anotherNum FROM MasatosanTest t1
JOIN MasatoView v1 ON v1.username = t1.username;"
System.out.println("get join jpql native query is being called
============================");
EntityManager em = null;
List<Object[]> out = null;
try {
em = EmProvider.getDefaultManager();
Query query = em.createNativeQuery(SQL_JOIN);
out = query.getResultList();
System.out.println("return object ==========>" + out);
System.out.println(out.get(0));
String one = out.get(0).toString(); //LINE 77 where ClassCastException
System.out.println(one);
}
catch(Exception e) {
}
finally {
if(em != null) { em.close; }
}
}
The problem is
System.out.println("return object ==========>" + out); outputs:
return object ==========>
[[true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020],
[false, 0, 2010-12-21 15:32:53.0, koga, 0.213]]
System.out.println(out.get(0)) outputs:
[true, 0, 2010-12-21 15:32:53.0, masatosan, 0.020]
So I assumed that I can assign return value of out.get(0) which should be String:
String one = out.get(0).toString();
But I get weird ClassCastException.
java.lang.ClassCastException: java.util.Vector cannot be cast to
[Ljava.lang.Object;
at local.test.jaxrs.MasatosanTestResource.getJoinJpqlNativeQuery
(MasatosanTestResource.java:77)
So what's really going on? Even Object[] foo = out.get(0); would throw an ClassCastException :(
The SELECT clause queries more than one column or entity, the results are aggregated in an object array (Object[]) in the java.util.List returned by getResultList( ).
//---
Query query = manager.createQuery("SELECT v1.bitbit, v1.numnum, v1.someTime, t1.username, t1.anotherNum FROM MasatosanTest t1 JOIN MasatoView v1 ON v1.username = t1.username;");
List results = query.getResultList( ); // Fetches list containing arrays of object
Iterator it = results.iterator( );
while (it.hasNext( )) {
Object[] result = (Object[])it.next(); // Iterating through array object
Boolean first = (Boolean) result[0]; // Fetching the field from array
/* Likewise for all the fields, casting accordingly to the sequence in SELECT query*/
}
//---
Edit :
To avoid casting explicitly, you can go for constructor expression, adding a constructor to the entity with appropriate arguments.
SELECT new org.somepackage.XEntity(x.a, x.b) FROM XEntity x
I'm not familiar with JPQL Native query, but you simply debug with:
Object o = out.get(0);
System.out.println(o.getClass());
Then work from there. If it's a vector, iterate through and find what's in the vector.