【发布时间】:2021-11-12 01:29:28
【问题描述】:
我正在使用 org.mongodb:bson:4.1.2 和 org.springframework.boot:spring-boot-starter-data-mongodb:2.4.7。
我的实体看起来像:
@Entity
@Table(name = "fire_alert")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Document(collection = "alert_<dynamic>")
@Data
public class AlertPO implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "owner_id")
private Long ownerId;
@Column(name = "alert_type")
private Long alertType;
}
因为会有数百万的alert,所以我需要根据AlertPO.alertType将记录保存到不同的mongodb集合中。
深入org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity后发现@Document的注解字段collection支持SpEL表达式。这种表达式会在org.springframework.data.mongodb.core.mapping.BasicMongoPersistentEntity#getCollection中求值,显然当前实体不会被添加到EvaluationContext中。
根据这个问题:
How to Map a Java Entity to Multiple MongoDB Collections in Spring Data?
我们可以覆盖存储库以使用MongoTemplate 以编程方式将数据持久化到适当的集合中。但是我们将使用 JPA,我们不想直接使用MongoTemplate。如何做到这一点?
【问题讨论】:
标签: java spring mongodb spring-boot