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.
Related
Good afternoon people!
I think that may be a silly question ..
I have the following code in Hibernate:
query = session.createQuery ("select F from Employee F where F.email =" + email);
Does anyone know how I can get the value of a field within this query?
Example: How would I get the name of the person (employee).
Note: I would like to use a good Hibernate practice ... I believe it is not good to repeat:
query = session.createQuery ("select F.person from Employee F where F.email =" + email);
Can you help me? :)
Thank you.
Prior to Hibernate 5.2:
String sql = "SELECT e.person FROM Employee e WHERE e.email = :email";
Query query = session.createQuery( sql )
query.setParameter( "email", emailAddress );
List<Person> people = (List<Person>) query.getResultList();
In Hibernate 5.2 and beyond:
String sql = "SELECT e.person FROM Employee e WhERE e.email = :email";
Query query = session.createQuery( sql, Person.class );
query.setParameter( "email", emailAddress );
List<Person> people = query.getResultList();
With the merge of Hibernate EntityManager into Core as a part of 5.2.x+, you now get better type safe queries to avoid casting later on :).
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
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= !;";
query = query.replace("?", "'"+post.getDatetime()+"'");
query = query.replace("!", Integer.toString(post.getPublisher().getID()));
PreparedStatement pstm = con.prepareStatement(query);
ResultSet rs = pstm.executeQuery();
The resulting query looks like this
SELECT * FROM POST_COMMENT WHERE Post_date_time= '2013-04-12 07:20:34.0' AND Post_User= 378;
Which works right in the MySQL prompt line but, when launched from prepared statement throws this error:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '07:20:34.0 AND Post_User=378' at line 1
But
pstm.setString(1, post.getDatetime());
pstm.setString(2, Integer.toString(post.getPublisher().getID()));
isn't working either.
Table definition
CREATE TABLE Post_Comment (
Comment_ID INTEGER(7) NOT NULL,
Post_date_time DATETIME NOT NULL,
Post_User INTEGER(7) NOT NULL,
PRIMARY KEY(Comment_ID, Post_date_time, Post_User),
CONSTRAINT Post_Comment_Post
FOREIGN KEY (Post_User, Post_date_time)
REFERENCES Post (User, date_time)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT Post_Comment_Comment
FOREIGN KEY (Comment_ID)
REFERENCES Commentary (ID)
ON DELETE CASCADE
ON UPDATE CASCADE
)
;
Please help.
Take a look at the Java tutorials. You're not supposed to replace() the fields using the String functions.
You're supposed to call the "set" methods of the PreparedStatement.
EDIT:
No, take a look at the available methods. And what types the database columns expect. If you want a date, use setDate(), if you want an Integer, then use setInt(). Example:
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time = ? AND Post_User = ?;";
PreparedStatement pstm = con.prepareStatement(query);
pstm.setDate(1, post.getDatetime());
pstm.setInt(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();
Also note that the query uses ? for both placeholders, not !.
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= ?;";
PreparedStatement pstm = con.prepareStatement(query);
pstm.setObject(1, post.getDatetime());
pstm.setObject(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();
I have the following code to executing a sql query:
query = String.format("select * from users where user_name = '%s';", results.getString(1));
results2 = mStmt.executeQuery(query);
One user_name in the dataset has value "O'brien". This ruins my query due to the single parenthesis in "O'brien. The query would become:
select * from users where user_name = 'O'brien'
What is the strategy to overcome this and not modify the data?
EDIT: The prepared statement does fix the single quote problem however that was only part of the problem. One of the string values I have contains the word "UNDER". which is a SQL keyword. For example I have a preparedStatement called insertAll with the query:
insert into names (id, val1, val2, val3, val4, tTime, val5) values (?, ?, ?, ?, ?, ?, ?)
Thanks for all the help!
Set your parameters with prepareStatement. Your code is a SQL injection exploitable code from the book.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Why not use PreparedStatement instead, avoid the tedious and error-prone issue of escaping quotes in sql queries altogether?
The could would look something like this (sorry, I didn't actually run this, but you should get the idea):
query = "select * from users where user_name = ?";
PreparedStatement p = new PreparedStatement(con, query);
p.setString(1, results.getString(1));
results2 = p.executeQuery();
I am using struts and hibernate in my problem. I tried the following query
String hql ="insert into "+
"OPENQUERY(OracleLinkedServer, \'SELECT * FROM report_access_log\') "+
"(CALLINGHOST, ACCESSTIMESTAMP, HTTPREQUESTMETHOD, ACCESSURL,"+
"HTTPRESPONSECODE, HTTPRESPONSETIMEMILLI, USERNAME, REPORTNAME, ID)"+
" values "+
"(:CALLINGHOST,:ACCESSTIMESTAMP,:HTTPREQUESTMETHOD,:ACCESSURL,:HTTPRESPONSECODE," +
":HTTPRESPONSETIMEMILLI,:USERNAME,:REPORTNAME,"+
"(select * from OPENQUERY(OracleLinkedServer,"+
"\'select SQ_RPT_ACC_LOG_ID.nextval from dual\')))";
Query query=session.createQuery(hql);
query.setString("CALLINGHOST", userLogReport.get(0).toString());
query.setDate("ACCESSTIMESTAMP", (Date)userLogReport.get(1));
query.setString("HTTPREQUESTMETHOD", userLogReport.get(2).toString());
query.setString("ACCESSURL", userLogReport.get(3).toString());
query.setString("HTTPRESPONSECODE", userLogReport.get(4).toString());
query.setInteger("HTTPRESPONSETIMEMILLI", (Integer)userLogReport.get(5));
query.setString("USERNAME", userLogReport.get(6).toString());
query.setString("REPORTNAME", userLogReport.get(7).toString());
The query printed on the console is as follows
insert into OPENQUERY(OracleLinkedServer, 'SELECT * FROM report_access_log')
(CALLINGHOST, ACCESSTIMESTAMP, HTTPREQUESTMETHOD, ACCESSURL,HTTPRESPONSECODE,
HTTPRESPONSETIMEMILLI, USERNAME, REPORTNAME, ID) values
(:CALLINGHOST,:ACCESSTIMESTAMP,:HTTPREQUESTMETHOD,:ACCESSURL,:HTTPRESPONSECODE:HTTPRESPONSE
TIMEMILLI,:USERNAME,:REPORTNAME,(select * from OPENQUERY(OracleLinkedServer,'select
SQ_RPT_ACC_LOG_ID.nextval from dual')))
i get a query syntax exception at column no 79 which is (CALLINGHOST,...
But when i ran the query in SQL it is getting executed. The query is as follows
insert into OPENQUERY(OracleLinkedServer, 'SELECT * FROM report_access_log')
(CALLINGHOST, ACCESSTIMESTAMP, HTTPREQUESTMETHOD, ACCESSURL,HTTPRESPONSECODE,
HTTPRESPONSETIMEMILLI, USERNAME, REPORTNAME, ID) values
('10.87.192.246','GET','/cci/bby/ImageViewer/viewImages.action','200',6,'su','Insert
Review',(select * from OPENQUERY(OracleLinkedServer,'select SQ_RPT_ACC_LOG_ID.nextval
from dual')))
Please explain the problem and provide me a solution for executing it from Java.
Thanks in advance.
HQL and SQL are two different languqges. HQL works on Hibernate entities, their properties, and associations between them. SQL works on database tables and columns.
Use
Query query = session.createSQLQuery(sql);
rather than
Query query = session.createQuery(hql);