Persisting Array

Working with Array is similar to that with List, but in List, it is not compulsory to add @IndexColumn. However, Array requires an indexed column to maintain the column order.

Getting ready

Create the required class using the following code to persist Array:

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
  @IndexColumn(name="email_index")
  @CollectionTable(name = "email")
  private 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 String[] getEmails() {
    return emails;
  }

  public void setEmails(String[] emails) {
    this.emails = emails;
  }

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

How to do it…

We will take a look at how to insert and retrieve the data from hibernate using Array.

Inserting a record

Here, we create one employee record with Array of e-mail addresses. Use the following code to do so:

Code

Employee employee = new Employee();
employee.setName("vishal");
employee.setEmails (new String []{"[email protected]", "[email protected]", "[email protected]", "[email protected]"});

session.getTransaction().begin();
session.save(employee);
session.getTransaction().commit();

Output

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

Retrieving a record

Use the following code to retrieve records for Employee#1:

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_, emails0_.email_index as email3_0_ from email emails0_ where emails0_.Employee_id=?
Employee
  Id: 1
  Name: vishal
  Emails: [[email protected], [email protected],  [email protected], [email protected]]
..................Content has been hidden....................

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