Persisting Set

Set provides an unordered data structure, and duplicate elements are not allowed. Some classes implemented by the Set interface are java.util.HashSet, java.util.LinkedHashSet, and so on. For this recipe, we will use the java.util.HashSet class, which implements the java.util.Set interface. The only difference between List and Set is that Set doesn't allow duplicate values. For example, in our previous example, we added the e-mail address with [email protected] twice, and hibernate will allow us to do this. But in case of Set, you cannot add a duplicate value. Let's take a look at how to achieve this.

Getting ready

Now, we need the class to persist Set in hibernate. Use the next code snippet to create the Employee class.

Creating a class

Use the following code to create the classes:

Source file: Employee.java

@Entity
@Table(name = "employee")
public class Employee {

  @Id
  @GeneratedValue
  @Column(name = "id")
  private long id;

  @Column(name = "name")
  private String name;

  @ElementCollection
  @CollectionTable(name = "email")
  private Set<String> emails;

  public long getId() {
    return id;
  }

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

  public String getName() {
    return name;
  }

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

  public Set<String> getEmails() {
    return emails;
  }

  public void setEmails(Set<String> emails) {
    this.emails = emails;
  }

  @Override
  public String toString() {
    return "Employee"
        + "
	Id: " + this.id
        + "
	Name: " + this.name
        + "
	Emails: " + this.emails;
  }

}

How to do it…

Here, we will discuss how to persist Set and also the manipulation operations with Set, such as inserting, retrieving, deleting, and updating.

Inserting a record

Here, we create the employee record with some e-mail addresses of the employee.

From the code's point of view, there are fewer changes as compared to List. This is because this relationship is not directly known to the database but virtually created by hibernate. Use the following code to do so:

Code

  SessionFactory sessionFactory =   HibernateUtil.getSessionFactory();
  Session session = sessionFactory.openSession();

  Employee employee = new Employee();
  employee.setName("yogesh");
    
  Set<String> emails = new HashSet<String>();
  emails.add("[email protected]");
  emails.add("[email protected]");
  emails.add("[email protected]");
  employee.setEmails(emails);
    
  session.getTransaction().begin();
  session.save(employee);
  session.getTransaction().commit();

Output

Hibernate: insert into employee (name) values (?)
Hibernate: insert into email (Employee_id, emails) values (?, ?)
Hibernate: insert into email (Employee_id, emails) values (?, ?)
Hibernate: insert into email (Employee_id, emails) values (?, ?)

When the code is executed, it inserts one record into the employee table and three records into the email table, and it also sets a primary key value for the employee record in each record of the email table as a reference.

Retrieving a record

Here, we know that our record is inserted with id 1. So, we will try to get only this record and understand how Set works in our case:

Code

  Employee employee = (Employee) session.get(Employee.class, 1l);
  System.out.println(employee.toString());

Output

Hibernate: select employee0_.id as id0_0_, employee0_.name as name0_0_ from employee employee0_ where employee0_.id=?
Hibernate: select emails0_.Employee_id as Employee1_0_0_, emails0_.emails as emails0_ from email emails0_ where emails0_.Employee_id=?
Employee
  Id: 1
  Name: yogesh
  Emails: [[email protected], [email protected],   [email protected]]

Updating a record

Here, we will try to add one more e-mail address to Employee#1:

Code

  Employee employee = (Employee) session.get(Employee.class, 1l);
  Set<String> emails = employee.getEmails();
  emails.add("[email protected]");
  session.getTransaction().begin();
  session.saveOrUpdate(employee);
  session.getTransaction().commit();
  System.out.println(employee.toString());

Output

Hibernate: select employee0_.id as id0_0_, employee0_.name as name0_0_ from employee employee0_ where employee0_.id=?
Hibernate: select emails0_.Employee_id as Employee1_0_0_, emails0_.emails as emails0_ from email emails0_ where emails0_.Employee_id=?
Employee
  Id: 1
  Name: yogesh
  Emails: [[email protected], [email protected]  [email protected]]

Here, we can see that we tried to add the e-mail address, [email protected], which is already in List; therefore, hibernate doesn't execute an update query to the database. This is because Set doesn't allow duplicate values.

Deleting a record

Here again, we will try to delete the Employee#1 object. Use the following code to do so:

Code

  Employee employee = new Employee();
  employee.setId(1);
  session.getTransaction().begin();
  session.delete(employee);
  session.getTransaction().commit();

Output

Hibernate: delete from email where Employee_id=?
Hibernate: delete from employee where id=?

While deleting the object, hibernate will delete the child records (here, e-mail addresses) as well. This works in the same way as List.

How it works…

The implementation of Set is the same as that of List, because this relationship is handled by hibernate only and is not directly known by the database. Also, hibernate creates the same table structure as List, as shown in table below:

How it works…
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.237.164