用于删除关系的 JPA 查询

问题描述 投票:0回答:1
@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

sql spring postgresql spring-boot spring-data-jpa
1个回答
0
投票

您在问题中提到:

我尝试使用election_voter表进行查询...

所以让我们从选民的表定义开始。

CREATE TABLE voter
(
    voter_id    UUID PRIMARY KEY,
    election_id UUID NULL,
    FOREIGN KEY (election_id) REFERENCES election (election_id)
);

这应该允许选民在没有选举的情况下存在。

当仅使用此代码运行代码时,Hibernate 会尝试将记录插入到中间表中,因此我们需要修改 Election 类。

@OneToMany 
@JoinColumn(name="election_id") // let Hibernate know about the FK
var eligibleVoters: MutableList<Voter> = mutableListOf()
© www.soinside.com 2019 - 2024. All rights reserved.