@One-To-Many annotation

@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface OneToMany {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default LAZY;
String mappedBy() default ”;
}

@Many-To-One annotation

@Target({METHOD, FIELD}) @Retention(RUNTIME)
public @interface ManyToOne {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default EAGER;
boolean optional() default true;
}

1. Bidirectional One-To-Many relationship

@Entity

@Table(name=”ITEMS”)

public class Item {

@Id

protected Long itemId;

protected String title;

protected String description;

protected Date postdate;

@OneToMany(mappedBy=”item”)

protected Set<Bid> bids;

//if not generic type of Set

//@OneToMany(targetEntity=Bid.class,mappedBy=”item”)

//protected Set bids;

}

@Entity

@Table(name=”BIDS”)

public class Bid {

@Id

protected Long bidId;

protected Double amount;

protected Date timestamp;

@ManyToOne

@JoinColumn(name=”BID_ITEM_ID”,

referencedColumnName=”ITEM_ID”)

protected Item item;

}

targetEntity:

If we did not use generics on the Set.

No “mappedBy” at @Many-To-One: Many-to-one is always as owning-side of relationship.

2. Many-To-One self referencing relationship

@Entity

@Table(name=”CATEGORIES”)

public class Category implements Serializable {

@Id

@Column(name=”CATEGORY_ID”)

protected Long categoryId;

@ManyToOne

@JoinColumn(name=”PARENT_ID”,

referencedColumnName=”CATEGORY_ID”)

Category parentCategory;

}

Advertisements