How to add dynamically an object to a hibernate query - java

When I use Hibernate query language, how can I add dinamically the object I want to get from the DB?
What I want to reach is somethin like this:
......
if(....){
queryString = "from '" + Object1+ "'";
}
if(...){
queryString = "from '" + Object2+ "'";
}
....
Session session = this.getSessionFactory().getCurrentSession();
Query query = session.createQuery(queryString);
......
I tried different kind of syntax but I get errors every time.

Via Criteria API you can easily build dynamic query's...
Criteria criteria = session.createCriteria(Sale.class);
if (startDate != null) {
criteria.add(Expression.ge("date",startDate);
}
if (endDate != null) {
criteria.add(Expression.le("date",endDate);
}
List results = criteria.list();

you can use this:
......
if(....){
queryString = "from '" + Object1.getClass().getName()+ "'";
}
if(...){
queryString = "from '" + Object2.getClass().getName()+ "'";
}
....
Session session = this.getSessionFactory().getCurrentSession();
Query query = session.createQuery(queryString);
......

What actually you need is to pass class name. You can use following way to get class name of a given object.
object1.getClass().getSimpleName()
So in your case you can append this in your query
example :
if(....){
queryString = "from '" + Object1.getClass().getSimpleName()+ "'";
}

Related

How to use variables passed through a method argument in a nativeQuery from javax.persistance?

I can currently pass in a variable to a nativeQuery by just using a string. Like so
Query query = em.createNativeQuery(""
+ "SELECT * FROM jobposting "
+ "WHERE title = ?1 "
+ "ORDER BY created_at ASC", JobPostingModel.class);
query.setParameter(1, "Web dev");
List<JobPostingModel> Joblist = query.getResultList();
But when I pass web dev using a variable through the method argument. I don't get anything in from the query.getResultList().
public static List<JobPostingModel> retriveJobPostingsWith(String type) {
Query query = em.createNativeQuery(""
+ "SELECT * FROM jobposting "
+ "WHERE title = ?1 "
+ "ORDER BY created_at ASC", JobPostingModel.class);
query.setParameter(1, type);
List<JobPostingModel> Joblist = query.getResultList();
return Joblist;
}
The method is called using
retriveJobPostingsWith("Web dev");
Could anyone tell me why this won't work?

MYSQL+Hibernate, Query cannot be created

Can someone help me to have a look at what is wrong with my query?
Java code :
public boolean fValidLogin(String fUsername, String fPassword) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
String query = "SELECT fusername,fpassword FROM flogin WHERE fusername=" + fUsername + " AND fpassword=" + fPassword + "";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) {
it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}
MYSQL Code:
SELECT fusername,fpassword FROM flogin WHERE fusername="SAS" AND fpassword="Sas123"
Try this first:
"SELECT fusername,fpassword FROM flogin WHERE fusername=\"" + fUsername + "\" AND fpassword=\"" +fPassword +"\""
By the way you are tring to use a native query. Maybe you should consider to use "createNativeQuery" instead of "createQuery"
Your query is a victim of an SQL Injection, it can also cause syntax error, instead you have to use setParameter with a JPQL query :
String query = "SELECT f FROM flogin f WHERE f.fusername = ? AND f.fpassword = ?";
Query dBquery = session.createQuery(query);
dBquery.setParameter(0, fUsername);//set username variable
dBquery.setParameter(1, fPassword);//set password variable
To get the nbr of result you can just call Query::list()
int count = dBquery.list().size();
Or just :
return dBquery.list().size() == 1;
The real problem in your query is that the String should be between two quotes (but i don't advice with solution)
fusername='" + fUsername + "'
//--------^_________________^
Note: Your query is not a JPQL Query, it seems a native query, if that you have to use session.createNativeQuery(query);.

Hibernate trunc in criteria

My sql query
SELECT count(1),trunc(D_O_I) FROM TableName
WHERE P_D IN (3) AND
D_O_I BETWEEN to_date('01/01/2014','mm/dd/yyyy') and to_date('01/31/2015','mm/dd/yyyy') group by trunc(D_O_I)
And my Hibernate code for query is as below..
session = HibernateSessionFactory.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TableName.class).setProjection(Projections.projectionList()
.add(Projections.groupProperty("dteOfIss"), "dteOfIssResult").add(Projections.rowCount(), "count")).setResultTransformer(Transformers.aliasToBean(GroupedDateDTO.class));
criteria.add(Restrictions.sqlRestriction("(P_D IN ('3'))"));
if (reportsForm.getFromDate() != null && reportsForm.getToDate() != null) {
criteria.add(Restrictions.sqlRestriction("trunc(D_O_I) >= to_date('"+ utils.convertDateToString(reportsForm.getFromDate()) + "', 'MM/dd/yyyy')"));
criteria.add(Restrictions.sqlRestriction("trunc(D_O_I) <= to_date('"+ utils.convertDateToString(reportsForm.getToDate()) + "', 'MM/dd/yyyy')"));
}
listResult = criteria.list();
How to add Trunc to dteofIss in hibernate code? i tried diffrent way's but i am unable to fetch.
Please Help

Hibernate update a certain value

I have coded a method which selects or updates a value if it has a certain identifier:
#Transactional
public List<Settings> getSettingsByParameter(String identifier) throws Exception {
log.info("get resultsList by " + identifier);
if(identifier.isEmpty()) {
throw new Exception("Identifier is empty!");
}
if(identifier == "today") {
//update today field
String query = "UPDATE settings SET value=TODAY() where identifier = '" + identifier + "'";
em.merge(em.createQuery(query, Settings.class).getSingleResult());
}
String query = "SELECT p FROM Settings p WHERE identifier = '" + identifier + "'";
List<Settings> resultList = em.createQuery(query, Settings.class).getResultList();
return resultList;
}
However, I am getting an exception:
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: settings is not mapped [UPDATE settings SET value=TODAY() where identifier = 'today']
Why and how is this possible using hibernate and hsqldb?
I really appreciate your answer!
Hibernate is case-sensitive with class names. Try it with a captial S for the Settings class:
String query = "UPDATE Settings SET value=TODAY() where identifier = '" + identifier + "'";

HQL: variable column

I'm able to set variable values for "where" restrictives:
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where test.col = :variableValue ");
criteria.setInteger("variableValue", 10);
But is it possible to set variable column like this?
String variableColumn = "test.col1";
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where :variableColumn = :variableValue ");
criteria.setInteger("variableValue", 10);
criteria.setString("variableColumn", variableColumn);
This is the result:
Exception in thread "main" Hibernate: select .... where ?=? ...
org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
...
at _test.TestCriteria.main(TestCriteria.java:44)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value 'test.col1' to data type int.
...
UPDATE (working solution):
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where (:value1 is null OR test.col1 = :value1) AND
(:value2 is null OR test.col2 = :value2) "
Does this make sense in your application:
String query = "select test.col1, test.col2, test.col3" +
"from Test test " +
"where {columnName} = :variableValue ";
Object variableValue = // retrieve from somewhere
String columnName = // another retrieve from somewhere
query = query.replace("{columnName}", columName);
// Now continue as always
This is generally a naive query constructor. You may need to refactor this idea to a separate utility/entity-based class to refine (e.g. SQL injection) the queries before execution.
You can set the column name as part of the string. For security you may do the SQL escaping manually, but at the end you can achieve this.
To avoid SQL injection you can use commons class:
String escapedVariableColumn = org.apache.commons.lang.StringEscapeUtils.escapeSql(variableColumn);
Query criteria = session.createQuery(
"select test.col1, test.col2, test.col3
"from Test test " +
"where " + escapedVariableColumn + " = :variableValue ");
criteria.setInteger("variableValue", 10);

Categories

Resources