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

ldfqzlk8  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(181)

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

  1. public class Foo {
  2. @Id
  3. @Column(name = "foo_id");
  4. Long fooId;
  5. }
  6. public class Bar{
  7. @Id
  8. @Column(name = "bar_id");
  9. Long barId;
  10. @ManyToOne
  11. @JoinTable(name = "Foo ", joinColumns = @JoinColumn(name = "bar_id"), inverseJoinColumns = @JoinColumn(name = "foo_id"))
  12. Foo foo;
  13. }

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

  1. insert into FooBarAssociation (foo_id, bar_id) values (?, ?)
  2. Cannot insert the value NULL into column 'date', table 'FooBarAssociation'; column does not allow nulls. INSERT fails.

4dbbbstv

4dbbbstv1#

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

  1. @Getter
  2. @Setter
  3. @Entity
  4. @NoArgsConstructor
  5. public class Bar {
  6. @Id
  7. @GeneratedValue(strategy = GenerationType.AUTO)
  8. Long id;
  9. @ManyToOne(cascade = CascadeType.ALL)
  10. @JoinColumn(name = "bar_id")
  11. FooBarRelation relation;
  12. public void setFoo(Foo foo) {
  13. relation = new FooBarRelation(this, foo);
  14. }
  15. }
  16. @Getter
  17. @Setter
  18. @Entity
  19. @NoArgsConstructor
  20. @EntityListeners(AuditingEntityListener.class)
  21. public class FooBarRelation {
  22. @Id
  23. @GeneratedValue(strategy = GenerationType.AUTO)
  24. Long id;
  25. @OneToOne(cascade = CascadeType.ALL)
  26. @JoinColumn(name = "foo_id")
  27. Foo foo;
  28. @OneToOne(cascade = CascadeType.ALL)
  29. @JoinColumn(name = "bar_id")
  30. Bar bar;
  31. @LastModifiedDate
  32. LocalDateTime dateTime;
  33. public FooBarRelation(Bar bar, Foo foo) {
  34. this.bar = bar;
  35. this.foo = foo;
  36. }
  37. }
  38. @Getter
  39. @Setter
  40. @Entity
  41. @NoArgsConstructor
  42. public class Foo {
  43. @Id
  44. @GeneratedValue(strategy = GenerationType.AUTO)
  45. Long id;
  46. }

字符串
试验项目:

  1. @Autowired
  2. public BarRepo barRepo;
  3. @Test
  4. public void testBar(){
  5. Bar bar = new Bar();
  6. bar.setFoo(new Foo());
  7. barRepo.save(bar);
  8. List<Bar> all = barRepo.findAll();
  9. FooBarRelation relation = all.get(0).getRelation();
  10. assertNotNull(relation.getBar());
  11. assertNotNull(relation.getFoo());
  12. assertNotNull(relation.getDateTime());
  13. }


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

展开查看全部

相关问题