我有以下问题:我有一个使用mongodb作为存储的spring (1.3.3)应用程序。所有这些都可以使用mongo存储库使用真正的mongodb。但是对于单元测试,我们尝试使用fongo在每个服务器上安装mongodb。测试的大部分部分在fongo中也很好,但是当我从数据库(Fongo)加载对象时,没有设置id字段。其他人也有过类似的经历吗?提前感谢你的帮助!
文档:
@Document
public class SystemEvent {
@Id
private String id;
private String oid;
private String description;
private String type;
private String severtity;
public SystemEvent(){
}
// getter/setter
}仓库:
@Repository
public interface SystemEventRepository extends MongoRepository<SystemEvent, String> {
}测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MongoFongoApplication.class)
public class MongoFongoApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
SystemEventRepository systemEventRepository;
@Test
public void testRepo() {
SystemEvent info1 = systemEventRepository.save(new SystemEvent("DESC 1", "TYPE 1", "INFO"));
SystemEvent info2 = systemEventRepository.save(new SystemEvent("DESC 2", "TYPE 2", "INFO"));
List<SystemEvent> all = systemEventRepository.findAll();
assertThat(all.size(), is(2)); // WORKS FINE
// -----
SystemEvent systemEvent = systemEventRepository.findOne(info1.getId());
assertThat(systemEvent, notNullValue()); // WORKS FINE
assertThat(systemEvent.getId(), notNullValue()); // FAILS
}
@Configuration
public static class TestConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "test";
}
@Override
public Mongo mongo() throws Exception {
return new Fongo(getDatabaseName()).getMongo();
}
}
}发布于 2018-02-08 18:07:12
尝试在文档模型类中为Id字段添加这些内容。这应该能解决你的问题。
@Id
@Field(value = GdnBaseMongoEntity.ID)
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String id;对于GeneratedValue,您需要添加javax 的依赖项。您可以将其添加到您的pom.xml文件中。
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>对于build.gradle
compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.0-api', version: '1.0.0.Final'https://stackoverflow.com/questions/37006665
复制相似问题