Question: can you explain for Composite in hibernate?
Certainly! In Hibernate, a Composite Key (also known as a composite primary key) is a key that is made up of two or more fields to uniquely identify an entity. Instead of using a single attribute as the primary key, Hibernate can use a combination of fields as the identifier for an entity.
This is useful when:
-
You don't have a single field that can serve as the unique identifier for the entity.
-
You need a combination of fields to represent the uniqueness of the entity.
Types of Composite Keys in Hibernate
There are two main approaches for using composite keys in Hibernate:
-
Using
@Embeddableand@EmbeddedIdannotations -
Using
@IdClassannotation
1. Composite Key Using @Embeddable and @EmbeddedId
Steps:
-
Create an embeddable class that represents the composite key.
-
Use the
@EmbeddedIdannotation on the entity to link the composite key.
Example:
Let's say we have an entity OrderDetail that has a composite key made up of orderId and productId.
Step 1: Create the Composite Key Class (@Embeddable)
import javax.persistence.Embeddable;
import java.io.Serializable;
@Embeddable
public class OrderDetailId implements Serializable {
private int orderId;
private int productId;
// Getters, Setters, hashCode, and equals methods
public OrderDetailId() {}
public OrderDetailId(int orderId, int productId) {
this.orderId = orderId;
this.productId = productId;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OrderDetailId that = (OrderDetailId) o;
return orderId == that.orderId && productId == that.productId;
}
@Override
public int hashCode() {
return 31 * orderId + productId;
}
}
Explanation:
-
OrderDetailIdis a class that is embeddable (@Embeddable), and it contains two fields:orderIdandproductId. It also overridesequals()andhashCode()to ensure proper comparison of composite keys. -
The
OrderDetailclass uses the@EmbeddedIdannotation to embed the composite key. TheOrderDetailIdobject will be the primary key ofOrderDetail.
Advantages:
-
Clear separation of composite key from entity.
-
Easy to manage complex composite keys.
Input: abcdefghi
OutPut : aibchdgfe
Explanation: a (first), i (last), b (second), h (second last), c (third), g (third last), .
Sure! Here's a simple Java program that:
-
Accepts a string
-
Splits it into words
-
Removes duplicate words
-
Prints only the unique words
Output:
No comments:
Post a Comment