spring @JoinTable注解中使用的表中的额外列

ldfqzlk8  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(83)

我正在使用Sping Boot 和Hibernate创建一个REST API。
我有两个表,我们称之为表Foo和表Bar。它们有一个1-N关联,通过第三个表Map,我们称之为FooBarAssociation。我使用@JoinTable注解在它们之间创建了这个关联。
这是我现在所拥有的一个最小的例子。

public class Foo {
    @Id
    @Column(name = "foo_id");
    Long fooId;
}

public class Bar{

    @Id
    @Column(name = "bar_id");
    Long barId;

    @ManyToOne
    @JoinTable(name = "Foo ", joinColumns = @JoinColumn(name = "bar_id"), inverseJoinColumns = @JoinColumn(name = "foo_id"))
    Foo foo;

}

字符串
问题是,表FooBarAssociation还有第三列,应该包含关系创建的日期。所以有三列:foo_idbar_iddate。当hibernate尝试向FooBarAssociation插入新条目时,它会生成异常,因为date列不允许空值。有没有一种方法可以告诉Hibernate如何填充这个额外的列?

insert into FooBarAssociation (foo_id, bar_id) values (?, ?)

Cannot insert the value NULL into column 'date', table 'FooBarAssociation'; column does not allow nulls. INSERT fails.

4dbbbstv

4dbbbstv1#

既然这个关系是强制性的,我认为修改中间层的唯一方法就是显式地控制它。这会有所帮助。

@Getter
@Setter
@Entity
@NoArgsConstructor
public class Bar {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "bar_id")
    FooBarRelation relation;

    public void setFoo(Foo foo) {
        relation = new FooBarRelation(this, foo);
    }
}

@Getter
@Setter
@Entity
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
public class FooBarRelation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "foo_id")
    Foo foo;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "bar_id")
    Bar bar;

    @LastModifiedDate
    LocalDateTime dateTime;

    public FooBarRelation(Bar bar, Foo foo) {
        this.bar = bar;
        this.foo = foo;
    }
}

@Getter
@Setter
@Entity
@NoArgsConstructor
public class Foo {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
}

字符串
试验项目:

@Autowired
    public BarRepo barRepo;

    @Test
    public void testBar(){
        Bar bar = new Bar();
        bar.setFoo(new Foo());
        barRepo.save(bar);
        List<Bar> all = barRepo.findAll();
        FooBarRelation relation = all.get(0).getRelation();
        assertNotNull(relation.getBar());
        assertNotNull(relation.getFoo());
        assertNotNull(relation.getDateTime());
    }


级联类型和其他小细节对你;)

相关问题