在多对一关系中更新FK值

时间:2019-09-02 03:47:40

标签: spring-boot jpa

我正在尝试更新表1中包含表2外键的记录。表1中的当前记录指向表2上的id = 2。我希望它指向表2上的Id = 4。

我正在使用Http PUT更新值。 http PUT调用的主体为

URL: http://localhost:8080/table1s/1

{
  "name": "Dependent 16",
  "tabId":"http://localhost:8080/table2s/4"
}

我知道此值已正确解释为表2记录。但是,在处理PUT请求时,将删除更新的记录,并保留外键的旧值。

通过深入研究Java库,似乎可能是我在表1和表2之间的关联配置。

任何帮助将不胜感激。

'''表创建SQL。

CREATE TABLE IF NOT EXISTS table2 (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name varchar(32) not null)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS table1 (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name varchar(32) not null,
  tab_id int not null,
  CONSTRAINT FK_table1_table2
    FOREIGN KEY (tab_id)
    REFERENCES table2 (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

insert into table2 (id, name) 
    values(1, "First row");

insert into table2 (id, name) 
    values(2, "Second row");

insert into table2 (id, name) 
    values(3, "Third row");

insert into table2 (id, name) 
    values(4, "Fourth row");

insert into table2 (id, name) 
    values(5, "Fifth row");


insert into table1 (id, name, tab_id) 
    values(1, "Dependent 1", 2);

insert into table1 (id, name, tab_id) 
    values(2, "Dependent 2", 2);

insert into table1 (id, name, tab_id) 
    values(3, "Dependent 3", 5);

'''结束SQL

'''Java实体-表1

@Data
@NoArgsConstructor
@Entity
@Table(name = "table1")
@XmlRootElement
public class Table1 implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Long id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 32)
    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "tabId")
    private Table2 tabId;
}

-------------------- Java实体-表2

@Data
@NoArgsConstructor
@Entity
@Table(name = "table2")
@XmlRootElement
public class Table2 implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotNull
    @Size(min = 1, max = 32)
    private String name;

}

--------------------表1存储库

@RepositoryRestResource
public interface table1Repository extends JpaRepository<Table1, Long>{

}

--------------------表2存储库

@RepositoryRestResource()
public interface table2Repository extends JpaRepository<Table2, Long>{

}

我希望在PUT请求之后,查询结果应从

更改
select * from table1;
+----+--------------+--------+
| id | name         | tab_id |
+----+--------------+--------+
|  1 | Dependent 1 |      2 |
|  2 | Dependent 2  |      2 |
|  3 | Dependent 3  |      5 |
+----+--------------+--------+

select * from table1;

+----+--------------+--------+
| id | name         | tab_id |
+----+--------------+--------+
|  1 | Dependent 14 |      4 |
|  2 | Dependent 2  |      2 |
|  3 | Dependent 3  |      5 |
+----+--------------+--------+

0 个答案:

没有答案