@ManyToOne是最常见的关联,在关系数据库中具有外键关系,因此建立了子实体和父实体之间关系。

@ManyToOne

@Entity
@Table
public class Unit extends AbstractEntity implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Column
	private String name;
	
    @CreationTimestamp
	@Column
	@Temporal(TemporalType.TIMESTAMP)
	private Date createDatetime;

	@OneToMany(mappedBy = "unit", cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = User.class)
	private List<User> users = new ArrayList<>();

	//Getters and setters are omitted for brevity
}
@Entity
@Table
public class User extends AbstractEntity implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Column(name = "name")
	private String name;

	@Column(name = "email", nullable = false, length = 250)
	private String email;
	
	@NotNull
	@Range(max = 150, min = 1)
	@Column
	private Integer age;
	
	@CreationTimestamp
	@Column
	@Temporal(TemporalType.TIMESTAMP)
	private Date createDatetime;
	
	@ManyToOne(fetch = FetchType.LAZY)
	private Unit unit;

	//Getters and setters are omitted for brevity
}
Unit unit = new Unit("unit1", new Date());
		
entityManager.persist(unit);

User user = new User("user1", "user1@gmail.com", 20, unit);

entityManager.persist(user);
System.out.println(user.getCreateDatetime());

user.setUnit(null);

entityManager.flush();

Hibernate将执行以下SQL语句:

insert into unit (id, create_datetime, name) values (null, ?, ?)
insert into user (id, age, create_datetime, email, name, unit_id) values (null, ?, ?, ?, ?, ?)
update user set age=?, create_datetime=?, email=?, name=?, unit_id=? where id=?

数据库表关系:

image-20200412170139549

GitHub