gpt4 book ai didi

java - Spring Rest 数据 - 外键对象 URL 未在 @RequestBody 中转换

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:33 29 4
gpt4 key购买 nike

我正在使用 Spring Rest Data,并且已将我的应用程序配置为使用 RepositoryRestMvcConfiguration。我有以下 2 个实体:

企业有很多用户关系。

@Entity
@Table(name="enterprise")
public class Enterprise extends BaseEntity
{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="enterprise_id")
private Long id;

@Column(name="enterprise_name")
private String name;
}

@Entity
@Table(name="user")
public class User extends BaseEntity
{
@Id
@Column(name="user_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "owner_enterprise_id", referencedColumnName = "enterprise_id")
private Enterprise ownerEnterprise;

@Column(name="username")
private String userName;

@Column(name="emailaddress")
private String emailAddress;

@Column(name="passwordhash")
private String password;
}

我能够发送帖子请求来创建企业,接下来我想做的是创建一个对企业有 FK 的用户。

这是我的用户 Controller :

@RequestMapping(value="/createUser", method=RequestMethod.POST)
public ResponseEntity<User> register(@RequestBody User user) {

User newUser = userService.register(user);
return new ResponseEntity<User>(newUser, HttpStatus.OK);
}

当我尝试发送帖子以创建新用户时:

curl -i -X POST \
-H "Content-Type: application/json" \
-d '{"userName":"johndoe", "emailAddress":"johndoe@gmail.com", "password":"johnpass1", "ownerEnterprise":"http://localhost:8080/enterprises/1"
}' \
http://localhost:8080/createUser

我在我的 Controller 中放置了断点,发现 User 对象的 ownerEnterprise 字段为空(但其他字段包含正确的数据)。有人可以帮我看看我错过了什么吗?我已经尝试搜索了几个小时,但没有成功。

我还验证了 url 是正确的:

curl http://localhost:8080/enterprises/1 

{
"name" : "MyEnterprise",
"_links" : {
"self" : {
"href" : "http://localhost:8080/enterprises/1"
}
}
}

非常感谢您的宝贵时间!

最佳答案

您的界面不是基于 Spring-Data-REST 的界面,它是直接的 Spring MVC 请求,因此以下类型的 POST 应该适合您:

{"userName":"johndoe", "emailAddress":"johndoe@gmail.com", "password":"johnpass1", "ownerEnterprise":{"id":1, "name":"Test Enterprise"}}

本质上,这是您的 User 实体的 json 表示。

如果您将 User 实体公开为 @RepositoryRestResource,那么您的原始请求应该有效

关于java - Spring Rest 数据 - 外键对象 URL 未在 @RequestBody 中转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27082040/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com