-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Hibernate Persistence HELP
PostPosted: Thu Jul 12, 2007 9:09 am 
Newbie

Joined: Thu Jul 12, 2007 8:57 am
Posts: 11
I have been trying to add a persistence layer on a JSF web app with little luck. I am using Eclipse with Exadel Studio Pro.

For the purpose of learning hibernate, I have created a very simple sample project.

This project has one java bean (ProjectManager) that controls a class (Project) with four properties; id, name, client, location.

The first page (index2.jsp) has a button which creates a new instance of the Project class, which redirects to another page (index3.jsp) with inputText boxes to enter the values. Clicking the set button on this page redirects to another page (index4.jsp) which uses outputText to show the values of the attributes of the Project class. There is a button there that is to persist this instance by calling a method in ProjectManager which saves the Project object.

Below is the relevent code for the files:

the JSP pages are self explanatory, they accomplish everything I said above with inputText, outputText and commandButton tags.

Project.java contains:
Code:
Integer id;    // Primary key
String name, client, location;

as well as the proper getters/setters.

ProjectManager.java:
Code:

package beans;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class ProjectManager {
   private Project projObj;
   
   public void setProjObj(Project _projObj) {
      this.projObj = _projObj;
   }
   public Project getProjObj() {
      return projObj;
   }
   
   public ProjectManager() {}
   
   public String newProject() {
      projObj = new Project();
      return "success";
   }
   
   public String saveProject() throws Exception {
        // Create SessionFactory object
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

        // Open Session
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        // Save Project and close Session
        session.saveOrUpdate(projObj);
        session.close();
      
      return "success";
   }
}




hibernate.cfg.xml:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate10</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <mapping resource="beans/Project.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


Project.hbm.xml:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping schema="hibernate10" package="beans">
  <class name="Project" table="project" optimistic-lock="none">
    <id name="id" type="integer" unsaved-value="null" column="id">
      <generator class="increment"/>
    </id>
    <property name="name" type="string" column="name"/>
    <property name="client" type="string" column="client"/>
    <property name="location" type="string" column="location"/>
  </class>
</hibernate-mapping>


I made the project table with the following SQL statement:

CREATE TABLE project ( id INT(255) NOT NULL AUTO_INCREMENT , name varchar(255), client varchar(255), location varchar(255), primary key (id) )

I also tried:

CREATE TABLE project ( id INT(255) NOT NULL DEFAULT '0' , name varchar(255), client varchar(255), location varchar(255), primary key (id) )

I'm hoping there's an obvious little error in all of this, if someone can point it out. Perhaps my SQL statements are making tables that aren't appropriate to my task? Also, I'm not sure if my configuration files are missing a tag or have a property improperly defined. What frustrates me most is that there are no exceptions being thrown, and the save method executes to completion, but data is still not being written to the database.

Thank you all for your time, any help would be greatly appreciated!


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jul 12, 2007 2:30 pm 
Expert
Expert

Joined: Tue Dec 28, 2004 7:02 am
Posts: 573
Location: Toulouse, France
...

Why didn't you commit your transaction? When no data is even written, it seems the first thing to look at the transaction demarcation.

In your case, I can't see any session.getTransaction().commit();.

I suppose you were thinking that the close() method would commit(). The thing is it could, but I almost sure this behaviour depends on the underlying used db and strategy.

In fact, even the javadoc for this close() doesn't specify anything about what it'd do if a tx is started but still not committed or rollbacked. IMO, it seems in your case this does nothing or a rollback, so no data is ever written for long :-).

HTH.

_________________
Baptiste
PS : please don't forget to give credits below if you found this answer useful :)


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jul 12, 2007 3:18 pm 
Newbie

Joined: Thu Jul 12, 2007 8:57 am
Posts: 11
Thank you very much for the help, and this is exactly what went wrong.
I had to add a tx.commit(); line just before session.close();
I actually figured this out earlier, in digging through some of the documentation on the hibernate site, but your input is very much appreciated.
I am now successfully writing to the database as I would expect, but I hope you can help me in my next problem. I've been using this tutorial
http://www.codeguru.com/cpp/misc/misc/interfacingtootherlanguages/article.php/c10079__1/ since it is easier to understand than most hibernate tutorials.
The authour never included a tx.commit(); line and so this is why my code didn't have it. I've gone ahead and used his example for reading from a file, but that too doesn't work. Since the earlier code was flawed I have no idea what is wrong in this case.

This is the code I'm now using for pulling the object back:
Code:
   public Project[] listProjects() throws Exception {
      Project[] projectAll;
      ArrayList projAlist = new ArrayList();
      
      //Log4J initialisation
      org.apache.log4j.BasicConfigurator.configure();
      

      //***RELEVENT HIBERNATE CODE

              // Create SessionFactory and Session objects
           SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
           Session session = sessionFactory.openSession();

           //Query using Hibernate Query Language
           String sqlString = "FROM project as p";
             Query query = session.createQuery(sqlString);
       
           //Iterate through stored objects
           for (Iterator it = query.iterate(); it.hasNext();) {
                 Project tempProjObj = (Project) it.next();
                 projAlist.add(tempProjObj);
           }
      session.close();

      //***END RELEVENT HIBERNATE CODE
      
      // Create an array of type Projects from projAlist arraylist
      projectAll = new Project[projAlist.size()];
      // Populate projectAll array with Project objects from projAlist arraylist in reverse order
      for (int i = 0; i < projAlist.size(); i++) {
         projectAll[i] = (Project) projAlist.get( (projAlist.size() - i -1) );
      }
      return projectAll;
   }


I recognise that any number of things may be going wrong. I've tried playing around with the HQL statement a bit to see what kind of results I can get, but have settled on using the syntax provided by the tutorial. Using a test class, I receive this error in calling this method:

Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: project is not mapped. [FROM project as p]

I have a mapping configuration file for the object. Do I need to add anything or even have another file for mapping an object from a relational database or should I be using the same mapping as that for object -> schema? Does anyone have a good resource for valid SQL/HSQL statements? I only need to learn basic SQL statements to make appropriate queries to the database, and plan to learn more SQL from there. I'm confused about the compatibility between SQL and HSQL, and what constitutes a valid SQL statement. For example, MySQL query browser is using this to query the table:
SELECT * FROM hibernate10.project p
The same statment does not seem to be valid in the java class, as it causes even more problems. Can someone explain to me what is going on here?

Also, the Log4J initialization line is there because I was getting errors concerning Log4J. Is there a more appropriate thing to do? That line doesn't seem so elegant, and I'm not currently using Log4J for anything.

Thanks!
Merci bien!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
cron
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.