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.
Related
I am trying to retrieve a student object from a student table but am getting null.
public Student getStudentbyStudentName(String studentName) {
final String query = "from Student s where s.studentName = '" + studentName + "'";
return (Student)sessionFactory.getCurrentSession().createQuery(query).uniqueResult();
}
I have also tried the following to retrieve the student object of studentName. It works until my web page refreshes. When page refreshes, the following returns null. Please help.
public Student getStudentbyStudentName(String studentName) {
return (Student) sessionFactory.getCurrentSession()
.createCriteria(Student.class)
.add(Restrictions.eq("studentName", studentName))
.uniqueResult();
}
I guess that the name you pass in to that method is kind of Unicode, then you should place extra parameters in your MySQL connection url. E.g:
jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8
Second, but important. Your first code snippet is vulnerable for SQL Injection attack. Please use Criteria API (your 2nd snippet) or prepare your query:
from Student s where s.studentName = :name
in conjuntion with setParameter(...) method
Contact contact7 = new Contact(7,"Jobs", "jobsatapplet.com", "CoffeeBeans", "0123456789");
contact7.setId(7);
//session.update(contact7);
Contact contact8 = (Contact)session.load(Contact.class, new Integer(7));
contact8 = new Contact(7,"Jobs", "javaatapplet.com", "Cupertino", "0123456789");
session.save(contact7);
// commits the transaction and closes the session
session.getTransaction().commit();
session.close();
This is my code, instead of reinserting record 7 it inserts a new record which increments the number of records with duplicate values.
I am not sure what you are trying to do, but if it is to update an existing record, you can do this:
Contact c = (Contact)session.load(Contact.class, new Integer(7));
c.setLocation("Cupertino");
session.getTransaction().commit();
session.close();
This is, if your Contact class has a setLocation() method. Without the mapping and class files I can't be more precise.
I have a test class :
class SomeTest {
public static void main(String args[]){
Client kom = new Client();
kom.setId(kom.newID());
kom.setClient("OldName");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(kom); // I think insert is here ?
Query q = session.createSQLQuery(" call change_name(:old, :new) ");
q.setParameter("old","OldName");
q.setParameter("new","NewName");
int result = q.executeUpdate();
session.getTransaction().commit();
}
};
And database stored procedure change_name which do update of name of client.. every time I run test I have one record with old name ?? I expect that update is execute in same transaction and that I never see old name ?
JB Nizet has right answer..
save() does NOT insert. It associates the object with the session. The insert query is executed at the next flush. So call flush explicitely before calling your stored proc. – JB Nizet yesterday
There is also FlushMode ... I set to ALWAYS. I call many procedures which change data in database..
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.
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.