如何使用Spring Data MongoDB不保存Bean属性值到MongoDB
嘿,我来给你唠唠怎么解决这个问题!在Spring Data MongoDB里,要让Bean里的某个属性不被保存到MongoDB数据库,有几个简单实用的办法,我给你拆解清楚:
最常用的方法:@Transient注解
这是最简单直接的方式,你只需要在不想被持久化的属性(或者它的getter方法)上面加上@Transient注解,Spring Data MongoDB就会自动忽略这个属性,不会把它存入数据库。
举个你的Person类的例子:
import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import javax.persistence.Transient; // 也可以用org.springframework.data.annotation.Transient @Document(collection = "persons") public class Person { @Id private String id; private String name; private int age; // 这个属性不会被保存到MongoDB @Transient private String tempProperty; // 下面是对应的getter和setter public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getTempProperty() { return tempProperty; } public void setTempProperty(String tempProperty) { this.tempProperty = tempProperty; } }
不管你给tempProperty赋什么值,当你通过MongoRepository保存Person对象时,这个属性都不会出现在MongoDB的文档里。
另外,如果是某个动态计算的属性(比如通过getter方法生成的)不想被保存,你也可以直接在getter上加@Transient:
@Transient public String getFullInfo() { return this.name + "(" + this.age + "岁)"; }
这样这个计算出来的fullInfo也不会被持久化。
进阶方案:自定义映射配置(适合复杂场景)
如果你的场景比较特殊(比如不想在实体类上加注解,或者需要动态控制哪些属性被忽略),可以自定义MongoDB的映射规则。比如通过MongoMappingContext来配置属性过滤,但这种方式相对复杂,一般日常开发用上面的@Transient就完全够用了。
总的来说,90%的场景下,@Transient注解就能完美解决你的问题,简单又省心!
内容的提问来源于stack exchange,提问作者chiku
相关产品推荐
相关产品推荐

