@Entity
data class Election(
@Id @UuidGenerator val electionId: String = "",
var name: String = "",
var description: String = "",
var startDate: LocalDateTime? = null,
var endDate: LocalDateTime? = null,
var electionCode: String = "", // auto generated to be unique
@ManyToOne(cascade = [CascadeType.ALL]) @Column(nullable = false) var electoralCommission: ElectoralCommission = ElectoralCommission(),
@OneToMany(mappedBy = "elections") var candidates: MutableList<Candidate> = mutableListOf(),
@OneToMany var eligibleVoters: MutableList<Voter> = mutableListOf(),
@Enumerated(EnumType.STRING) var electionStatus: ElectionStatus = ElectionStatus.UPCOMING
)
@Entity
data class Voter(
@Id
@UuidGenerator
@Column(name = "voter_id")
private val _voterId: String = "",
val name: String = "",
val email: String = "",
val phoneNumber: String = "",
val dateOfBirth: LocalDateTime = LocalDateTime.now(),
@Column(name = "voter_code", unique = true, length = 8, updatable = false) var voterCode: String = "",
@Enumerated(EnumType.STRING) val voterStatus: VoterStatus = VoterStatus.REGISTERED,
@ManyToOne
@JoinColumn(name = "electoral_commission_id") val electoralCommission: ElectoralCommission? = null
) {
fun toCandidate(election: Election): Candidate {
return Candidate(
name = name,
email = email,
phoneNumber = phoneNumber,
voterCode = voterCode,
candidateStatus = CandidateStatus.REGISTERED,
election = election
)
}
}
选举实体有一个选民名单(多对一,单向)。当有人投票时,该选民与选举的关系将结束。我无法弄清楚如何使用 jpa 实现这一点。我尝试使用election_voter表进行查询,但 jpa 给出无法解析查询的错误。查询是
从election_voter e中删除,其中e.voter_voter_code = :voterCode
您在问题中提到:
所以让我们从选民的表定义开始。
这应该允许选民在没有选举的情况下存在。
当仅使用此代码运行代码时,Hibernate将尝试将记录插入中间表,因此我们需要对 Election 类进行修改。
为了使用上述方法将选民从选举中分离出来,我们需要一个本机查询:
这是不可取的,所以让我们尝试使用这样的查询:
查询表明我们需要添加
electionId
到选民:并再次更改选举