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.  [ 8 posts ] 
Author Message
 Post subject: Unable to Save the object of a child class
PostPosted: Mon Oct 12, 2009 6:35 am 
Newbie

Joined: Sun Oct 11, 2009 2:32 am
Posts: 5
Hi,

Am relatively new to Hibernate. However, i am stuck, please help.

Brief Background:

The application is to get information about different machines and store the info in the database.

One main class: MachineDetails. Primary key is the IP address.
Another child class "HardDiscDetails". There is a foreign key constraint from the main class to the child class(for the field NIC_IP). I am using a string as a primary key, i wonder if that could be causing the issue (I have not seen many examples of this type)

MachineDetails.hbm.xml:
Code:

<?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="MachineDetails" table="MachineDetails">
        <id name="NIC_IP" type="string" unsaved-value="null" >
            <column name="NIC_IP" sql-type="char(32)"
                    not-null="true"/>
            <generator class="assigned"/>
        </id>
   
<property name="AppId">
<column name="AppId"/>
</property>
<property name="Vendor">
<column name="Vendor"/> 
</property>
<property name="Model">   
<column name="Model"/>     
</property>
<property name="HDCount">
<column name="HDCount"/>
</property>
</class>
</hibernate-mapping>
   

HardDiscDetails.hbm.xml
Code:
   
<?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="HardDiscDetails" table="HardDiscDetails">
  <id name="HardDiscID" type="long" column="HardDiscID" >
        <generator class="increment"/>
     </id>
<property name="HardDiscNumber">
<column name="HardDiscNumber"/>
</property>
<property name="HardDiscName">
<column name="HardDiscName"/>
</property>
<property name="HardDiscSize">
<column name="HardDiscSize"/>
</property>
<many-to-one name="NIC_IP" class="MachineDetails" column="NIC_IP"/>
  </class>
</hibernate-mapping>


Pojo for MachineDetails
Code:
 
public class MachineDetails
{
private String AppId;
private String Vendor;
private String Model;
private String NIC_IP ;
private String HDCount;

public void setAppId(String SAppId)
{
   AppId = SAppId;
}
public String getAppId()
{
return AppId;
}
/* --------------------------------- */
public void setVendor(String SVendor)
{
   Vendor=SVendor;
}
public String getVendor()
{
return Vendor;
}

/* --------------------------------- */
public void setModel(String SModel)
{
   Model=SModel;
}
public String getModel()
{
return Model;
}

public void setNIC_IP(String SNIC_IP)
{
   NIC_IP = SNIC_IP;
}
public String getNIC_IP()
{
return NIC_IP;
}

public void setHDCount(String SHDCount)
{
   HDCount=SHDCount;
}
public String getHDCount()
{
return HDCount;
}

}
 

Pojo for HardDiscDetails
Code:
 
public class HardDiscDetails
{

private String HardDiscNumber ;
private String HardDiscName ;
private String HardDiscSize ;
private String NIC_IP ;
private long HardDiscID;

public void setHardDiscID(long SHardDiscID)
{
HardDiscID=SHardDiscID;
}
public long getHardDiscID()
{
return HardDiscID;
}

public void setHardDiscNumber(String SHardDiscNumber)
{
   HardDiscNumber= SHardDiscNumber;
}
public String getHardDiscNumber()
{
return HardDiscNumber;
}

public void setHardDiscName(String SHardDiscName)
{
   HardDiscName = SHardDiscName;
}
public String getHardDiscName()
{
return HardDiscName;
}

public void setHardDiscSize(String SHardDiscSize)
{
   HardDiscSize = SHardDiscSize;
}
public String getHardDiscSize()
{
return HardDiscSize;
}


public void setNIC_IP(String SNIC_IP)
{
   NIC_IP = SNIC_IP;
}
public String getNIC_IP()
{
return NIC_IP;
}

}
 

Servlet
Code:
   
