Hibernate Iterator retrieving same data - java

I have a form that is connected to the database via hibernate. With this form, the user can go in and fill out fields such as names, address, and email information, etc. After they are all done filling out information they would submit the form. After submit, all the information would be display on a data table on the same page.
I am using session to interact with the database. However, the data that is being populated from database doesn't seem to be right.
public void somefunction() {
//The sessionfactory is being configured in another class
Session s = sessionFactory.openSession();
Transaction tx= null;
try {
tx= s.beginTransaction();
List userInformation = s.createQuery("FROM database1 WHERE PKEY ='"+somevalue+"'").list();
for(Iterator iterator = userInformation.iterator; iterator.hasNext();){
//database1 is an entity bean
database1 x = (database1) iterator.next();
System.out.print(x.getName());
}
tx.commit();
}
catch(Exception) {......}
finally {.....}
}
After the user submit the first "user" with their information, everything shows up in the datatable fine. However, when they enter a second "user" the row displayed on the datatable is the same information as the first user, even though the data is different. I think the code looks correct, so i am not sure what could be wrong with this.

you should use primary key to get correct value.
List userInformation = s.createQuery("FROM database1 where yourId='PK'").list();
In your query always it will return first row.

Found the solution.
Instead of using session.createQuery("QUERY"), I used
Criteria cr = session.createCriteria(SomeClass.class)
cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
cr.add(/* add some filters here */);
ScrollableResults sr = cr.scroll(ScrollMode.FORWARD_ONLY);
while(sr.next) {
someObject so = (someObject) sr.get(0);
//Do action here
}
that solved my problem of returing a single result.

Related

Mybatis insert function can not return model id

I used Mybatis. I have Class Form (id, name). I want to insert a new record in the database and get it's Id.
my code is
Form form = new Form();
form.setName("insertid");
formMapper.insert(form);
Long id = form.getId();
System.out.println("----" + id);
but form.getId() is null.
how to fix it? Thanks.
I have inquired a lot of information, but no one else was in the same situation

procedure call not working from java call

I have created a procedure which updates a table row in DB and returns a specific string(e.g 'done') after the update it returns a different response if the value is not updated(e.g 'fail').
When calling from MySQL tool it's updating the table and returning the value in response
call LoginCheck('9111111114','AGGR001002','11d3ad9315b7be5dd53b31a273b3b3aba5defe700808305aa16a3062b76658a791','DIST001007');
However when I am calling the same procedure from Java code it's returning the proper response i.e 'done', but when I am checking the table it seems that it has not updated the respective table row.
factory = DBUtil.getSessionFactory();
Session session = factory.openSession();
Transaction transaction = session.beginTransaction();
String status = "7000";
List objectList = null;
SQLQuery query = session.createSQLQuery("call LoginCheck(:userid,:AggId,:Password,:id)");
query.setString("userid", userid);
query.setString("AggId", AggId);
query.setString("Password", Password);
query.setString("id", id);
objectList = query.list();
I have already tried query.setParameter and query.ExecuteUpdate()
Please let me know if anything else is required from my side.
It seems that you have begin your transaction but not committed it . so try commit it .
Transaction transaction = session.beginTransaction();
transaction.commit()

How to fetch list of tables in database using HibernateDaoSupport?

