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
Related
Got a question, how can i get 2 different variables from different tables using mysql? Is it possible to make it work from 1 query using prepared statement? I'm new at mysql database programming with java, so that's my problem.
I'm trying to get:
user_key from user table
project_key from project table
and yes, I know, table names should be in non singular form.
I'm trying :
String project_key = null;
String user_key = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://mysql:" + Config.getPortDB() + "/" + Config.getDatabase() + "?"
+ "user=" + Config.getUsername() + "&password=" + Config.getPassword());
String query ="SELECT user_key,project_key FROM user, project WHERE user_key = ? AND project_key = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
for(int i = 0; i < auths.size() ; i++ ) {
preparedStatement.setString(i+1, auths.get(i));
}
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
project_key = rs.getString("project_key");
user_key = rs.getString("user_key");
}
System.out.println(project_key); // null
System.out.println(user_key); // null
What am I doing wrong here?
SELECT u.user_key,
p.project_key
FROM (select user_key from user WHERE user_key = ?) u,
(select project_key from project WHERE project_key = ?) p
If the tow tables has no relation at all you still can get the 2 values using subqueries
This is your current query:
SELECT user_key,project_key
FROM user, project
WHERE user_key = ?
AND project_key = ?
To get results from 2 tables use JOIN, like this:
SELECT u.user_key, p.project_key
FROM user u
JOIN project p ON p.userId = u.id
WHERE u.user_key = ?
AND p.project_key = ?
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.
I am in the process of replacing jdbc with hibernate in my Web Application. I have learned that i don't have to write any SQL queries in this. Instead of this,criteria queries can help me.
These are my SQL queries which i want to convert to hibernate using criteria not HQL.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
rsDeptName = stmt.executeQuery("SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID ="+ DeptID + ";");
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
First off all you must map your table with POJOS.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
Preceding code in Hibernate look like following.
Criteria criteria = session.createCriteria(USER_DETAILS.class);
criteria.add(Restrictions.eq("user_id",yourUserId));
List<USER_DETAILS> list = criteria.list();
Your second select query is also same as preceding.
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
With Hibernate Criteria update looks like following:
USER_DETAILS user_details = (USER_DETAILES) session.get(USER_DETAILS.class,yourUserId);
user_details.setUser_Name(NewUserName);
user_details.setOrganization_Id(newOrganizationId);
// some other fields update goes here
session.update(user_details);
tx.commit();
I hope this help you.
need a help to create hibernate query that table is jdwCustomerTlrdRef and it should take all the operation_spec = customer name. the method should return sysId.
Here is the code to review. Please help me i am new to this hibernate query.
public getCustomerTlrdRef(BigDecimal sysId) {
System.out.println("---- getAllCustomerTlrdRef " );
String query = "from JdwCustomerTlrdRef as jdwCustomerTlrdRef where jdwCustomerTlrdRef.operation_spec= '+customer_name+'";
Query q = getSessionFactory().getCurrentSession().createQuery(query);
List<JdwCustomerTlrdRef> customerTlrdRefSysId = q.list();
System.out.println(" List size: " + customerTlrdRefSysId.size());
return customerTlrdRefSysId;
}
This should work.
String query = "from JdwCustomerTlrdRef jdwCustomerTlrdRef where jdwCustomerTlrdRef.operation_spec= '+ customer_name +'";
Otherwise if you want to pass the parameter later in your code then do it this way.
String query = "FROM JdwCustomerTlrdRef jdwCustomerTlrdRef WHERE jdwCustomerTlrdRef.operation_spec = :customer_name"
then in your code you can pass the parameter this way.
query.setParameter("customer_name", theCustomerNameParameter);
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 );