public class InventoryMonitorServlet extends HttpServlet
{

private Connection conn;
SessionFactory SessFact;
Session Sess;
MachineDetails macdel;
HardDiscDetails hadel;

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
try
{

String AppId="";
String Vendor="";
String Model="";
String NIC_IP="";
String HDCount="";

AppId=req.getParameter("AppId");
Vendor=req.getParameter("Vendor");
Model=req.getParameter("Model");
HDCount=req.getParameter("HDCount");
NIC_IP=req.getParameter("NIC_IP");

int NICRegister = Integer.parseInt(NICCount.trim());
int HDRegister = Integer.parseInt(HDCount.trim());

if (NICRegister > 0)
{
SessFact = new Configuration().configure().buildSessionFactory();
Sess =SessFact.openSession();
Transaction CurrTran = Sess.beginTransaction();
     
for (int j=0;j<NICRegister;j++)
{
   NIC_IP = req.getParameter("NIC_IP["+j+"]");
   
   String IsMember=isMember(NIC_IP);
   
   if (IsMember.equals("true"))
   {
               String hql = "delete from MachineDetails where NIC_IP = ?";
                  Query query = Sess.createQuery(hql);
                 query.setParameter(0, NIC_IP);
                  int del = query.executeUpdate();
                  if (del == 0)
                 {
                    System.out.println("No Rows deleted");
                  }
                  else
                 {
                    System.out.println("Deleted  Row: " + del);
                  }
                 Sess.clear();
               macdel = new MachineDetails();
               macdel.setNIC_IP(NIC_IP);
               macdel.setAppId(AppId);
               macdel.setVendor(Vendor);
               macdel.setModel(Model);
               
               Sess.save(macdel);
               Sess.flush();
               
               String TempReqDataHolder="";
               if (HDRegister > 0)
               {
               hadel = new HardDiscDetails();
               for(int k=0;k<HDRegister;k++)
               {
               hadel.setHardDiscNumber("HD["+j+"]");
               TempReqDataHolder=req.getParameter("HD["+j+"]");
               hadel.setHardDiscName(TempReqDataHolder);
               TempReqDataHolder=req.getParameter("HD_Size["+j+"]");
               hadel.setHardDiscSize(TempReqDataHolder);
               
               hadel.setNIC_IP(NIC_IP);
               
               System.out.println("NICIP macdel:"+macdel.getNIC_IP());
               System.out.println("NICIP hadel:"+hadel.getNIC_IP());
               Sess.save(hadel);
               
               }
               }
               
      }
      
      }
   
   
   else
   {
      System.out.println("Has to register a new machine");
   }
}
   
}

}
catch (Exception e)
{
System.out.println(e);
}   
}
}

When i run the client i get this exception:
01:47:52,890 ERROR [BasicPropertyAccessor] IllegalArgumentException in class: MachineDetails, getter method of property: NIC_IP
01:47:52,890 INFO [STDOUT] org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of MachineDetails.NIC_IP

I checked and i am getting this error at the step where i save the HardDiscDetails object.
Code:
Sess.save(hadel);      

Above i am saving the MachineDetails object (macdel) before i save the child object for HardDiscDetails (hadel). Also as you can see i am able to print out the values of the foreign key column using both the objects. And i when i querry the machine details table on the db(MYSQL) i see the data is saved. But i dont understaqnd why i am not able to persist the child object to the database.

Any help would be greatly appriciated.[/quote]


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Mon Oct 12, 2009 5:09 pm 
Regular
Regular

Joined: Mon Jan 05, 2009 6:42 pm
Posts: 99
Location: IL
Hope you will not get any errors this time.. Try the ones below. Typically you will not do it in a Servlet instead in a DAO class. But I dont know your requirement.

your MachineDetails.hbm.xml:
needs to have this

Code:
    <set
            name="hardDiscs"
            table="HardDiscDetails"
            lazy="true"
            inverse="false"
            cascade="all"
            sort="unsorted"
        >

              <key
                  column="NIC_IP"
              >
              </key>

              <one-to-many
                  class="HardDiscDetails" table="HardDiscDetails"
              />

        </set>



Pojo for MachineDetails
Code:
private Set hardDiscs = new HashSet();
  public Set getHardDiscs()
  {
    return hardDiscs;
  }

  public void setHardDiscs(Set set)
  {
    hardDiscs = set;
  }


your HardDiscDetails pojo

Code:
public MachineDetails machineDetails = null;
public MachineDetails getMachineDetails()
  {
    return machineDetails;
  }

public void setMachineDetails(MachineDetails machineDetails){
this.machineDetails = machineDetails;
}


your Servlet replace every thing below the statement macdel = new MachineDetails(); with the code below.