Here I have added my code. Issue occurs in try block while I am trying fetch list of tables.
Database is MySql
Exception is : java.lang.IllegalArgumentException: node to traverse cannot be null!
public class DBOptimizationDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(DBOptimizationDAO.class);
public void optimizeAdapter(String year)
{
List<com.ecw.adapterservice.beans.TransactionInbound> transactionInboundList = null;
StringBuilder queries = new StringBuilder();
try {
transactionInboundList = (List<com.ecw.adapterservice.beans.TransactionInbound>)super.getHibernateTemplate().find("from TransactionInbound where inboundTimestamp < '" + year+ "-01-01'order by 1 desc limit 2");
// Check if archive table exist or not
List<Object> inboundObj = getHibernateTemplate().find("SHOW TABLES LIKE transaction_outbound");
List<Object> outboundObj = getHibernateTemplate().find("SHOW TABLES LIKE 'transaction_outbound_archive'");
The HibernateTemplate::find expects a HQL query in the string parameter and you are passing a native statement. You can do native stuff (queries, statements, etc) using the Session object returned by HibernateTemplate::getSession. To pass a native select query you then have Session::createSQLQuery
BUT do you really want to rely on database specific code to do this? There is a more elegant way to do it by using DatabaseMetaData::getTables. See this answer. And you can get an instance of DatabaseMetaData from a callback method of your HibernateTemplate.
Try this:
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
if(!session instaceof SessionImpl){
//handle this, maybe throw an exception
}
else {
Connection con = (SessionImpl)session.connection();
...
}

Hibernate retrieve query not working

I have a hibernate implementation inside my JSF2 code trying to list some records from MySQL DB. There are following code snippets: Search.java - implementing the querying logic; Student.java - implementing the record saving logic.
The problem I am facing is whenever I run Search.java, the result returned is 'null'.
Please note - my DB has already many entries and even when I tried to query Student myStudent = session.get(Student.class, 23); it returned me 'null'.
Here 23 is the id field in the SQL table. Also, the table has auto-generated PK as id. I have another class for inserting the records that works perfectly fine.
Search.java:
public class Search {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// start a transaction
Student tempStudent = new Student("bob", "thebuilder", "good", "blabla#bla.com", "(456)-456 5897");
session.beginTransaction();
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
System.out.println("id of the student is " + tempStudent.getId());
session = factory.getCurrentSession();
session.beginTransaction();
System.out.println("student with id " + tempStudent.getId());
Student myStudent = session.get(Student.class, tempStudent.getId());
session.getTransaction().commit();
System.out.println("Done!");
} finally {
factory.close();
}
}
}
Please advise what mistake I might have made here. I've spent hours googling. Also, please forgive me for my (possibly) rookie mistakes, I am new to Hibernate and to this website.
Let me know if I need to post error stack or my cfg.xml as well.
As I can see in your case id of tempStudent is 0. You need to get from session by id of saved student.
Try this:
Serializable id= session.save(tempStudent);
...
Student myStudent = session.get(Student.class, id);
Also you can enable show_sql property in your hibernate.cfg file. It will log all generated sql, so you can chek if it is ok.

How to retrieve database table value in hibernate?

I am new to the Hibernate, i want to retrieve table values from database, I have a code but it returns object values. My sample code is,
Configuration conf=new Configuration();
#SuppressWarnings("deprecation")
SessionFactory sessionfactory=conf.configure().buildSessionFactory();
Session session=sessionfactory.openSession();
List maintable = null;
try
{
org.hibernate.Transaction tx = session.beginTransaction();
Query q = session.createQuery ("select main.empid,main.address from Main as main");
maintable =q.list();
Object[] obj=maintable.toArray();
for(int i=0;i<obj.length;i++)
{
System.out.println("column valuse : "+obj[i]);
}
tx.commit();
session.close();
}
catch(Exception e1)
{
System.out.println("Exception");
}
I need to get multiple column values...How can i do that?
I can retrieve value from list easily.But in my above question i print only object property not a value.
Query qry=session.createQuery("from Main");
List<Main> user=(List<Main>) qry.list();
session.getTransaction().commit();
session.close();
for(Main u : user)
{
System.out.println("User id : "+u.getEmpid());
System.out.println("User Address:"+u.getAddress());
}
This is what Hibernate (or JPA rather) is meant for. If you want to access regular values, use JDBC instead.
It’s very useful when we retrieve some fields/properties from our entity class. The above query with “new” keyword can return a list of type “Main”. If we do not use such a keyword and specify the fields directly, a list of type Object [ ] is retrieved.
select new Main(main.empid,main.address) from Main as main ,
select main.empid,main.address from Main as main
please check that empid,address are the column name in the database or the property name of Main class.
It should be the property name of entity(i.e Main) class.

Categories