Powered by Blogger.

Wednesday, 9 July 2014

one-to-one mapping using annotations

By Shambhu Kumar  |  02:41 No comments


one-to-one mapping using annotations

1)   Using foreign key association

In this association, a foreign key column is created in owner entity. For example, if we make EmployeeEntity owner, then a extra column “ACCOUNT_ID” will be created in Employee table. This column will store the foreign key for Account table.
The join column is declared with the @JoinColumn annotation which looks like the @Column annotation. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
If no @JoinColumn is declared on the owner side, the defaults apply. A join column(s) will be created in the owner table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side.
In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side.

@Entity
@Table(name = "ACCOUNT")
public class AccountEntity implements Serializable
{

       private static final long serialVersionUID = -6790693372846798580L;

       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       @Column(name = "ID", unique = true, nullable = false)
       private Integer accountId;

       @OneToOne(mappedBy="account")
       private EmployeeEntity employee;

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

       //Setter & Getter
}

@Entity
@Table(name = "Employee_1")
public class EmployeeEntity implements Serializable {
      
       private static final long serialVersionUID = -1798070786993154676L;
      
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       @Column(name = "ID", unique = true, nullable = false)
       private Integer employeeId;
      
       @Column(name = "EMAIL")
       private String email;
      
       @OneToOne
       @JoinColumn(name="ACCOUNT_ID")
       private AccountEntity account;

//Setter & Getter
}

public class TestForeignKeyAssociation {
       public static void main(String[] args) {
        Session session = HibernateUtils.getSessionFactory().openSession();
        session.beginTransaction();

        AccountEntity account = new AccountEntity();
        account.setAccountNumber("123-345-68454");

        // Add new Employee object
        EmployeeEntity emp = new EmployeeEntity();
        emp.setEmail("demo-user@mail.com");
      
    
        session.saveOrUpdate(account);
        // Save Employee
        emp.setAccount(account);
        session.saveOrUpdate(emp);

        session.getTransaction().commit();
        HibernateUtils.shutdown();
    }
}

Running above code creates desired schema in database and run these SQL queries.
Hibernate: insert into ACCOUNT (ACC_NUMBER) values (?)
Hibernate: insert into Employee (ACCOUNT_ID, EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?, ?)

2)  Using a common join table

In this technique, main annotation to be used is @JoinTable. This annotation is used to define the new table name (mandatory) and foreign keys from both of the tables.
@JoinTable annotation is used in EmployeeEntity class. It declares that a new table EMPLOYEE_ACCOUNT will be created with two columns EMPLOYEE_ID (primary key of EMPLOYEE table) and ACCOUNT_ID (primary key of ACCOUNT table).
@OneToOne(cascade = CascadeType.ALL) @JoinTable(name="EMPLOYEE_ACCCOUNT",
joinColumns = @JoinColumn(name="EMPLOYEE_ID"), inverseJoinColumns = @JoinColumn(name="ACCOUNT_ID"))
private AccountEntity account;

public class TestJoinTable
{
      
       public static void main(String[] args)
       {
              Session session = HibernateUtils.getSessionFactory().openSession();
              session.beginTransaction();
      
              AccountEntity account = new AccountEntity();
              account.setAccountNumber("123-345-65454");
             
              //Add new Employee object
              EmployeeEntity emp = new EmployeeEntity();
              emp.setEmail("demo-user@mail.com");
              emp.setFirstName("demo");
              emp.setLastName("user");
             
              emp.setAccount(account);
              //Save Employee
              session.save(emp);
             
              session.getTransaction().commit();
              HibernateUtils.shutdown();
       }

}
O/P
Hibernate: insert into ACCOUNT_1 (ACC_NUMBER) values (?)
Hibernate: insert into Employee_1 (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into EMPLOYEE_ACCCOUNT (ACCOUNT_ID, EMPLOYEE_ID) values (?, ?)

3)   Using shared primary key

In this technique, hibernate will ensure that it will use a common primary key value in both the tables. This way primary key of EmployeeEntity can safely be assumed the primary key of AccountEntity also.
@Entity
@Table(name = "Employee")
public class EmployeeEntity implements Serializable {

       private static final long serialVersionUID = -1798070786993154676L;

       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       @Column(name = "ID", unique = true, nullable = false)
       private Integer employeeId;

       @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
       private String email;

       @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
       private String firstName;

       @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
       private String lastName;

       @OneToOne(cascade = CascadeType.ALL)
       @PrimaryKeyJoinColumn
       private AccountEntity account;

      
}

@Entity
@Table(name = "ACCOUNT")
public class AccountEntity implements Serializable
{

       private static final long serialVersionUID = -6790693372846798580L;

       @Id
       @Column(name = "ID", unique = true, nullable = false)
       @GeneratedValue(generator="gen")
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="employee"))
       private Integer accountId;

       @Column(name = "ACC_NUMBER", unique = true, nullable = false, length = 100)
       private String accountNumber;
      
       @OneToOne(mappedBy="account", cascade=CascadeType.ALL)
       private EmployeeEntity employee;

}

public class TestSharedPrimaryKey
{
      
       public static void main(String[] args)
       {
              Session session = HibernateUtils.getSessionFactory().openSession();
              session.beginTransaction();
      
              AccountEntity account = new AccountEntity();
              account.setAccountNumber("123-345-65754");
             
              //Add new Employee object
              EmployeeEntity emp = new EmployeeEntity();
              emp.setEmail("demo-user@mail.com1");
              emp.setFirstName("demo");
              emp.setLastName("user");
             
              emp.setAccount(account);
              account.setEmployee(emp);
              //Save Employee
              session.save(emp);
             
             
              session.getTransaction().commit();
              HibernateUtils.shutdown();
       }

}






Author: Shambhu Kumar

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP