-->
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: problem in commiting transaction
PostPosted: Wed Jun 21, 2006 9:12 am 
Newbie

Joined: Wed Jun 21, 2006 8:55 am
Posts: 1
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp

Hibernate version:2.0

Mapping documents:
<class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">

<!-- A 32 hex character is our surrogate key. It's automatically
generated by Hibernate with the UUID pattern. -->
<id name="id" type="string" unsaved-value="null" >
<column name="CAT_ID" sql-type="char(32)" not-null="true"/>
<generator class="uuid.hex"/>
</id>

<!-- A cat has to have a name, but it shouldn' be too long. -->
<property name="name">
<column name="NAME" length="16" not-null="true"/>
</property>

<property name="sex"/>

<property name="weight"/>

</class>


Code between sessionFactory.openSession() and session.close():
Session session = HibernateUtil.currentSession();
//inserting data in Cat Table
Transaction tx=null;
tx=session.beginTransaction();
Contact cat = (Contact) session.load( Contact.class, new Integer(1));
cat.setFirstName("PK");
session.save(cat);
tx.commit();


Full stack trace of any exception that occurs:
exception

javax.servlet.ServletException
org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:523)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


root cause

java.lang.NullPointerException
net.sf.hibernate.impl.SessionImpl.preFlushEntities(SessionImpl.java:2253)
net.sf.hibernate.impl.SessionImpl.flushEverything(SessionImpl.java:2018)
net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2007)
net.sf.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:57)
net.sf.hibernate.examples.quickstart.ContactAction.execute(ContactAction.java:43)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)




Name and version of the database you are using:
SAPDB


The generated SQL (show_sql=true):
No generated sql


Debug level Hibernate log excerpt:
i dont know about this plz also tell me how to get this

_________________
Pankaj Chaudhary
Soft. Engg.
Bars Technologies Pvt Ltd.
New Delhi


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jun 21, 2006 9:24 am 
Regular
Regular

Joined: Mon May 08, 2006 6:00 am
Posts: 53
Location: India
Code between sessionFactory.openSession() and session.close():
Session session = HibernateUtil.currentSession();
//inserting data in Cat Table
Transaction tx=null;
tx=session.beginTransaction();
Contact cat = (Contact) session.load( Contact.class, new Integer(1));
cat.setFirstName("PK");
session.save(cat);
tx.commit();

In above code not sure whether you shall be doing session.save(cat);

I think you shall use session.update(cat) or session.saveOrUpdate(cat) as you are trying to altear a record which already exist

Sudhir


Top
 Profile  
 
 Post subject: problem with inserting values in database using hibernae.
PostPosted: Wed Jun 21, 2006 9:55 am 
Newbie

Joined: Wed Jun 21, 2006 9:25 am
Posts: 5
Location: India
Hi ! i am new to hibernate i had read the quickstart guide of hibernate and write a small application using hibernate,which insert values in database;
i am using following:
Hibernate 3.0
jdk 1.5
tomcat 5.5.12
struts1.2
SAP DB

i had written following files:

Configuration file:
hibernate.cfg.xml


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

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.sap.dbtech.jdbc.DriverSapDB</property>
<property name="hibernate.connection.url">jdbc:sapdb://localhost/BARSDB?sqlmode=oracle</property>
<property name="hibernate.connection.username">local</property>
<property name="hibernate.connection.password">local</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">net.sf.hibernate.dialect.SAPDBDialect</property>

<!-- Mapping files -->
<mapping resource="Contact.hbm.xml"/>
<mapping resource="Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>


Mapping File:
Contact.hbm.xml



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

<hibernate-mapping>
<class name="net.sf.hibernate.examples.quickstart.Contact" table="CONTACT">
<id name="id" type="int" column="ID" >
<generator class="assigned"/>
</id>

<property name="firstName">
<column name="FIRSTNAME" />
</property>

<property name="lastName">
<column name="LASTNAME"/>
</property>

<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>



