-->
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.  [ 25 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: Most effective way to access data via hibernate
PostPosted: Tue Oct 26, 2004 10:01 pm 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
Hi,
I am currently using JBoss 3.2.6 and am accessing data via jdni in the following manner:

InitialContext ctx = new InitialContext();
sessionfactory = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory");
session = sessionfactory.openSession();
transaction = session.beginTransaction();

I'm looking for a non ejb solution to accessing data from hibernate using jdni, i.e. a Hibernate method, can anybody please point me documentation which details this?

regards


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 5:15 am 
Beginner
Beginner

Joined: Mon Aug 16, 2004 6:09 am
Posts: 46
Location: Geneva, Switzerland
What do you mean non ejb solution? From where are you accessing hibernate? servlets? mbeans?

Anyway, preferred way to access hibernate session is
Code:
Session session = HibernateContext.getSession("java:/hibernate/SessionFactory").

You must be in transaction when asking for session (therefore, I think that ejb is the best place for hibernate access code).
Session will be flushed when transaction commits and closed when transaction ends. jboss will do all session cleanup work for you. No need to call session.openTransaction() as well, since hibernate knows how to lookup JTA transaction.[/code]


Top
 Profile  
 
 Post subject: Octoupus
PostPosted: Wed Oct 27, 2004 5:37 am 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
I am using JBoss 3.2.6. I have tried the method you used as follows and could not get it to work:

try {
session = org.jboss.hibernate.session.HibernateContext.getSession("java:/HibernateFactory");

transaction = session.(begin/open)Transaction();
session.save(myOrder);

transaction.commit();

} catch (Exception sql) {
throw new RuntimeException("Exception: " + sql.getMessage(), sql);

}

I think it is not being within a transaction that is causing the problem. How do I ensure that the session is within a transaction. could you use the above code as an example?


many thanks


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 6:03 am 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
This is the code I have used which does not work:

session = org.jboss.hibernate.session.HibernateContext.getSession("java:/HibernateFactory");
transaction = session.beginTransaction();

//Get User details
query = session.createQuery("from test.User as user where user.UserName=:username and user.UserPassword=:password")
.setString("username",username)
.setString("password",password);
user = (User) query.uniqueResult();

transaction.commit();

In the jboss logs I get:

2004-10-27 11:02:20,573 INFO [org.apache.jk.server.JkCoyoteHandler] Response already commited

Nothing is returned, hence the reason I have been using ctx.lookup. Any ideas what is going wrong?

many thanks


Andrew


Top
 Profile  
 
 Post subject: Is this the cause
PostPosted: Wed Oct 27, 2004 7:44 am 
Newbie

Joined: Fri Sep 10, 2004 9:46 am
Posts: 10
IMHO I think your problem is your use of the HibernateContext.getSession(String name) method.

This method expects to work within the concept of JTA transaction, ie you should not be issuing begin/commit on Hibernate session, but on a JTA transaction. The easiest way to do this is inside an EJB, as you declare the transactions in the deployment.

If you are not using EJB's then you manage transaction on the JTA transaction manager, which you obtain via the following line of code. A transaction must be started before you make you call on HibernateContext to obtain the Hibernate session.

Code:
TransactionManager tm = (new InitialContext()).lookup( "java:/TransactionManager" );


Hope this helps.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 8:54 am 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
Can you elaborate a bit more on the useage?

I have tried:

import javax.transaction.TransactionManager;
import javax.transaction.Transaction;

......


transaction = tm.getTransaction();
session = org.jboss.hibernate.session.HibernateContext.getSession("java:/hibernate/SessionFactory");
transaction.commit();

Still I get nothing. All I get from the logs is:

2004-10-27 13:50:34,659 INFO [org.apache.jk.server.JkCoyoteHandler] Response already commited

What is wrong here?


regards


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 10:04 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 3:00 pm
Posts: 1816
Location: Austin, TX
[/quote]
transaction = tm.getTransaction();
session = org.jboss.hibernate.session.HibernateContext.getSession("java:/hibernate/SessionFactory");
transaction.commit();
[/quote]

First, you need to be dealing with the UserTransaction, not the Transaction. The Transaction object is a container object and not meant for usage by applications).

