0

Here's the code and what I'm trying to achieve is to remove a registration object from the registration table on delete. When I delete I want to remove it's corresponding certificate values in certificatesChosen table(which has primary keys id(from registration) and cid(from certificates)and the address objects.

Registration.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.global.manager.Registration" table="registrations">
        <meta attribute="class-description">
            This class contains the employee detail.
        </meta>
        <id name="id" type="int" column="id">
            <generator class="native" />
        </id>
        <property name="username" column="username" type="string" />
        <property name="password" column="password" type="string" />
        <property name="dob" column="dob" type="string" />
        <property name="email" column="email" type="string" />
        <property name="phone" column="phone" type="string" />
        <property name="registered" column="registered" type="string" />
        <set name="certifications" table="certificatesChosen" cascade="all">
            <key column="id" not-null="true" />
            <many-to-many column="certificationId" class="com.global.manager.Certifications"
                unique="true" />
        </set>
        <set name="address" table="address" cascade="all">
            <key column="id" not-null="true" />
            <one-to-many class="com.global.manager.Address" />
        </set>
    </class>
</hibernate-mapping>

Address.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.global.manager.Address" table="address">
        <meta attribute="class-description">
            This class contains the courses opted by student
        </meta>
        <id name="aid" type="int" column="aid">
            <generator class="native" />
        </id>
        <property name="type" column="type" type="string" />
        <property name="street" column="street" type="string" />
        <property name="city" column="city" type="string" />
        <property name="state" column="state" type="string" />
        <property name="country" column="country" type="string" />
        <property name="pin" column="pin" type="int" />

        <many-to-one name="registration" class="com.global.manager.Registration"
            fetch="select" insert="false" update="false">
            <column name="id" not-null="true" />
        </many-to-one>
        <!-- <many-to-one name="student" class="com.global.hibernate.Student" column="regnId" 
            not-null="true" /> -->

    </class>
</hibernate-mapping>

Certifications.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.global.manager.Certifications" table="certifications">
        <meta attribute="class-description">
            This class contains the courses opted by student
        </meta>
        <id name="cid" type="int" column="certificationId">
        </id>
        <property name="name" column="certificationName" type="string" />
        <join table="certificatesChosen" inverse="true">
            <key column="certificationId" />
            <many-to-one name="registrations" column="id" not-null="true" />
        </join>
    </class>
</hibernate-mapping>

deleteUser.java(where I actually delete a registration object)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username =request.getParameter("username");
        DBHelper.deleteStudent(username);

    }

DBHelper.java

public class DBHelper
{
    public static void deleteStudent(String username) {
    System.out.println("inside dbhelper");
        try {

            Configuration cfg = new Configuration().configure();
            SessionFactory sf = cfg.buildSessionFactory();

            Session session = sf.openSession();
            Transaction tx = session.beginTransaction();
            Criteria criteria = session.createCriteria(Registration.class).add(Restrictions.eq("username", new String(username)));
            List <Registration> details = criteria.list();
            session.delete(details.get(0));
            tx.commit();
            session.close();
        }catch(HibernateException e) {
            e.printStackTrace();
        }
    }
}

I'm sending the username from a jsp page and on execution this is the error log:

2017-12-15T18:46:01.902+0530|Severe: [http-thread-pool(5)] ERROR org.hibernate.util.JDBCExceptionReporter - Cannot delete or update a parent row: a foreign key constraint fails (`Jpa`.`certificatesChosen`, CONSTRAINT `certificatesChosen_ibfk_2` FOREIGN KEY (`certificationId`) REFERENCES `certifications` (`certificationId`))
2017-12-15T18:46:01.903+0530|Severe: [http-thread-pool(5)] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
2017-12-15T18:46:01.905+0530|Severe: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:114)
    at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:109)
    at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:244)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2650)
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2895)
    at org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at com.global.manager.DBHelper.deleteStudent(DBHelper.java:90)
    at com.global.manager.deleteUser.doGet(deleteUser.java:36)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1693)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:526)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)

Please let me know if the mappings are right and if it's a rigth way to delete in a DBHelper. Would greatly appreciate your help. Thanks!

  • `DBHelper.deleteStudent(username)` - static methods like this are the root of all evil. It makes your code difficult, if not impossible, to unit test. Ever heard of dependency injection and/or Inversion of Control (IOC)? – lance-java Dec 15 '17 at 13:56
  • I understand I was introduced to hibernate day before yesterday, but thank you, will consider your suggestion and will sure go through it. –  Dec 15 '17 at 14:04
  • this has absolutely nothing to do with hibernate and everything to do with coding style – lance-java Dec 15 '17 at 14:07
  • Alright, i didn't pay attention to your comment at first, but with the time left, I'm only concerned with the output, let me know if you can figure. Thanks for your input, will modify it soon. –  Dec 15 '17 at 14:12
  • You'll either need to manually delete the associated objects first, or delare `cascade="delete|all"` on all the associations you want to be cascaded in the delete – lance-java Dec 15 '17 at 14:34

0 Answers0