One of the key features of relational database is referential integrity which s maintained by the system, by taking certain actions when referential constraints are violated. So for example what happens when:

1) A row with a referenced primary key is deleted from the referenced table
2) A referenced primary key is updated in the referenced table

In order to mantain referential integrity you can specify to use cascade deletes or cascade updates in any of the two options. The cascade is supported in both XML mapping file and annotation.

Hibernate supports several different types of cascades that can be applied to many-to-one associations as well as collections. The default cascade is none. Each cascade strategy specifies the operation or operations that should be propagated to child entities. The cascade types that you are most likely to use are the following:

all: All operations are passed to child entities: save , update , and delete.
save-update : Save and update ( and UPDATE , respectively) are passed to child entities.
delete: Deletion operations are passed to child entities.
delete-orphan: All operations are passed to child entities, and objects no longer associated with the parent object are deleted.

The cascade element is added to the desired many-to-one or collection element. For example, the following configuration instructs Hibernate to delete the child Singer elements when the parent Event is deleted:

<set name="singers" cascade="delete">
      <key column="event_id"/>
      <one-to-many class="Singer"/>
</set>

Enable Cascades using Annotations

In annotation, declared the CascadeType.SAVE_UPDATE (save, update) and CascadeType.REMOVE (delete) in @Cascade annotation.

@Entity 
public class Employee { 
// ... 
@OneToOne(cascade={CascadeType.PERSIST, CascadeType.REMOVE}) 
Address address; 
@OneToMany(mappedBy="employee", 
cascade={CascadeType.PERSIST, CascadeType.REMOVE}) 
Collection<Task> tasks; 
// ... 
}  

This will cascade delete:

Query q = session.createQuery("from Employee where surname = :surname ");
q.setParameter("surname", "Smith");
Employee e= (Employee)q.list().get(0);
session.delete(e);

 

 

0
0
0
s2smodern

In this tutorial you will show how to map composite components using Hibernate/JPA Annotations.  Consider the following relationship between Worker and WorkerInfo Entity.

embeddable hibernate jpa embed

According to the relationship each Worker should have a unique WorkerInfo.

So, since the two Entities are strongly related (composition relation), it is better to store them in a single table (named Worker) but you can keep them logically separated in two Entities. Here's the Worker Entity:


package com.sample;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Worker {

    private long workerId;
    private String name;
    private WorkerInfo info;

    public Worker() {
    }

    public Worker(String name, WorkerInfo info) {
        this.name = name;
        this.info = info;
    }

    @Id
    @GeneratedValue
    @Column(name = "WORKER_ID")
    public long getStudentId() {
        return this.workerId;
    }

    public void setWorkerId(long workerId) {
        this.workerId = workerId;
    }

    @Column(name = "WORKER_NAME", nullable = false, length = 100)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Embedded
    public WorkerInfo getWorkerInfo() {
        return this.info;
    }

    public void setStudentAddress(WorkerInfo info) {
        this.info = info;
    }

}

The @Embedded annotation is used to specify the WorkerInfo entity should be stored in the WORKER table as a component.

@Embeddable annotation is used to specify the WorkerInfo class will be used as a component. The WorkerInfo class cannot have a primary key of its own, it uses the enclosing class primary key.

package com.sample;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class WorkerInfo {

    private String address;
    private String city;
    private String country;


    public WorkerInfo() {
    }

    public WorkerInfo(String street, String city, String state ) {
        this.address = street;
        this.city = city;
        this.country = state;

    }
    @Column(name = "INFO_STREET", nullable = false, length=250)
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    @Column(name = "INFO_CITY", nullable = false, length=50)
    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
    @Column(name = "INFO_COUNTRY", nullable = false, length=50)
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }


}

0
0
0
s2smodern

Supposing that you have created an Oracle sequence using:

SQL> create sequence AGENDA_SEQ

Now, in your Entity define  SequenceGenerator which points to the sequence via the sequenceName attribute:

@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="my_entity_seq_gen")
@SequenceGenerator(name="my_entity_seq_gen", sequenceName="AGENDA_SEQ", allocationSize = 1)
private Long id;

Note that you can achieve the same result in Hibernate by mapping the Sequence in the XML configuration file:

<id name="id" type="java.lang.Integer">   

<column name="ID" />   

  <generator class="sequence-identity" >       

   <param name="sequence">AGENDA_SEQ</param>   

  </generator>

</id>
0
0
0
s2smodern

Hibernate dynamic-insert and dynamic-update

When the dynamic-insert  property is set to  true , Hibernate does  not include null values for properties (for properties that aren’t set by the application) during an  INSERT operation. With the  dynamic-update property set to true, Hibernate does not include unmodified  properties in the  UPDATE operation.
This can be specified either via XML:

<class name="MyCar" table="CAR" dynamic-insert="true" dynamic-update="true">


or using annotations:

@Entity 
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true) 
@Table (name="CAR")

0
0
0
s2smodern

You can use @javax.persistence.Lob annotation to fetch Clob and Blob elements from the Database. Example:  

@Entity
public class SampleEntity implements Serializable
{
   private Long id;
   private Blob blob;
   private Clob clob;

   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
   public Long getId()
   {
      return id;
   }

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

   @Lob @Basic(fetch = FetchType.EAGER)
   public Blob getBlob()
   {
      return blob;
   }

   public void setBlob(Blob blob)
   {
      this.blob = blob;
   }

   @Lob @Basic(fetch = FetchType.EAGER)
   public Clob getClob()
   {
      return clob;
   }

   public void setClob(Clob clob)
   {
      this.clob = clob;
   }


}

If you need to insert data in your Clob/Blob you can use Hibernate helper classes:

Blob:

org.hibernate.Hibernate.createBlob(byte[] bytes)
org.hibernate.Hibernate.createBlob(InputStream stream, int length)
org.hibernate.Hibernate.createBlob(InputStream stream)

Clob:

org.hibernate.Hibernate.createClob(String string)
org.hibernate.Hibernate.createClob(Reader reader, int length)

0
0
0
s2smodern