Second, just obtaining a UserTransaction is not "running in a transaction". You need to make sure you begin() the transaction...

So, if you are not using CMT, this would look something like:
Code:
UserTransaction transaction = (UserTransaction) context.lookup("java:/UserTransaction");
transaction.begin();

Session session = HibernateContext.getSession("java:/hibernate/SessionFactory");

// do something

transaction.commit();



Quote:
2004-10-27 13:50:34,659 INFO [org.apache.jk.server.JkCoyoteHandler] Response already commited

This is an error from the web container. It has nothing to do with transactions being committed; it is talking about the http reponse having already been committed. There is another error somewhere which is causing this one...


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 10:52 am 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
still nothing is being returned. Hibernate is being run as an mbean:

hibernate-service.xml:

<mbean code="org.jboss.hibernate.jmx.Hibernate" name="jboss.har:service=Hibernate">
<depends>jboss.jca:service=LocalTxCM,name=PostgresDS</depends>
<attribute name="SessionFactoryName">java:/hibernate/SessionFactory</attribute>
<attribute name="DatasourceName">java:/PostgresDS</attribute>
<attribute name="Dialect">net.sf.hibernate.dialect.PostgreSQLDialect</attribute>
<attribute name="Hbm2ddlAuto"></attribute>
<attribute name="Password">postgres</attribute>
<attribute name="Username">postgres</attribute>
<attribute name="ShowSqlEnabled">true</attribute>
<attribute name="JdbcBatchSize">25</attribute>
</mbean>

Does hibernate being run like this have an impact on the code mentioned?

regards


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 12:49 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 3:00 pm
Posts: 1816
Location: Austin, TX
Quote:
Does hibernate being run like this have an impact on the code mentioned?

Um, sure. It's what allows code like mentioned :)

Could you possibly elaborate on what you mean by "still nothing is being returned"?

Also, why is this like pulling teeth? Why don't you just post the code you are using, tell us exactly what is happening in error, and describe what you'd like to see? Easier for you and us...


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 2:06 pm 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
Ok here goes,
I can currently access data from postgreSQL (7.4.1) via Hibernate using jndi like so:

User.class:

try {
InitialContext ctx = new InitialContext();
sessionfactory = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory");
session = sessionfactory.openSession();
transaction = session.beginTransaction();

//Get User details
query = session.createQuery("from test.User as user where user.UserName=:username and user.UserPassword=:password")
.setString("username",username)
.setString("password",password);
user = (User) query.uniqueResult();

transaction.commit();
session.close();

}

but I understand that the preferred way to access data via Hibernate is to use:

org.jboss.hibernate.session.HibernateContext.getSession("java:/hibernate/sessionFactory")

which I have tried to implement with little success so far. I am not getting an errors, but no data is being returned to the user. How can I implement org.jboss.hibernate.session.HibernateContext.getSession("java:/hibernate/sessionFactory") with my current setup?

1. hibernate.cfg.xml

<hibernate-configuration>

<session-factory>
<!-- Use a Tomcat JNDI datasource -->
<mapping resource="test/User.hbm.xml"/>
<mapping resource="test/Artist.hbm.xml"/>
<mapping resource="test/ArtistImages.hbm.xml"/>
<mapping resource="test/Stock.hbm.xml"/>
<mapping resource="test/StockImages.hbm.xml"/>
<mapping resource="test/Order.hbm.xml"/>
<mapping resource="test/OrderItem.hbm.xml"/>

<property name="hibernate.cache.provider_class">net.sf.hibernate.cache.EhCache</property>
<class-cache class="org.hibernate.auction.model.Order" usage="transactional"/>
<collection-cache collection="org.hibernate.auction.model.Order.OrderItem" usage="transactional"/>
<class-cache class="org.hibernate.auction.model.ArtistImages" usage="transactional"/>
<class-cache class="org.hibernate.auction.model.User" usage="transactional"/>
</session-factory>

