- Given a Customer class, you need to persist customer data in the database with customer ID as primary key. Please list down the changes you need to make?
To persist customer data in the database with customer ID as the primary key using Hibernate, you need to make several changes. Below are the steps you would typically follow:
-
Define the Customer Class: Define a Java class representing the Customer entity. This class should include attributes corresponding to the columns in the database table.
-
Annotate the Class: Use Hibernate annotations to map the Customer class to the database table and specify the primary key generation strategy.
-
Configure Hibernate: Set up Hibernate configuration to connect to the database and specify additional properties such as dialect, connection pool settings, etc.
-
Write DAO (Data Access Object) Layer: Implement DAO classes to perform CRUD operations (Create, Read, Update, Delete) on the Customer entity.
-
Use Hibernate API: Utilize Hibernate's API to save, retrieve, update, and delete Customer objects.
Here's an example demonstrating the steps mentioned above:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long customerId;
private String firstName;
private String lastName;
private String email;
// Constructors, getters, and setters
// Constructor(s) could be created as per requirement
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
In this example:
- The
Customer
class represents the entity to be persisted in the database. - The
@Entity
annotation marks the class as an entity. - The
@Id
annotation specifies the primary key attribute. - The
@GeneratedValue
annotation withGenerationType.IDENTITY
strategy specifies that the primary key values are generated by the database (auto-increment).
After making these changes, you would configure Hibernate to use this entity and then use Hibernate's API to perform database operations on Customer objects.