Bean Class:
Contact.java

package net.sf.hibernate.examples.quickstart;

/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: Jun 20, 2006
* Time: 4:29:11 PM
* To change this template use File | Settings | File Templates.
*/
public class Contact {
private String firstName;
private String lastName;
private String email;
private int id;

/**
* @return Email
*/
public String getEmail() {
return email;
}

/**
* @return First Name
*/
public String getFirstName() {
return firstName;
}

/**
* @return Last name
*/
public String getLastName() {
return lastName;
}

/**
* @param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}

/**
* @param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}

/**
* @param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}

/**
* @return ID Returns ID
*/

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
}



HibernateUtil helper class:

HibernateUtil.java



package net.sf.hibernate.examples.quickstart;

import net.sf.hibernate.*;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Transaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;
import org.apache.commons.lang.*;
import org.apache.commons.lang.exception.NestableException;


public class HibernateUtil {

private static Log log = LogFactory.getLog(HibernateUtil.class);

private static SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory

sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
static ThreadLocal transaction = new ThreadLocal();

public static Session currentSession() {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
try {
s = sessionFactory.openSession();
session.set(session);
Transaction tr = s.beginTransaction();
session.set(session);
transaction.set(tr);

if (log.isDebugEnabled()) {
log.debug("created session and started new transaction");
}

} catch (HibernateException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
session.set(s);
}
return s;
}

public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}



and in last my servlet Action class:
ContactAction.java



package net.sf.hibernate.examples.quickstart;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Iterator;

import net.sf.hibernate.Session;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Transaction;


public class ContactAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res )throws Exception {


try
{

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/BARSDB");
if(ds!=null){
Connection conn = ds.getConnection();
}
Session session = HibernateUtil.currentSession();
Query query = session.createQuery("select c from Contact as c where c.id = :id");
query.setInteger("id", 2);
for (Iterator it = query.iterate(); it.hasNext();) {
Contact cat = (Contact) it.next();
System.out.println("First Name: " + cat.getFirstName() );
}


Contact princess =new Contact();
Transaction t = session.beginTransaction();

princess.setFirstName("Princess");
princess.setLastName("pri");
princess.setEmail("pri@yahoo.com");
princess.setId(1);
session.saveOrUpdate(princess);
t.commit();
session.close();
HibernateUtil.closeSession();
} catch (HibernateException e) {
e.printStackTrace();
}
return mapping.findForward("success");
}
}



and my strutsconfig.xml is as under:


<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<!--
This is a blank Struts configuration file with an example
welcome action/page and other commented sample elements.

Tiles and the Struts Validator are configured using the factory defaults
and are ready-to-use.

NOTE: If you have a generator tool to create the corresponding Java classes
for you, you could include the details in the "form-bean" declarations.
Otherwise, you would only define the "form-bean" element itself, with the
corresponding "name" and "type" attributes, as shown here.
-->


<struts-config>

<!-- ============================================ Data Source Configuration -->
<!--
<data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<set-property
property="driverClassName"
value="org.postgresql.Driver" />
<set-property
property="url"
value="jdbc:postgresql://localhost/mydatabase" />
<set-property
property="username"
value="me" />
<set-property
property="password"
value="test" />
<set-property
property="maxActive"
value="10" />
<set-property
property="maxWait"
value="5000" />
<set-property
property="defaultAutoCommit"
value="false" />
<set-property
property="defaultReadOnly"
value="false" />
<set-property
property="validationQuery"
value="SELECT COUNT(*) FROM market" />
</data-source>
</data-sources>
-->

<!-- ================================================ Form Bean Definitions -->

<form-beans>

<!-- sample form bean descriptor for a DynaActionForm-->
<form-bean
name="cat"
type="org.apache.struts.action.DynaActionForm">
<form-property
name="name"
type="java.lang.String"/>
<form-property
name="sex"
type="java.lang.String"/>
<form-property
name="weight"
type="java.lang.String"/>

