Java 如何使用Spring数据Rest和MongoRepository在属性上设置只读?
我想这样做:-但是这种方法在SpringDataREST中不起作用 我知道有一个注释@ReadOnlyProperty,这将是使用它的最佳解决方案,因为它反映在JSON模式响应中:Java 如何使用Spring数据Rest和MongoRepository在属性上设置只读?,java,json,spring,mongodb,rest,Java,Json,Spring,Mongodb,Rest,我想这样做:-但是这种方法在SpringDataREST中不起作用 我知道有一个注释@ReadOnlyProperty,这将是使用它的最佳解决方案,因为它反映在JSON模式响应中: { "title" : "org.example.Person", "properties" : { "firstName" : { "readOnly" : true, "type" : "string" }, .. 但通过这种方式,GET操作不会返回带
{
"title" : "org.example.Person",
"properties" : {
"firstName" : {
"readOnly" : true,
"type" : "string"
},
..
但通过这种方式,GET操作不会返回带注释的属性(它的值为null)
更新1:添加代码示例
@Getter
@Document
public class Person {
@Id
private String id;
private String firstName;
private String lastName;
@ReadOnlyProperty
private String comments;
}
@RepositoryRestResource
public interface PersonRepository extends MongoRepository<Person, String> {
}
@Getter
@文件
公共阶层人士{
@身份证
私有字符串id;
私有字符串名;
私有字符串lastName;
@只读属性
私有字符串注释;
}
@存储资源
公共接口PersonRepository扩展了MongoRepository{
}
更新2:多亏了Leon的建议,我在推理中发现了一个错误-使用注释@JsonIgnore和@JsonProperty的方法工作正常,但是也用测试数据阻塞了配置数据库-这就是为什么GET操作会在注释字段中显示早期的null值。我假设您使用的是Jackson,并且可以通过构造函数初始化属性。解决方案是使用
@JsonCreator
注释并通过constructor@Leon我在模型类中添加了带有JsonCreator注释的构造函数和一个参数,但这只会导致Jackson2RepositoryPopulatorFactoryBean中出现异常-仍然可以发送补丁并更新我的模型类的其他字段(我希望是只读的)。您仍然可以使用setter设置其他值。您能提供您的产品的代码示例吗Java@Leon现在,我的主要问题是,我可以通过Rest更新Person类的每个字段。好的,我同意。你用的是什么版本的杰克逊?