JPA将外键插入为空

时间:2019-09-21 22:40:15

标签: java hibernate spring-boot jpa

好吧,我尝试了所有可以在网上找到的东西,但还是没有运气。

我有2节课。趋势图和趋势。这是OneToManyMapping。 TrendsChart可以有多个趋势。

DB:SQL Server

趋势图表

CREATE TABLE [dbo].[TrendsChart](
    [id] [int] NOT NULL IDENTITY,
    [Name] [varchar] (50) NULL,
PRIMARY KEY CLUSTERED
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

趋势表

CREATE TABLE [dbo].[Trends](
    [TrendsID] [int] NOT NULL IDENTITY,
        [ItemName] [varchar] (100) NULL,
    [chart_id] [int] NULL
PRIMARY KEY CLUSTERED
(
    [TrendsID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Trends]  WITH CHECK ADD  CONSTRAINT [FK_Trends_TrendsChart] FOREIGN KEY([chart_id])
REFERENCES [dbo].[TrendsChart] ([id]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Trends] CHECK CONSTRAINT [FK_Trends_TrendsChart]
GO

趋势图模型

@Entity
@Table(name = "TrendsChart")
public class TrendsChart {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

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

    @OneToMany(mappedBy="trendsChart", cascade = CascadeType.ALL)
    List<Trends> trends = new ArrayList<>();

趋势模型

@Entity
@Table(name = "Trends")
public class Trends {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="TrendsID")
    private int trendsID;

    @Column(name="ItemName")
    private String itemName;

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name ="chart_id", nullable=false, updatable = false, insertable = true,referencedColumnName = "id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private TrendsChart trendsChart;

我正在做控制器

trendsChartRepository.save(trendsChart);

所有数据均已正确填充,但 chart_id 列始终为空

1 个答案:

答案 0 :(得分:0)

您必须积极设置TrandChart的每种趋势:

@Entity
@Table(name = "TrendsChart")
public class TrendsChart {

   //...

   public void addTrend(Trends trend) {
      this.trends.add(trend);
      trend.setTrendsChart(this);
   }

}

然后保存:

TrendsChart trendsChart = new TrendsChart();
Trends trend = new Trend();
trendsChart.setTrend(trend);
trendsChartRepository.save(trendsChart);

有关此主题的很好的教程: https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/