java - 间接插入命名表?

标签 java database jpa

让我们考虑一下这个图表

A Genre table and Track table, where track has a FK on Genre and Genre only consists of the PK 'name'

使用 Track 类的 JPA 片段。

@Entity
@Table(name = "track")
public class Track {
    @Id
    @Type(type="pg-uuid")
    private UUID id;

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

    /* Getters, setters, etc */
}

以及数据库架构

/** Liquibase */
<changeSet id="1" author="SoulBeaver">
    <createTable tableName="genre">
        <column name="name" type="VARCHAR(1024)">
            <constraints primaryKey="true" nullable="false" />
        </column>
    </createTable>

    <createTable tableName="track">
        <column name="id" type="UUID">
            <constraints primaryKey="true" nullable="false" />
        </column>
        <column name="genre" type="VARCHAR(1024)" />
    </createTable>
    <addForeignKeyConstraint baseTableName="track" baseColumnNames="genre" constraintName="genre_fk"
                             referencedTableName="genre"
                             referencedColumnNames="name" />
</changeSet>

现在,当我尝试保留已被赋予 track.setGenre("Rock"); 的轨道时我收到一个运行时错误,指出该 key 在流派中不存在。

有什么方法可以避免创建 Genre 类,首先保留 Genre,最后保留 Track?

最佳答案

基本上,FKey 约束的工作方式是,如果您尝试在父表中不存在 FKey 值的子表中插入值,则会失败。这不是 JPA 特有的。这就是关系型数据库的设计方式。

关于java - 间接插入命名表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19789141/

相关文章:

java - struts 1.0逻辑标签选择——if/else逻辑

Java正则表达式从一个句子中删除多次出现的模式

java - 使用 Ant 构建 jar 文件(htsjdk jar)

mysql - MYSQL中自动递增的列

java - Spring Boot + Oauth2 客户端凭据

javascript - 如何从多个 Baqend 表中删除所有数据?

php - foreach 在带有数据库表数据的表单中循环,更改数据并在 WordPress 插件中更新数据库

java - JMS 和 JPA 的同步问题

java - 限制映射以获得基于 JPA 的排序的特定一对一关系

java - 使用@Inheritance JPA属性时插入顺序无效