java.lang.IllegalArgumentException: Parameter with that name [xxx] did not exist - java

java.lang.IllegalArgumentException: Parameter with that name [xxx] did not exist
I'm using Spring-data-jpa + hibernate
String login = "AdanaKebap";
String userQuery = "select * from user where username like '%:login%'"; // not working
Query query = entityManager.createNativeQuery(userQuery);
query.setParameter("login", login);
List<Object[]> userObjects = query.getResultList();
I'd try
String userQuery = "select * from user where username like '%?%'"; // not working
query.setParameter("1", login);
String userQuery = "select * from user where username like '%?1%'"; // not working
query.setParameter("1", login);
String userQuery = "select * from user where username like ':login'"; // not working
query.setParameter("login", login);
String userQuery = "select * from user where username like :login "; // not working
query.setParameter("login", login);
String userQuery = "select * from user where username = :login "; // working, but i don't need this

You need to use CONCAT, to concat % and the value passed to the query, so try :
String userQuery = "select * from user where username like CONCAT('%', ?1, '%')";
//...
query.setParameter(1, login); // note here you have to use the index of placeholder
or
String userQuery = "select * from user where username like CONCAT('%', :login, '%')'";
//...
query.setParameter("login", login);

Related

Getting the JPQL/SQL String Representations for a Criteria Query

How to Getting the SQL String Representations for a Criteria Query with parmetervalue ?
I tried this but it returns a string to me without the parameter values:
String QueryString = 'SELECT * FROM CUSTOMERS WHERE lastname = ?'
query = entityManager.createNativeQuery(QueryString);
query.setParameter(1, "toto");
System.out.print(query.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString());
But returns "SELECT * FROM CUSTOMERS WHERE lastname = ?"
instead of "SELECT * FROM CUSTOMERS WHERE lastname = 'toto'"
Thanks to #GrootCfor helping me find the solution.
If it helps other people here is the solution:
String QueryString = 'SELECT * FROM CUSTOMERS WHERE lastname = ?';
Query query = entityManager.createNativeQuery(QueryString);
Session session = entityManager.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = query.unwrap(org.eclipse.persistence.jpa.JpaQuery.class).getDatabaseQuery();
DatabaseRecord recordWithValues= new DatabaseRecord();
query.setParameter(1, "toto");
recordWithValues.add(new DatabaseField(Integer.toString(1)), "toto");
databaseQuery.prepareCall(session, recordWithValues);
String sqlStringWithArgs = databaseQuery.getTranslatedSQLString(session, recordWithValues);
System.out.print(sqlStringWithArgs);
====SELECT * FROM CUSTOMERS WHERE lastname = 'toto'====

Conditional AND using hibernate