Code:
macdel = new MachineDetails();
   // i dont know why you are setting NIC_IP since its a generated identifier.
               macdel.setNIC_IP(NIC_IP);
               macdel.setAppId(AppId);
               macdel.setVendor(Vendor);
               macdel.setModel(Model);
    //Sess.save(macdel);
    //           Sess.flush();
       String TempReqDataHolder="";
               if (HDRegister > 0)
               {
               hadel = new HardDiscDetails();
               for(int k=0;k<HDRegister;k++)
               {
               hadel.setHardDiscNumber("HD["+j+"]");
               TempReqDataHolder=req.getParameter("HD["+j+"]");
               hadel.setHardDiscName(TempReqDataHolder);
               TempReqDataHolder=req.getParameter("HD_Size["+j+"]");
               hadel.setHardDiscSize(TempReqDataHolder);
               
               //hadel.setNIC_IP(NIC_IP);
               
               System.out.println("NICIP macdel:"+macdel.getNIC_IP());
               System.out.println("NICIP hadel:"+hadel.getNIC_IP());
               //Sess.save(hadel);
               macdel.getHardDiscs().add(hadel);
               }
               }
               
                Sess.save(macdel);
               Sess.flush();


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Tue Oct 13, 2009 4:54 am 
Newbie

Joined: Sun Oct 11, 2009 2:32 am
Posts: 5
Hi Latha,

First and foremost a big thanks, for taking interest.

The requirement is to take some sort of a web based inventory of different machines in our network at regular intervals. The machines communicate periodically with central cosole and register their current status.

The database has one MachineDetails table(NicIp is the primary key), and a HardDisk details table (foreign key is NicIp and has its one incrementally generated primary key)

1. Instead of using one to many in the MachineDetails Class, i have used many to one in the Hard disk details class. At the risk of sounding like some one who hasnt read the manual first, do i have to make the mapping bi-directional?

2. NicIp is not generated it is assigned after it is extracted from the servlet.

3. I have not explored DAO as yet, i will.

Thanks again, will implement your suggestions and let you know the result.

Best,


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Wed Oct 14, 2009 2:45 am 
Newbie

Joined: Sun Oct 11, 2009 2:32 am
Posts: 5
Hi Latha,

This is to let you know that your suggestion worked like charm. Thanks a TON.

Best,


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Tue Oct 27, 2009 6:09 am 
Newbie

Joined: Sun Oct 11, 2009 2:32 am
Posts: 5
Hi Latha,

I did implement the changes; Every thing is working fine except when i try to delete a row.

If you are still watching this post could you kindly let me know how to delete a row, with cascading from machine details to harddiscdetails?

Thanks again.

Best,


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Tue Oct 27, 2009 11:31 am 
Regular
Regular

Joined: Mon Jan 05, 2009 6:42 pm
Posts: 99
Location: IL
How are you doing it now?
Have you tried something like below:-

Query q=Session.createQuery("from MachineDetails m where m.NIC_IP=? ")
List<MachineDetails> mdetailsList =q.setInteger().list();
//somehow get the MachineDetails object.
Set<HardDiscDetails> hardDiscs= MachineDetails.getHardDiscs();
//remove or update a harddisc entry and save MachineDetails object.

Hope this helps,
Srilatha.


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Wed Oct 28, 2009 5:30 am 
Newbie

Joined: Sun Oct 11, 2009 2:32 am
Posts: 5
Hi Srilatha,

As of now I was doing this:

Code:
hql= "delete from MachineDetails where NicIp = ?";
query = Sess.createQuery(hql);
query.setParameter(0, NicIp);
del = query.executeUpdate();


But when I do that i am getting an error from the database:
Code:
13:41:07,576 WARN  [JDBCExceptionReporter] SQL Error: 1451, SQLState: 23000
13:41:07,576 ERROR [JDBCExceptionReporter] Cannot delete or update a parent row:
a foreign key constraint fails (`appinventory`.`processdetails`, CONSTRAINT `FK
1C0FECF36FA5594A` FOREIGN KEY (`NicIp`) REFERENCES `machinedetails` (`NicIp`))
13:41:07,607 INFO  [STDOUT] org.hibernate.exception.ConstraintViolationException
: could not execute update query;


Regarding this too I wanted to clarify:

