OneToOne | Bi directional | (Non Optional) - gauravsk89/hibernate GitHub Wiki
Scenario: OneToOne Bi-directional
In a Online auction/bidding system an item can have one shipping details.
Data Modelling Perspective: Shipping Address table can a FK to Item ID in ITEM table.
SHIPPING_DETAILS ID NUMBER PK ORDER_DATE DATE NOT NULL ITEM_ID NUMBER FK
Java Object Perspective: ShippingDetails entity has a reference to Item entity.
Since association is bi-directional, Item entity will have reference back to ShippingDetails entity.
Entities
@Entity @Table(name = "ITEMS") @Data @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode(of = {"itemId", "name"}, callSuper = false) @ToString public class Item {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ITEM_ID_SEQ")
@SequenceGenerator(name= "ITEM_ID_SEQ",
sequenceName="ITEM_ID_SEQ",
allocationSize = 1)
@Column(name = "ITEM_ID")
@JsonIgnore
private Long itemId;
@Column(name = "NAME")
private String name;
@Column(name = "INITIAL_AMOUNT")
private BigDecimal initialAmount;
// oneToOne uni-directional (non-optional)
@OneToOne
@JoinColumn(name = "SELLER_ID")
private User seller;
// oneToOne uni-directional (optional)
@OneToOne
@JoinTable(name = "ITEM_BUYER",
joinColumns = @JoinColumn(name = "ITEM_ID_PK"/*, referencedColumnName = "itemId"*/),
inverseJoinColumns = @JoinColumn(name = "BUYER_ID"/*, referencedColumnName = "id"*/))
private User buyer;
// oneToOne bi-directional (using FK)
@OneToOne(mappedBy = "item")
private ShippingDetails shippingDetails;
}
@Data @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode(of = {"id"})
@Entity @Table(name = "SHIPPING_DETAILS") public class ShippingDetails {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SHIPPING_DETAILS_ID_SEQ")
@SequenceGenerator(name = "SHIPPING_DETAILS_ID_SEQ",
sequenceName="SHIPPING_DETAILS_ID_SEQ",
allocationSize = 1)
@Column(name = "ID")
@JsonIgnore
private Long id;
@Column(name = "ORDER_DATE")
private Date orderDate;
@OneToOne
@JoinColumn(name= "ITEM_ID")
private Item item;
}
Persistence Logic
@Override @Transactional public void shipItem(ShippingDTO shippingDTO) {
Item item = itemsRepository.findOne(shippingDTO.getItemId());
ShippingDetails shippingDetails = ShippingDetails
.builder()
.item(item)
.orderDate(new Date())
.build();
shippingRepository.save(shippingDetails);
}