I have the following query:
#NamedQuery(name = "User.findByParams", query=
"SELECT *
FROM User user
WHERE user.name type = :inputType")
And I wish to add AND statement, that will take place only if the inputs are supplied:
#NamedQuery(name = "User.findByParams", query=
"SELECT *
FROM User user
WHERE user.name type = :inputType AND (:ageInput != null AND user.age > :ageInput")
It means that if the ageInput is supplied, filter by it as well. If not- ignore this param. Any ideas?
Any ideas?
As the previous speakers wrote, you can use Criteria
Criteria criteria = createCriteria()
.add(Restrictions.eq("type", type));
if (ageInput != null) {
criteria.add(Restrictions.eq("ageInput", ageInput));
}
List<User> list = criteria.list();
or SQLQuery
String sql = "SELECT * " +
"FROM User user " +
"WHERE user.type = :inputType ";
sql += (ageInput != null) ? "AND ageInput = :ageInput " : "";
Query query = sessionFactory.getCurrentSession().createSQLQuery(sql)
.setParameter("inputType", inputType);
if(ageInput != null) {
query.setParameter("ageInput", ageInput);
}
return (List<User>) query.list();
You will have to check if ageInput is supplied or not in code and will have to call different methods accordingly.
Means if ageInput is supplied then you will have to call a method having ageInput constraint o/w call method which do not have ageInput constraint.
Alternatively, you can use predicates and execute a query.

SQL query to do INNER JOIN from two tables of a data base

I have two tables:
usuario (user in english): nombre, apellido, usuario, contrasena, id_perfil
perfil (profile in english): id_perfil, nombre
I have a login on my program using Java and MySQL and I want to know if the username and password entered by the user is correct, to send him to another Jframe.
I don't know much about SQL query but, I did my best here (I'm passing the username and password directly to the function):
public boolean login(String usuario, String contrasena) {
Dato_login d_lgn = new Dato_login();
boolean resultado = false;
sSQL = "SELECT u.nombre, u.apellido, u.usuario, u.contrasena, u.id_perfil, p.nombre AS perfil_nombre FROM "
+ "usuario U INNER JOIN perfil P u.id_perfil = p.id "
+ "WHERE u.usuario='" + usuario + "' AND u.contrasena='" + contrasena + "'";
// Java 7 try-with-resources
try (PreparedStatement pstm = con.prepareStatement(sSQL);
ResultSet rs = pstm.executeQuery(sSQL)) {
while (rs.next()) {
if (d_lgn.getContrasena().equals(contrasena)) {
resultado = true;
} else {
resultado = false;
}
d_lgn.setPerfil(rs.getString("perfil_nombre"));
d_lgn.setUsuario(rs.getString("usuario"));
d_lgn.setNombre(rs.getString("nombre"));
d_lgn.setApellido(rs.getString("apellido"));
d_lgn.setContrasena(rs.getString("contrasena"));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "SQLException:\n" + e, "Error: login(String usuario, String contrasena)", JOptionPane.ERROR_MESSAGE);
}
return resultado;
}
Is not working, it keeps telling me that there is not any user to log in.
What I need to change?
Also I would like to receive the name of the profile instead of the id of the user, I tried with INNER JOIN but I don't understand how it works correctly yet.
Table:
Error received:
Error in SQL Syntax
In this part:
sSQL = "SELECT u.nombre, u.apellido, u.usuario, u.contrasena, u.id_perfil FROM usuario U INNER JOIN perfil P ON p.nombre=u.nombre WHERE u.usuario='"
+ usuario + "' AND u.contrasena='" + contrasena + "'";
I don't see where a variables contrasena or usario is defined. Should that be ...AND u.usario='" + username + "' AND u.contrasena='" + password + "'"; instead? (putting aside a moment that this exposes a SQL Injection vulnerability). Also, it seems suspect that you're joining your usario and perfil tables on nombre. Is it the case that a User's name would be the same as their Profile name? Without understanding your domain and data model better, I can't really say.
If you also wanted to retrieve the profile name as well, your query could be this:
SELECT u.nombre, u.apellido, u.usuario, u.contrasena, p.nombre as perfil_nombre
FROM usario u
JOIN perfil p ON u.id_perfil = p.id_perfil
WHERE u.usuario = ? and u.contrasena = ?
Notice I'm joining usario and perfil on the id columns instead of nombre. I think you want the usario.perfil_id to match the perfil.id_perfil column.
Instead of con.createStatement() use con.createPreparedStatement(). See Using Prepared Statements for more information on that.
Lastly, to access the perfil.nombre from the ResultSet do this: rs.getString("perfil_nombre");
Also I am returning perfil.nombre instead of usario.nombre because you mentioned your want the profile name instead of the user name.

How to set placeholders in hibernate

Hi this my java code here am using hibernate to check whether this email id and password exist in db or not could anybody plz exp line me how to place the value to this place holders.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).list();
ses.close();
Thanks in advance
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo rp where rp.email = :emailAddress and rp.pwd = :password";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("emailAddress", Your email address)
.setParameter("password", Your password)
.list();
ses.close();
You should use a prepared statement instead of a string. example here
PreparedStatement preparedStatement = con.prepareStatement ("from RegisterPojo where email=? and pwd=?");
preparedStatement.setString(1, "email");
preparedStatement.setString(2, "password");
You have to modify your query like this,
query = "from RegisterPojo where email =:email and pwd =:password ";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("email",emailVal)
.setParameter("password",emailVal)
.list();
Read the hql docs here
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
ses.close();
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo where email = '" + varEmailAddress + "' and pwd = '" + varPassword + "'";
List<RegisterPojo> list = ses.createQuery(query).list();
ses.close();
Sorry This Is not Answer but instead another case, in above case #Grigoriev Nick suggested
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
but here the script starts with directly from clause while what if I want want to used sql like below
WITH A (
/// do some selection from many tables using various union as per my requirement
),
B (
/// another set of sqls for different set of data
)
select XXX from A a join B b on a.XYZ = b.xyz
where
/// few more fixed where clause conditions
AND A.SOME_COLUMN = ? // Here Instead Of String Concatenation I want to
//use Query parameters but using hibernate instead of raw Prepares statements

Why SQLQuery setParameter cannot use LIKE?

I have here:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE '%?%'");
query.setParameter(0, personName);
I get the following error:
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
But when I try:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME = ?");
query.setParameter(0, personName);
its working.
I need to use LIKE.
You can do like this:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE ?");
query.setParameter(0, "%" + personName + "%");
User criteria as
Criteria criteria = getSession().createCriteria(Person.class);
criteria.add(Restrictions.like("name", personName, MatchMode.ANYWHERE));
criteria.list();
String strQuery = "SELECT * FROM PERSON WHERE upper(NAME) LIKE '%"
+ personName.trim().toUpperCase() + "%'";
Session session = getSession();
SQLQuery query = session.createSQLQuery(strQuery );

Categories