简体   繁体   English

在 jpa hibernate 表上保存数据在连接列上给出 null

[英]Saving data on jpa hibernate table gives null on join columns

I have two tables which are related to each other, table "user" and "address":我有两个相互关联的表,表“用户”和“地址”:

@Entity
@Table(name = "user")
@Data
public class User{

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

    @NotNull
    @Column(unique = true)
    private String user_name;

    @Column
    private String description;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    protected Set<Address> addresses= new HashSet<>();
}

While in the other table:在另一个表中:

@Entity
@Table(name = "address")
@Data
public class Address{

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

    @ManyToOne
    @JoinColumn(name = "user_id")
    protected User user;

    private String description;
}

I did a post request to create new user with some addresses:我做了一个帖子请求,用一些地址创建新用户:

@PostMapping ("/user/create")
public ResponseEntity post(@RequestBody User user) {
    userService.saveNewUser(user);
     // return
}

In a post request I sent this json:在发帖请求中,我发送了这个 json:

{
 
  "user_name": "example",
  "description": "this is a  user description",
  "addresses": [
    {
      "description": "this is a address 1"
    },
    {
      "description": "this is a address 2"
    }
  ]
}

When I insert data I get the "address" table the "user_id" is null, the data are inserted but the relations are not there?当我插入数据时,我得到“地址”表中的“user_id”是 null,数据已插入但关系不存在? What I'm doing wrong here?我在这里做错了什么? Please help!请帮忙!

Update: Let's say I have this method saveNewUser on the service, how to call update Address?更新:假设我在服务上有这个方法 saveNewUser,如何调用更新地址?

public Oject saveNewUser(User user ) {
       // 
        return jpaRepository.save(user);
    }

You have to support all relations manually.您必须手动支持所有关系。 Hibernate doesn't do it for you. Hibernate 不会为你做这件事。 So you need to set a user for each address.所以你需要为每个地址设置一个用户。

public Oject saveNewUser(User user ) {
   user.getAddresses().forEach(address -> address.setUser(user));
   return jpaRepository.save(user);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM