I want do a one-to-many relationship between two tables using a join table.
This is why I want to use a join table:
Finally, I want to use Hibernate annotations to perform this.
I found some examples to do this using xml mapping but nothing with annotations.
I believe this would be how the tables need to be created
CREATE TABLE `PRODUCT` (
`PRODUCT_ID` BIGINT PRIMARY KEY AUTO_INCREMENT
);
CREATE TABLE `PARTS` (
`PART_ID` BIGINT PRIMARY KEY AUTO_INCREMENT
);
-- USER_IMAGE_ID must be unique if we want a one-to-many relationship between PRODUCTS & PARTS tables
CREATE TABLE `USER_DETAILS_IMAGE` (
`PRODUCT_ID` BIGINT,
`PART_ID` BIGINT UNIQUE,
CONSTRAINT `FK_PRODUCT_ID` FOREIGN KEY (`PRODUCT_ID`) REFERENCES `PRODUCT`(`PRODUCT_ID`),
CONSTRAINT `FK_PART_ID` FOREIGN KEY (`PART_ID`) REFERENCES `PARTS`(`PART_ID`)
);
Most important point in above class is the ManyToOne annotation on Cart1 class variable and JoinColumn annotation to provide the column name for mapping. That's it for one to many mapping in hibernate using annotation in model classes.
In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations. Let's have a closer look at them. The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.
Don't look for examples. Read the official documentation:
@Entity
public class Product {
private String serialNumber;
private Set<Part> parts = new HashSet<Part>();
@Id
public String getSerialNumber() { return serialNumber; }
void setSerialNumber(String sn) { serialNumber = sn; }
@OneToMany
@JoinTable(
name="PRODUCT_PARTS",
joinColumns = @JoinColumn( name="PRODUCT_ID"),
inverseJoinColumns = @JoinColumn( name="PART_ID")
)
public Set<Part> getParts() { return parts; }
void setParts(Set parts) { this.parts = parts; }
}
@Entity
public class Part {
...
}
Also, note that this is the default for unidirectional one-to-many associations. So you don't even have to provide the @JoinTable
annotation if the default table and column names suit you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With