使用Spring Data MongoDB创建新文档时将_id复制到新字段可以通过以下步骤实现:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
@Field
注解指定该字段对应MongoDB文档中的_id字段。同时,使用@Id
注解标记一个字段作为文档的主键。import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "your_collection_name")
public class YourEntity {
@Id
private String id;
@Field("_id")
private String customId;
// 其他字段和方法...
}
import org.springframework.data.mongodb.repository.MongoRepository;
public interface YourRepository extends MongoRepository<YourEntity, String> {
default YourEntity saveWithCustomId(YourEntity entity) {
entity.setCustomId(entity.getId());
return save(entity);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourService {
private final YourRepository yourRepository;
@Autowired
public YourService(YourRepository yourRepository) {
this.yourRepository = yourRepository;
}
public void saveNewDocument(YourEntity entity) {
yourRepository.saveWithCustomId(entity);
}
}
这样,当调用saveNewDocument方法保存新文档时,_id的值将会被复制到customId字段中。
领取专属 10元无门槛券
手把手带您无忧上云