postgresql Micronaut JDBC多对多关系

6qfn3psc  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(122)

我试图在Micronaut中创建多对多关系,但似乎不起作用。使用PostgreSQL和micronaut-data-jdbc 3.9.3
SQL:

CREATE TABLE project
(
    id          SERIAL PRIMARY KEY,
    ...
);

CREATE TABLE user
(
    id    SERIAL PRIMARY KEY,
    ....
);

CREATE TABLE project_user
(
    user_id    INTEGER REFERENCES user (id),

    project_id INTEGER REFERENCES project (id),

    CONSTRAINT users_projects_pk PRIMARY KEY (user_id, project_id)
);

Java代码:

public class User {
    @Id
    @GeneratedValue
    private Integer id;
    ....

    @Relation(value = Relation.Kind.MANY_TO_MANY, mappedBy = "users")
    private Set<Project> projects = Collections.emptySet();
}
public class Project {
    @Id
    @GeneratedValue
    private Integer id;
    ...
    @Relation(value = Relation.Kind.MANY_TO_MANY)
    @JoinTable(
        name = "project_user",
        joinColumns = @JoinColumn(name = "project_id"),
        inverseJoinColumns = @JoinColumn(name = "user_id"))
    @JsonIgnore
    private Set<User> users;
}

使用示例:

var users = userRepository.findByIdInList(userIdList);

        Project project = Project.builder()
            .users(users)
            .build();
        project = projectRepository.save(project);

生成的项目包含所有属性并保存在数据库中。但是,project_user表中没有记录。
我错过了什么吗?

14ifxucb

14ifxucb1#

您没有告诉Micronaut将更改级联到Project

//@Relation(value = Relation.Kind.MANY_TO_MANY)
    @Relation(value = Relation.Kind.MANY_TO_MANY, cascade = Relation.Cascade.ALL)
    @JoinTable(
            name = "project_user",
            joinColumns = @JoinColumn(name = "project_id"),
            inverseJoinColumns = @JoinColumn(name = "user_id"))
    private Set<User> users;

cascade的默认值是NONE,什么都不做。

public @interface Relation {
    /**
     * @return The relation kind.
     */
    Kind value();

    /**
     * @return The inverse property that this relation is mapped by
     */
    String mappedBy() default "";

    /**
     * How to cascade insert/delete operations to the associated entity. Default is none.
     * @return The cascade handling
     */
    Cascade[] cascade() default Cascade.NONE;

    /**
     * Cascade type handling for different associations. Cascading delete is not yet supported.
     */
    enum Cascade {
        /**
         * Cascade all operations.
         */
        ALL,
        /**
         * Cascade insert operations.
         */
        PERSIST,
        /**
         * Cascade update operations.
         */
        UPDATE,
         /**
         * Don't cascade.
         */
        NONE
    }

相关问题