Nov 29, 2011

The Java Persistence for SINGLE_TABLE inheritance type strategy




Suppose we have  an application where we need to create a User Entity for User credentials. But as per each department concerned we need to have different types of Entities. Like we have ADMIN_USER, CUSTOMER, HRM, ACCOUNTANT, LOGISTICS and so on. So, instead of just adding an attribute manually is not the case when you use inheritance. In that case you just need to create a Parent Class and the types of users' entities.

Here are the example below how you need to do this:


@Entity

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)

@Table(name = "user")

public class User implements UserDetails {

         @Id

         @GeneratedValue(generator = "userseq")

         @SequenceGenerator(name = "userseq", sequenceName = "userid_seq", allocationSize = 1)

          private int id;



          private String username;

          private String password;

         

          //Getters and Setters method

}






Now, say we need to create a new user type named "customer". So, we need to create an Entity like this:


@Entity

@DiscriminatorValue("customer")

public class Customer extends User {

}






@Entity

@DiscriminatorValue("admin")

public class Admin extends User {

}





So, automatically in the database one table will be created and along with the id, username and password one additional column will be created named "type" because we defined DiscriminatorColumn and whose name is "type". So, whenever we need to create a "customer" type user just instantiate an object like this way:


User customer = new Customer();

customer.setUsername("");

customer.setPassword("");

customerService.save(customer);


That will directly create a "customer" typed user in the Object as well as "user" table.

----- Hossain Doula

1 comment: