Carlos Escalera Alonso
Carlos Escalera Alonso

Reputation: 2363

Delete all previous records and insert new ones

When updating an EMPLOYEE with id = 1 for example, what is the best way to delete all previous records in the table CERTIFICATE for this employee_id and insert the new ones?. For example employee id=1 has A,B certificates, when updating employee delete all certificates for this employee and insert again even the certificate are A, B or new ones C,D.

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

create table CERTIFICATE (
   id INT NOT NULL auto_increment,
   certificate_name VARCHAR(30) default NULL,
   employee_id INT default NULL,
   PRIMARY KEY (id)
);

Hibernate mapping

<?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="Employee" table="EMPLOYEE">
      <id name="id" type="int" column="id">
        <generator class="sequence">
            <param name="sequence">employee_seq</param>
        </generator>
      </id>
      <set name="certificates" lazy="false" cascade="all">
         <key column="employee_id" not-null="true"/>
         <one-to-many class="Certificate"/>
      </set>
      <property name="firstName" column="first_name"/>
      <property name="lastName" column="last_name"/>
      <property name="salary" column="salary"/>
   </class>

   <class name="Certificate" table="CERTIFICATE">
      <id name="id" type="int" column="id">
         <param name="sequence">certificate_seq</param>
      </id>
      <property name="employee_id" column="employee_id" insert="false" update="false"/>
      <property name="name" column="certificate_name"/>
   </class>

</hibernate-mapping>

Upvotes: 0

Views: 396

Answers (1)

Xeon
Xeon

Reputation: 5989

You should use CASCADE in your mapping in order to automatically delete relevant records. This will delete all certificates that has foreign key to employee.

<class name="Certificate" table="CERTIFICATE" cascade="delete-orphan, save-update" >
  <id name="id" type="int" column="id">
     <param name="sequence">certificate_seq</param>
  </id>

  <property name="name" column="certificate_name"/>

  <key>
    <property name="employee_id" column="employee_id" insert="false" update="false" not-null="true"/>
  </key>
  <one-to-many class="com.your.package.Certificate" />

</class>

Now you can modify certificates collection in your employee class. By doing employee.saveOrUpdate your certificates will be saved/removed accordingly.

I haven't tested this. But you should get the idea. Here is an example of cascade types.

Upvotes: 1

Related Questions