How to Set parameter to null value in java with hibernate? - java

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 = '')

Related

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Can not issue data manipulation statements with executeQuery()

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);

hibernate : binding parameter if not null

I create a web service which check an existence of data in a table. I had two input, one input is mandatory and the other is optional.
I want to create one query which binding the parameter mode if not null.
I used this query but it didn't work and I had this error:
java.sql.SQLException: ORA-01008: not all variables bound
query :
SELECT DATE_TRAITEMENT, DATE_DEB_PERIODE, DATE_FIN_PERIODE,user_cdg,canal,motif,SUJET_CRM,MODE_generation, TRAIT_STATUS,REMARK FROM ACM.CDG_REQUEST_OnDEMAND where CO_ID = :coId and (MODE_GENERATION= :mode or (MODE_GENERATION is null and :mode is null)) order by DATE_TRAITEMENT asc
and this my DAO class :
Session session = HibernateUtil.currentSession();
SQLQuery query = null;
org.hibernate.Transaction tx = session.beginTransaction();
String sql = cdg.getMessage("REQ001");
query = session.createSQLQuery(sql);
query.setLong("coId", coId);
if(integer != null) {
query.setInteger("mode", integer);
}
query.executeUpdate();

Select table row using HQL with param

I want to use this HQL query in order to select table row value:
String hql = "select e.token, e.name from Terminals e where e.token = ?";
Terminals terminal = entityManager
.createQuery(hql, Terminals.class)
.setParameter(0, terminalToken)
.getSingleResult();
But I get this result:
java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [org.api.entity.Terminals]
What is the proper way to implement this?
Your query return two Objects token and name and not a Terminals Object.
Instead you can use :
Object[] obj = entityManager
.createQuery(hql)
.setParameter(0, terminalToken)
.getSingleResult();
if(obj != null){
Terminals terminal = new Terminals((String) obj[0], (String) obj[1]);
}
Or you can create a constructor in Terminals class which hold two fields :
public Terminals(String token, String name){
this.token = token;
this.name = name;
}
then change your code to be :
String hql = "select new com.package.Terminals(e.token, e.name) from Terminals e where e.token = ?";
Terminals terminal = entityManager
.createQuery(hql, Terminals.class)
.setParameter(0, terminalToken)
.getSingleResult();
IMO, you should not directly call createQuery to assign to a custom object. And there is a possiblity of returning a list.
Query query = entityManager.createQuery(hql).setParameter(0, "something");<br>
List<Object[]> terminals = query.getResultList();
and retrieve the objects with an index as the ff as an example:
StudentDto dto = new StudentDto();
for(Object[] a: std) {
dto = new StudentDto();
dto.setId((long) a[0]); //id
dto.setName(a[1].toString()); //first name
dto.setPassportNumber(a[2].toString()); //last name
}

Use Criteria to select a particular field from DB?

I have a method like below
public List<String> getSimilarResourceNames(String resourceName){
String searchString = "%"+resourceName+"%";
Session session = getSession();
Criteria criteria = session.createCriteria(Resource.class);
criteria.add(Restrictions.like("name", searchString));
return criteria.list()
}
This will return me the entire resource from the DB, but what i need is just the name of the resource. How can I accomplish that ?
Use Projection, you can find examples in Hibernate documentation.
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
By using Projection you will get other fields (Which you did not got by Projection) in your Pojo setted to default values. In HQL you can get specified column values as follow:
Query query = session.createQuery("select u.fullname from Users u");
List<Object[]> rows = query.list();
List<String> fullnames = new ArrayList<String>();
for (Object[] row: rows) {
fullnames.add(row[0]);
}
I hope this will help you.

Problem with getting query result from database

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!!!

Categories

Resources