Tuesday, 9 December 2014

Composite Primary Key using JPA and Hibernate

File: Customer.java


import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
public class Customer implements Serializable{
      
       @EmbeddedId
       @NotEmpty
       private CustomerId id;
       //Getter Setter for CustomerId
       public CustomerId getId() {
              return id;
       }
       public void setId(CustomerId id) {
              this.id = id;
       }
      
       private String customerBookItem;
       private String customerBookTime;
       //Getter Setter
       public String getCustomerBookItem() {
              return customerBookItem;
       }
       public void setCustomerBookItem(String customerBookItem) {
              this.customerBookItem = customerBookItem;
       }
       public String getCustomerBookTime() {
              return customerBookTime;
       }
       public void setCustomerBookTime(String customerBookTime) {
              this.customerBookTime = customerBookTime;
       }
      
      

}



File: CustomerId.java



import javax.persistence.Embeddable;
import java.io.Serializable;

@Embeddable
public class CustomerId implements Serializable{
      
       @NotEmpty
       private String customerBirthday;
       @NotEmpty
       private String customerName;
      
       //Constructor is necessary
       //default constructor
       public CustomerId() {
              super();
              // TODO Auto-generated constructor stub
       }
      
       //Constructor with attributes
       public CustomerId(String customerBirthday, String customerName) {
              super();
              this.customerBirthday = customerBirthday;
              this.customerName = customerName;
       }
      
       public String getCustomerBirthday() {
              return customerBirthday;
       }
       public void setCustomerBirthday(String customerBirthday) {
              this.customerBirthday = customerBirthday;
       }
       public String getCustomerName() {
              return customerName;
       }
       public void setCustomerName(String customerName) {
              this.customerName = customerName;
       }
      
}

No comments:

Post a Comment