Spring数据框架将数据插入错误的集合中。当我想要添加productPropertiesService.add(new ProductProperties(200,100));
时,此记录会转到Product
集合而不是ProductProperties
集合。如何解决?
我的 applicationContext :
...
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<bean id="mongoDbFactory"
class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg name="mongo" ref="mongoFactoryBean" />
<constructor-arg name="databaseName" value="test" />
</bean>
<bean id="mongoFactoryBean" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
<property name="port" value="27017"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<mongo:repositories base-package="ee.test.mongo.dao"/>
<mongo:repositories base-package="mongodb"/>
...
测试插入的类:
public class MongoDBJDBC {
public static void main( String args[] ){
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
ProductService productService = context.getBean(ProductService.class);
ProductPropertiesService productPropertiesService = context.getBean(ProductPropertiesService.class);
productPropertiesService.add(new ProductProperties(200,100));
}
}
服务
@Service
public class ProductPropertiesService {
@Autowired
private ProductPropertiesDao productPropertiesDao;
public void add(ProductProperties productProperties) {
productPropertiesDao.save(productProperties);
}
}
存储库:
@Repository
public class ProductPropertiesDao {
@Autowired
private MongoOperations mongoOperations;
public void save(ProductProperties productProperties) {
mongoOperations.save(productProperties);
}
更新 实体类:
@Document(collection = ProductProperties.COLLECTION_NAME)
public class ProductProperties implements Serializable {
public static final String COLLECTION_NAME = "product_properties";
@Id
private String id;
private String property;
...
}
问题已解决,但作为一种奇怪的副作用,文档被添加到正确的集合中,但添加了额外的字段"_class" : "ee.test.mongo.model.ProductProperties"
。如何解决?