如何使用hibernate为实体类字段设置动态默认值?

问题描述 投票:0回答:1

我需要在创建实体时,通过从相关表中获取值来动态分配值。考虑以下场景,我有两个类--Student & Batch。

当在Student表中插入一条新记录时,我需要在Student表中通过从Batch中获取'Active'字段来设置' allocatedBatch'字段。真正 (考虑到在给定时间内只能有一个批次活动)

而这必须要动态地完成。请给我一些hibernate的最佳用法来处理这个问题。

注意--因为这必须在不使用各自的服务和仓库类的情况下完成,所以要寻找hibernate的用法。

学生.java

public class Student {

@Id
@GeneratedValue(Strategy = GeneratedType.Identity)
private Integer id;

private String name;

private Date DOB;

@ManyToOne
@JoinColumn(name = "Student_Batch", nullable=false)
private Batch allocatedBatch;

.....Getter and setter methods....
}

Batch.java

public class Batch {

@Id
@GeneratedValue(Strategy = GeneratedType.Identity)
private Integer id;

private String name;

private Date startDate;

 @ColumnDefault("false")
private boolean Active;

@OneToMany(mappedBy = "allocatedBatch", cascade = {CascadeType.PERSIST, CascadeType.REMOVE)
private Set<Student> students;

.....Getter and setter methods....
}
hibernate jpa hibernate-mapping hibernate-criteria dynamic-mapping
1个回答
0
投票

我不知道你的情况,但这听起来像你可能需要重新思考你的设计。然而,我认为使用事件监听器或拦截器可能会起到作用。(如果我理解正确的话)

查看 @PrePersist 注释。JPA回调

© www.soinside.com 2019 - 2024. All rights reserved.