All the foreign keys that are being set from Hibernate are being set properly, this is clarified by the mysql dump, but the fact that we have used cascade = all, is not reflecting on the database end. I mean to say it does not say "on delete cascade on update cascade".
Code:
DROP TABLE IF EXISTS `harddiscdetails`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `harddiscdetails` (
  `HardDiscID` bigint(20) NOT NULL DEFAULT '0',
  `HardDiscNumber` varchar(100) DEFAULT NULL,
  `HardDiscName` varchar(100) DEFAULT NULL,
  `HardDiscSize` varchar(100) DEFAULT NULL,
  `NicIp` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`HardDiscID`),
  KEY `FK583F68E26FA5594A` (`NicIp`),
  CONSTRAINT `FK583F68E26FA5594A` FOREIGN KEY (`NicIp`) REFERENCES `machinedetails` (`NicIp`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `harddiscdetails`
--

LOCK TABLES `harddiscdetails` WRITE;
/*!40000 ALTER TABLE `harddiscdetails` DISABLE KEYS */;
INSERT INTO `harddiscdetails` VALUES (1,'HD[0]','ST340014A','37','172.16.1.186');
/*!40000 ALTER TABLE `harddiscdetails` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `machinedetails`
--

DROP TABLE IF EXISTS `machinedetails`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `machinedetails` (
  `AppId` varchar(100) DEFAULT NULL,
  `Vendor` varchar(100) DEFAULT NULL,
  `Model` varchar(100) DEFAULT NULL,
  `Version` varchar(100) DEFAULT NULL,
  `SN` varchar(100) DEFAULT NULL,
  `Domain` varchar(100) DEFAULT NULL,
  `User` varchar(100) DEFAULT NULL,
  `OS` varchar(100) DEFAULT NULL,
  `HostName` varchar(100) DEFAULT NULL,
  `OS_Date` varchar(100) DEFAULT NULL,
  `RAM` varchar(100) DEFAULT NULL,
  `VGA` varchar(100) DEFAULT NULL,
  `Monitor` varchar(100) DEFAULT NULL,
  `HDCount` varchar(100) DEFAULT NULL,
  `CDRomCount` varchar(100) DEFAULT NULL,
  `SCCount` varchar(100) DEFAULT NULL,
  `NICCount` varchar(100) DEFAULT NULL,
  `SCSICount` varchar(100) DEFAULT NULL,
  `ServicesCount` varchar(100) DEFAULT NULL,
  `ProcessCount` varchar(100) DEFAULT NULL,
  `SofwareCount` varchar(100) DEFAULT NULL,
  `PeripharalCount` varchar(100) DEFAULT NULL,
  `NicIp` varchar(100) NOT NULL,
  PRIMARY KEY (`NicIp`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `machinedetails`
--

LOCK TABLES `machinedetails` WRITE;
/*!40000 ALTER TABLE `machinedetails` DISABLE KEYS */;
INSERT INTO `machinedetails` VALUES (NULL,'Hewlett-Packard','HP dx2000 MT(PG984AV)','','INI5270CC6','applabs.net','APPLABS\\IN060053','Microsoft Windows XP Professional','DTAPP0423','20020101','512','Intel(R) 82865G Graphics Controller','hp L1530','1','0','1','1','0','105','40','35','2','172.16.1.186');
/*!40000 ALTER TABLE `machinedetails` ENABLE KEYS */;
UNLOCK TABLES;



Assuming that hibernate handles cascades on the front end, I tried doing this :

Code:
macdel = (MachineDetails) Sess.load(MachineDetails.class,NicIp);
Set hardDiscsSet= macdel.getHardDiscs();
macdel.getHardDiscs().remove(hardDiscsSet);


However when i do that i am getting the following error

Code:
14:50:24,219 ERROR [BasicPropertyAccessor] IllegalArgumentException in class: Ha
rdDiscDetails, setter method of property: NicIp
14:50:24,219 ERROR [BasicPropertyAccessor] expected type: java.lang.String, actu
al value: MachineDetails
14:50:24,219 INFO  [STDOUT] org.hibernate.PropertyAccessException: IllegalArgume
ntException occurred while calling setter of HardDiscDetails.NicIp


Please look in to it and let me know how i should approach this. Thanks again.


Top
 Profile  
 
 Post subject: Re: Unable to Save the object of a child class
PostPosted: Thu Oct 29, 2009 12:09 pm 
Regular
Regular

Joined: Mon Jan 05, 2009 6:42 pm
Posts: 99
Location: IL
Hi,
I did not read through the below approach.
Code:
hql= "delete from MachineDetails where NicIp = ?";
query = Sess.createQuery(hql);
query.setParameter(0, NicIp);
del = query.executeUpdate();


I would use Hibernate to detect the changes and issue update/delete based on the actions performed.
I would try to fix the issue of loading the machine details first and then try to modify the children entries.

Code:
macdel = (MachineDetails) Sess.load(MachineDetails.class,NicIp);
//Set hardDiscsSet= macdel.getHardDiscs();
//iterate over the hardDiscSet and remove each of the harddisc.
//macdel.getHardDiscs().remove(<<harddisc>>);

Hope this helps,
-Srilatha.


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