</form-bean>

<form-bean
name="contact"
type="net.sf.hibernate.examples.quickstart.Contact">
</form-bean>




<!-- sample form bean descriptor for an ActionForm
<form-bean
name="inputForm"
type="app.InputForm"/>
end sample -->

<!-- sample form bean descriptor for a DynaActionForm
<form-bean
name="logonForm"
type="org.apache.struts.action.DynaActionForm">
<form-property
name="username"
type="java.lang.String"/>
<form-property
name="password"
type="java.lang.String"/>
</form-bean>
end sample -->
</form-beans>


<!-- ========================================= Global Exception Definitions -->

<global-exceptions>
<!-- sample exception handler
<exception
key="expired.password"
type="app.ExpiredPasswordException"
path="/changePassword.jsp"/>
end sample -->
</global-exceptions>


<!-- =========================================== Global Forward Definitions -->

<global-forwards>
<!-- Default forward to "Welcome" action -->
<!-- Demonstrates using index.jsp to forward -->
<forward
name="welcome"
path="/Welcome.do"/>
</global-forwards>


<!-- =========================================== Action Mapping Definitions -->

<action-mappings>
<!-- Default "Welcome" action -->
<!-- Forwards to Welcome.jsp -->
<action
path="/Welcome"
forward="/pages/addcontact.jsp"/>

<action
path="/addcontact"
type="net.sf.hibernate.examples.quickstart.ContactAction"
name="contact"
scope="request"
input="/pages/addcontact.jsp">

<forward name="success" path="/pages/success.jsp"/>
</action>
<!-- sample input and input submit actions

<action
path="/Input"
type="org.apache.struts.actions.ForwardAction"
parameter="/pages/Input.jsp"/>

<action
path="/InputSubmit"
type="app.InputAction"
name="inputForm"
scope="request"
validate="true"
input="/pages/Input.jsp"/>

<action
path="/edit*"
type="app.Edit{1}Action"
name="inputForm"
scope="request"
validate="true"
input="/pages/Edit{1}.jsp"/>

end samples -->
</action-mappings>


<!-- ============================================= Controller Configuration -->

<controller
processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>


<!-- ======================================== Message Resources Definitions -->

<message-resources parameter="MessageResources" />


<!-- =============================================== Plug Ins Configuration -->

<!-- ======================================================= Tiles plugin -->
<!--
This plugin initialize Tiles definition factory. This later can takes some
parameters explained here after. The plugin first read parameters from
web.xml, thenoverload them with parameters defined here. All parameters
are optional.
The plugin should be declared in each struts-config file.
- definitions-config: (optional)
Specify configuration file names. There can be several comma
separated file names (default: ?? )
- moduleAware: (optional - struts1.1)
Specify if the Tiles definition factory is module aware. If true
(default), there will be one factory for each Struts module.
If false, there will be one common factory for all module. In this
later case, it is still needed to declare one plugin per module.
The factory will be initialized with parameters found in the first
initialized plugin (generally the one associated with the default
module).
true : One factory per module. (default)
false : one single shared factory for all modules
- definitions-parser-validate: (optional)
Specify if xml parser should validate the Tiles configuration file.
true : validate. DTD should be specified in file header (default)
false : no validation

Paths found in Tiles definitions are relative to the main context.
-->

<plug-in className="org.apache.struts.tiles.TilesPlugin" >

<!-- Path to XML definition file -->
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
<!-- Set Module-awareness to true -->
<set-property property="moduleAware" value="true" />
</plug-in>


<!-- =================================================== Validator plugin -->

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

</struts-config>



Now My problem is:

in the action u can see the select query.
this query is successfully selecting the data from table.
but when i m inserting values in table
if i commit the transaction by: t.commit();
then it gives java.lang.nullpointerException.
and if i commented this statement(t.commit()) then nothing happen ;
no exception,no error and no result in short no value in database is inserted.
Please help me getting out of this problem.
Thanks .


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