</hibernate-configuration>

2. hibernate-service.xml

<mbean code="org.jboss.hibernate.jmx.Hibernate" name="jboss.har:service=Hibernate">
<depends>jboss.jca:service=LocalTxCM,name=PostgresDS</depends>
<attribute name="SessionFactoryName">java:/hibernate/SessionFactory</attribute>
<attribute name="DatasourceName">java:/PostgresDS</attribute>
<attribute name="Dialect">net.sf.hibernate.dialect.PostgreSQLDialect</attribute>
<attribute name="CacheProviderClass">net.sf.ehcache.hibernate.Provider</attribute>
<attribute name="ShowSqlEnabled">true</attribute>
</mbean>

3. postgres-ds.xml

<local-tx-datasource>
<jndi-name>PostgresDS</jndi-name>
<connection-url>jdbc:postgresql://localhost:5432/beyarecords</connection-url>
<driver-class>org.postgresql.Driver</driver-class>
<user-name>postgres</user-name>
<password>postgres</password>
</local-tx-datasource>

4. User.hbm.xml

<class name="User" table="usertbl">
<cache usage="read-write"/>
<id name="ID" column="user_id" type="integer" unsaved-value="0">
<generator class="sequence">
<param name="sequence">seq_user_mytable</param>
</generator>
</id>
<property name="FirstName" column="first_name" type="string" not-null="true"/>
<property name="LastName" column="last_name" type="string" not-null="true"/>
<property name="Address1" column="address1" type="string"/>
<property name="Address2" column="address2" type="string"/>
<property name="Address3" column="address3" type="string"/>
<property name="PostCode" column="postcode" type="string"/>
<property name="Country" column="country" type="string"/>
<property name="Email" column="email" type="string" not-null="true"/>
<property name="HomeTel" column="home_telephone" type="string"/>
<property name="HomeMob" column="mobile_telephone" type="string"/>
<property name="DateJoined" column="date_joined" type="timestamp"/>

<property name="UserName" type="string">
<column name="username" unique-key="UserPassKey"/>
</property>
<property name="UserPassword" type="string">
<column name="userpassword" unique-key="UserPassKey"/>
</property>

<set name="ArtistChoice" table="choicetbl">
<key column="user_id"/>
<many-to-many column="artist_id" class="test.Artist"/>
</set>
</class>


regards


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 2:13 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 3:00 pm
Posts: 1816
Location: Austin, TX
First, take a look at: http://www.jboss.org/wiki/Wiki.jsp?page=JBossHibernate

Second, is the code you mention executing within/behind an ejb?


Top
 Profile  
 
 Post subject:
PostPosted: Wed Oct 27, 2004 3:00 pm 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
I have already had a look at the page you mentioned, it basically tells me what you guys have already informed me of here.
In terms of where my code is well I am running my class files from

