具有@JoinTable的单向@OneToMany不更新联接表

时间:2018-12-14 14:41:53

标签: hibernate spring-boot jpa one-to-many querydsl

我正在尝试使用Spring Boot,JPA,QueryDsl和内存H2数据库实现单向一对多映射。当我通过schema.sql插入数据时,将正确检索文件关系。问题是将新对象存储到事件表中时。

Schema.sql

CREATE TABLE tag (
  tag_id  INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  label   VARCHAR(25)
);

CREATE TABLE event (
  event_id       INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  owner_id       INTEGER NOT NULL,
  place_id       INTEGER NOT NULL,
  content        TEXT,
  thumbnail      VARCHAR(100),
  heading        VARCHAR(50),
  date_added     DATE,
  start_date     DATE,
  start_time     TIME,
  end_date       DATE,
  end_time       TIME,
  approved       BOOL,
  FOREIGN KEY (owner_id) REFERENCES user (user_id),
  FOREIGN KEY (place_id) REFERENCES place (place_id)
);

CREATE TABLE event_tag (
  event_id   INTEGER NOT NULL,
  tag_id     INTEGER NOT NULL,
  PRIMARY KEY (event_id,tag_id),
  KEY fk_event (event_id),
  KEY fk_tag (tag_id),
  CONSTRAINT fk_tag FOREIGN KEY (tag_id) REFERENCES tag (tag_id),
  CONSTRAINT fk_event FOREIGN KEY (event_id) REFERENCES event (event_id)
)

Event.java

@Entity
@Getter
@Setter
@EqualsAndHashCode
@Table(name = "event")
public class Event implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "event_id")
    protected Long id;

    ...

    //todo: not working while saving
    @OneToMany(cascade=CascadeType.ALL)
    @JoinTable(
            name = "event_tag",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private Set<Tag> tags;

    ...
}

Tag.java

@Entity
@Getter
@Setter
@NoArgsConstructor
@EqualsAndHashCode
@Table(name = "tag")
public class Tag implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "tag_id")
    private Long id;

    @Column(name = "label")
    private String label;
}

然后这就是我将事件存储在服务中的方式 EventService.java

public Optional<Event> create(Event event) {
    try {
        entityManager.unwrap(Session.class).save(event);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return Optional.ofNullable(event);
}

此时,事件对象提供了标记和事件之间的关系 Tags are related to the Event Object

我从来没有收到任何错误。会话保存对象后,联接表保持不变。事件表将使用新存储的对象进行扩展。

也是我的application.properties:

spring.datasource.url=jdbc:h2:mem:testdb;MODE=MYSQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.h2.console.enabled=true

我想念什么?任何帮助表示赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

保存后不执行flush(),因此不会生成任何SQL语句。

调用flush()或确保create()在事务上下文中执行。