-->
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.  [ 6 posts ] 
Author Message
 Post subject: How to Insert using Hibernate
PostPosted: Thu Sep 29, 2005 6:59 pm 
Newbie

Joined: Wed Aug 17, 2005 10:50 am
Posts: 11
Hello,

I am tried to insert a row in the database using Hibernate. I am not able to do. Also I am not getting any error. But I am albe to select the fields from the database properly. This is code I am using for inserting:

[code]
session.createSQLQuery("Insert into FieldOffice (FieldOfficeNumber, FieldOfficeAlpha, ID)" +" values('"+fldOffCde+"', 'dfeer', 65)");

[/code]

Also I tried using:

[code]
session.save(fogs1,new Integer(65));
[/code]

but nothing works. On the output console for select, it outputs the SQL query but for insert it does not output anything neither it shows any errors.
This is the query I use for select:
[code]
session.createQuery("from FieldOfficeGS as fgs1 where " +" fgs1.FldOffNumber like '"+fldOffCde+"'")

[/code]

Please let me know if I am missing anything in the XML file or anywhere for which I will be very much thankful to you.

Arun.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 29, 2005 7:54 pm 
Expert
Expert

Joined: Mon Jul 04, 2005 5:19 pm
Posts: 720
createSQLQuery currently only supports retrieval. everything else is done via the Session interface . session.save is used to insert. if this does not work, it is because you need to call Transaction.commit().


Top
 Profile  
 
 Post subject: How to Insert using Hibernate
PostPosted: Thu Sep 29, 2005 8:23 pm 
Newbie

Joined: Wed Aug 17, 2005 10:50 am
Posts: 11
Dennis,

Thanks for the reply. Yes I am calling commit in my code, here is my complete code. pls Let me know.

Java Code:
[code]
package ne.dds.caseControl.efi.services;

import ne.dds.caseControl.efi.hibernate.HibernateUtil;
import ne.dds.caseControl.efi.util.*;
import ne.dds.caseControl.efi.formbeans.*;
import org.apache.struts.util.LabelValueBean;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.sql.*;

public class FOAlphaDetermination {

int flag =0;//variable used to find out if fldOffCde exists or not
public void setFldAlphaValue()
{
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
String fldOffCde="7226d";


Connection conn = null;
ArrayList offCodesList = new ArrayList();
ArrayList addCodesList = new ArrayList();

try {
System.out.println("Driver being accessed");

ResultSet res = null;

offCodesList.add(
new LabelValueBean(
"Select from list or type Refusal Description", null));


Statement st = session.connection().createStatement();
String sql = "select * from FieldOffice";
res = st.executeQuery(sql);
res.next();
if (!(res.getRow() == 0))
{
do {
String code=res.getString("FieldOfficeNumber");
offCodesList.add(new LabelValueBean(code, code));
addCodesList.add(code);
} while (res.next());
}

res.close();
for(int i=0; i<addCodesList.size(); i++)
{

if(addCodesList.get(i)==null)
{
addCodesList.set(i,"");
}
if(addCodesList.get(i).toString().trim().equals(fldOffCde))
{
System.out.println("Got it");
flag=1;
List result1 = session.createQuery("from FieldOfficeGS as fgs1 where " +
" fgs1.FldOffNumber like '"+fldOffCde+"'").list();

}

}

if(flag==0)
{
System.out.println("Did not Get it");
FieldOfficeGS fogs1 = new FieldOfficeGS(fldOffCde);
session.createSQLQuery("Insert into FieldOffice (FieldOfficeNumber, FieldOfficeAlpha, ID)" +
" values('"+fldOffCde+"', 'dfeer', 65)");
// fogs1.setId(65);
// session.get(FieldOfficeGS.class, "62");
session.save(fogs1,new Integer(65));
System.err.println(fogs1.toString());
// session.saveOrUpdate(fldOffCde);
}

tx.commit();
session.close();


}//END OF TRY
catch (SQLException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}

}

}
[/code]

XML Code
[code]
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"D:\neddsWorkspace\neddsWeb\Java Source\hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="ne.dds.caseControl.efi.util.FieldOfficeGS" table="FieldOffice" dynamic-update="true" select-before-update="true">
<id name="id" column="ID" type="int" unsaved-value="-1">
<generator class="assigned" />
</id>

<property name="FldOffNumber" column="FieldOfficeNumber" type="string"/>
<property name="FldAlphaNum" column="FieldOfficeAlpha" type="string"/>
</class>
</hibernate-mapping>
[/code]







Hibernate mapping Code
[code]
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"D:\neddsWorkspace\neddsWeb\Java Source\hibernate-configuration-3.0.dtd">
<!-- D:\Mystery\TestSample\JavaSource\ -->
<hibernate-configuration>

<session-factory>
<property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://172.31.68.220:1433/backupcasemsbesql;TDS=4.2</property>
<!-- jdbc:jtds:sqlserver://172.31.68.130:1433/Northwind;TDS=4.2 -->
<!-- jdbc:jtds:sqlserver://172.31.68.220:1433/backupcasemsbesql;TDS=4.2 -->
<property name="hibernate.connection.username">jimw</property>
<property name="hibernate.connection.password"></property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="show_sql">true</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name="hibernate.cache.provider_class">
org.hibernate.cache.HashtableCacheProvider
</property>
<property name="hibernate.hbm2ddl.auto">update</property>



<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>

<property name="hibernate.cglib.use_reflection_optimizer">false</property>
<property name="hibernate.cache.use_query_cache">false</property>

<property name="hibernate.cache.use_minimal_puts">false</property>


<mapping resource="ne/dds/caseControl/efi/mapping/FieldOffice.hbm.xml"/>

</session-factory>

</hibernate-configuration>


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 29, 2005 8:47 pm 
Expert
Expert

Joined: Mon Jul 04, 2005 5:19 pm
Posts: 720
well, like I said, the insert is not going to work w/ createSQLQuery and it's entirely possible this is interfering w/ the following line of code. you might want to shy away from calling session.connection().createStatement();

If you need the FieldOffices, use H w/ " from FieldOffice", not JDBC .


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 29, 2005 9:16 pm 
Beginner
Beginner

Joined: Tue Sep 06, 2005 5:16 pm
Posts: 24
Location: USA
Try this it'll definitely work

Code:
package com.genuitec.hibernate;
import net.sf.hibernate.*;


public class HibernateTest {
   public static void main(String[] args) {
      // Step 1 - Create a new entity
      EchoMessage message = new EchoMessage();
     // Step 2 - Set message field
      message.setMsg("Hello Hibernate, from MyEclipse!");

      try {
         // Step 3 - Get a Hibernate Session
         Session session = SessionManager.currentSession();
         // Step 4 - Persist entity to database
         Transaction tx = session.beginTransaction();
         session.save(message);
         tx.commit();
         System.out.println("Save successful.");
      } catch (HibernateException e) {
         System.out.println("Save failed.");
      } finally {
         try {
            // Step 5 - close the session
            SessionManager.closeSession();
         } catch (HibernateException e1) {
            // do nothing
         }
      }
   }
}


Top
 Profile  
 
 Post subject: How to Insert using Hibernate
PostPosted: Fri Sep 30, 2005 1:47 pm 
Newbie

Joined: Wed Aug 17, 2005 10:50 am
Posts: 11
Thank you very much Dennis and Srinivas, I learned something new today. Thanks once again,

Arun.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 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.