deploy/jbossweb-tomcat50.sar/cocoon.war/web-inf/classes/test/*.Class

As for my code:

package test;

import java.util.*;
import java.util.Set;
import java.util.HashSet;

import net.sf.hibernate.*;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.Query;
import org.jboss.hibernate.session.HibernateContext;
import javax.naming.InitialContext;
import java.io.Serializable;
import javax.transaction.UserTransaction;

public class User implements Serializable{

private int ID;
private String FirstName;
private String LastName;
private String Address1;
private String Address2;
private String Address3;
private String PostCode;
private String Country;
private String Email;
private String HomeTel;
private String HomeMob;
private Date DateJoined;
private String UserName;
private String UserPassword;
private Set ArtistChoice = new HashSet();

public User(){
}

public int getID() {
return ID;
}
public void setID(int newUserID) {
this.ID = newUserID;
}

public String getFirstName() {
return (FirstName);
}
public void setFirstName(String newfirstName) {
this.FirstName = newfirstName;
}

public String getLastName() {
return (LastName);
}
public void setLastName(String newlastName) {
this.LastName = newlastName;
}

public String getAddress1() {
return Address1;
}
public void setAddress1(String newAddress1) {
this.Address1 = newAddress1;
}

public String getAddress2() {
return Address2;
}
public void setAddress2(String newAddress2) {
this.Address2 = newAddress2;
}

public String getAddress3() {
return Address3;
}
public void setAddress3(String newAddress3) {
this.Address3 = newAddress3;
}

public String getPostCode() {
return PostCode;
}
public void setPostCode(String newPostCode) {
this.PostCode = newPostCode;
}

public String getCountry() {
return Country;
}
public void setCountry(String newCountry) {
this.Country = newCountry;
}

public String getEmail() {
return Email;
}
public void setEmail(String newEmail) {
this.Email = newEmail;
}

public String getHomeTel() {
return HomeTel;
}
public void setHomeTel(String newHomeTel) {
this.HomeTel = newHomeTel;
}

public String getHomeMob() {
return HomeMob;
}
public void setHomeMob(String newHomeMob) {
this.HomeMob = newHomeMob;
}

public Date getDateJoined() {
return DateJoined;
}
public void setDateJoined(Date newDateJoined) {
this.DateJoined = newDateJoined;
}

public String getUserName() {
return UserName;
}
public void setUserName(String newUserName) {
this.UserName = newUserName;
}

public String getUserPassword() {
return UserPassword;
}
public void setUserPassword(String newUserPassword) {
this.UserPassword = newUserPassword;
}

public Set getArtistChoice() {
return ArtistChoice;
}
public void setArtistChoice(Set newArtistChoice) {
this.ArtistChoice = newArtistChoice;
}

public static User getUser (String username, String password)
{
User user = null;
Transaction transaction = null;
Session session = null;
SessionFactory sessionfactory = null;
Query query = null;

try {
InitialContext ctx = new InitialContext();
sessionfactory = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory");
session = sessionfactory.openSession();
transaction = session.beginTransaction();

//Get User details
query = session.createQuery("from test.User as user where user.UserName=:username and user.UserPassword=:password")
.setString("username",username)
.setString("password",password);
user = (User) query.uniqueResult();

transaction.commit();
session.close();

} catch (Exception e) {

throw new RuntimeException("Exception in Hibernate:: " + e.getMessage(), e);
}



return user;
}

}

Hope that is plenty information


regards


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Sat Oct 30, 2004 6:24 am 
Newbie

Joined: Fri Sep 10, 2004 9:46 am
Posts: 10
Quote:
Second, is the code you mention executing within/behind an ejb?


Andrew, you havent answered Steves question. But you do mention running inside war. This is not inside EJB, and as such, a UserTransaction is not be managed for you, you must do this yourself using using steves code. Below.

HibernateContext.getSession() expect a JTA transaction to be active, it will fail if one is not present.

Code:
UserTransaction transaction = (UserTransaction) context.lookup("java:/UserTransaction");
transaction.begin();

Session session = HibernateContext.getSession("java:/hibernate/SessionFactory");

// do something

transaction.commit();


IMHO There may be little advantage in converting to the above methodology in your current environment, as you still have to manage the transaction, just in a different way.

The main advantage will be where you have to manage transactions for a secondary resource (not Hibernate), where you would have handle two trasactions in the same code. Using JTA just allows you to see it as one transaction.

The other advantage comes from using EJBs which mange the transactions (JTA) for you. Remember JTA is just a standard way of managing transactions across different components.

Hope this helps.


Top
 Profile  
 
 Post subject:
PostPosted: Sat Oct 30, 2004 6:31 am 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
mpruden,
how do I use the EJB approach? I take it that I would not have Hibernate as a .war, so how would I specify it so that I can get EJBs to manage the transactions?

thanks


Andrew


Top
 Profile  
 
 Post subject:
PostPosted: Sat Oct 30, 2004 6:43 am 
Regular
Regular

Joined: Fri Oct 08, 2004 4:11 am
Posts: 78
Location: Nottingham, England
Am I right in saying that instead of running cocoon as a .war, to take advantage of 'EJBs which mange the transactions (JTA)', I need to run it as an .Ear?

thanks


Andrew


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 25 posts ]  Go to page 1, 2  Next

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:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.