I'm trying to print a list (of only 1 item) but my JPQL statement isn't working due to quotations. I've tried every combination possible it seems but none will work. If anyone has any suggestions or different approaches I'd appreciate it. Note: I found a somewhat similar question on the site before I posted this but the answers aren't working for my case. Thanks
String submittedName=request.getParameter("name");
user=entityManager.find(user.getClass(),submittedName);
Query myQuery=entityManager.createQuery
("SELECT u.password FROM UserData u WHERE u.name=''"+submittedName+"");
List results=myQuery.getResultList();
String convertedResults=results.get(0).toString();
out.println(results);
To summarize what Dennis and Rob are trying to say:
String submittedName=request.getParameter("name");
user=entityManager.find(user.getClass(),submittedName);
Query myQuery=entityManager.createQuery("SELECT u.password FROM UserData u WHERE u.name=:name");
myQuery.setParameter("name", submittedName);
List results=myQuery.getResultList();
String convertedResults=results.get(0).toString();
out.println(results);
Related
I am having trouble while trying to implement where condition with " punchDate like :date1 " in sql query using hibernate. Can any one please tell me what is the correct syntax to implement it.
String sql=select * from PunchHistory whered punchDate like :date1;
String date="2017-10-23";
List<PunchHistory> results =session.createQuery(StackperksConstants.sql)
.setDate("date1", java.sql.Date.valueOf(date))
.list();
Could anyone please help me.
Thanks in advance
Like is used with Strings, instead you have to use = with dates :
String sql="select * from PunchHistory where punchDate = :date1"
//-----------------------------------------------------^
List<PunchHistory> results =
session.createQuery(StackperksConstants.sql)
.setParameter("date1", java.sql.Date.valueOf(date), TemporalType.TIMESTAM)
//Instead you can use -----^
.list();
The better way is using the setParameter() method, for example:
session.createQuery(sql,Class.class).setPrameter(0,date,TemporalType.TIMESTAMP).list();
I want to make my small spring project effectively. So I use IN clause instead of using loops in hql.
01) Question in setParameterList()
To use setParameterList(), we have to pass list object
List<Department> listDeptmntId = reportService.listDepartmentID(companyId); //list of objects
String hql = "select s.department.departmentName, g.dateTime from Gauge g inner join g.survey s where s.department in (:dpts)";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameterList("dpts",listDeptmntId);
The query works fine. But this return only one (first object in listDeptmntId list) resultset, does not return other results.
I tries to pass integer list like [1,2,3] using following method also not working.
List<Integer> dptIds=listDeptmntId.stream().map((Department::getDepartmentId()).collect(Collectors.toList());
02) Question in setParameter()
int cId=10;
String hql="...... companyId=:id"
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("id",cId);
Sometime when I use parameter passing ("=:") , it does not work for Integers . But directly setting variable to query like following is working
int cId=10;
String hql="...... companyId="+cId
Query query = sessionFactory.getCurrentSession().createQuery(hql);
My code may be wrong because I'm going through ebooks and referring materials to do the project. Thank you in advance.
I generally do IN(?, ..., ?) using an java.sql.Array.
long[] deptIds = listDeptmntId.toArray(new long[listDeptmntId.size()];
java.sql.Array array = conn.createArrayOf("LONG", deptIds);
query.setPameter("depts", array);
q1) Check the join (can't see any other reasons to return just one object). And passing [1,2,3] won't work with that query because in query you're dealing with department object. If you want [1,2,3] to work change the query to check for dept-ids like this -> "select s.department.departmentName, g.dateTime from Gauge g inner join g.survey s where s.department.id in (:id-list)"
q2) You've already created the query object when you set the parameter, so setting parameter at that point might not affect the query object. (Your "+" approach works since the parameter is set to the query when creating the query object.)
I just stumbled upon some SQL code of a colleague (we have a "dont fix it, if it aint broke policy"), for a login process.
The name variable is delivered by an input field from a JSP.
//BAD CODING ALERT: DONT USE THIS CRAPPY CODE, YOU NAUGHTY COPY PASTERS!
Query q = em.createQuery("select object(u) from User as u where u.name = '" + name + "'");
With no sanitation at all on the name variable except of server side validating on some Illegal characters: <>"'%;() (mind that that is single and double quotes)
Can this be exploited? And if yes, how so?
If it wasnt for the single and double quotes, one could do something like: blah' OR 'x'='x
You should NEVER EVER create query by string concatenation. use query.setParameter("paramName",paramValue);
so it would be something like that
Query q = em.createQuery("select object(u) from User as u where u.name =:name");
q.setParameter("name", "O'Reilly")
no SQLInjections possible because of escaping values;
Answering my own question... it is safe, however not practical as allready stated by myself.
Before downvoting this, READ the question. Or give an exploit example otherwise.
I am new into Spring, though my issue may appear immature.
Here is a big obstacle I have been stuck into. I am trying to choose the right approach to implement search logic based on wildcards, whether to select JDBC, or Hibernate, or JPA and repositories.
I will demonstrate the problem. Let say we have a search form within web page, where someone may put query to retrieve FirstName and LastName, and say for example there are records:
"Fred Fredrickson"
"Albert Jameson"
"Watson Dalbot"
It is possible to use something like *alb*, we should get:
"Albert Jameson"
"Watson Dalbot"
or using ????son we expect to get only "Albert Jameson".
Learning Spring I found that "like" clause may be only hardcoded, something like:
#Query("select u from User u where u.firstname like %?1")
List findByFirstnameEndsWith(String firstname);
in case of using JPA repositories.
I hope my problem has got a bit clearer.
Big thanks in advance for any kind of help or related advice.
I would have use JPA with the following example
#NamedQuery(name="Profile.getPerson", query="SELECT u FROM User u WHERE u.firstName LIKE ?1");
Query query = session.getNamedQuery("Profile.getPerson");
query.setParameter(1, patternYouWant);
query.getResultList();
I'm having problems with ldap search filters.
I want to search through all the children of a root node. I want the users where the username of the email contains the query string.
for example, if I have
foo_l.c_bar#foobar.com
foobar#foo_l.c_bar
and the search query is "l.c" I want only foo_l.c_bar#foobar.com
the following code, surprisingly, returns either the first and the second.
String query = "...";
DirContext dc = ...;
NamingEnumeration<SearchResult> ne = dc.search(root,
"(email=*{0}*#*)",
new Object[] { query }, null);
what's wrong in the "*...*#*" query filter?
I cannot give you a full answer, but if you try a ldapsearch from command line with the filter "(email=*l.c*#*)", you should get the right records ... so I would say the problem is in the Java method and not in the filter.
Hope it could help you.
I assume you forgot to paste the code that formatted your query and its {0} parameter ?
edit: wow, forget me, I didn't even know about the method that takes the filterArgs array.
As a side note, the standard attribute for e-mail address in inetOrgPerson is "mail" not "email" (but it might be different on your case of course)