I have 2 models: Order and User. There are id, orderDate, totalPrice, totalDiscount, price and userId in Order model. I want to reference id from User to userId to Order. How can I do this with using Spring Boot, Spring Data Jpa and Hibernate? Then I use MySQL workbench.
Technologies which I used: Spring Boot, Spring Data Jpa, Hibernate, MySQL, Liquebase, Lombok, ModelMapper and Spring Boot Validation.
Order.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", shape = JsonFormat.Shape.STRING)
@ApiModelProperty(required = true, example = "2021-08-20T00:00:00")
@NotNull(message = "Created date cannot be null")
private LocalDateTime orderDate;
@NotNull(message = "Total price cannot be null")
private BigDecimal totalPrice;
@NotNull(message = "Total discount cannot be null")
private BigDecimal totalDiscount;
@NotNull(message = "Price cannot be null")
private BigDecimal price;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="id", referencedColumnName = "id", insertable = false, updatable = false)
// @NotNull(message = "User ID cannot be null")
private User user;
@OneToMany
@JoinColumn(name="order_id")
private List<OrderProduct> orderProducts;
}
User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Name cannot be blank")
private String name;
@NotBlank(message = "Email cannot be blank")
@Email(message = "Email should be valid")
private String email;
@NotNull(message = "Password cannot be null")
@Size(min = 8, message = "Password should have at least 8 characters")
private String password;
@NotNull(message = "Password cannot be null")
@Size(min = 8, message = "Password should have at least 8 characters")
private String confirmPassword;
@OneToMany(mappedBy = "id") // mappedBy added: 04.01.2022
@JoinColumn(name="order_id", nullable = false)
private List<Order> orders;
}