2

我有以下问题:我有一个使用 mongodb 作为存储的 spring-boot (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();
        }
    }

}
4

1 回答 1

0

尝试在 Document 模型类中为您的 Id 字段添加这些。这应该可以解决您的问题。

@Id
@Field(value = GdnBaseMongoEntity.ID)
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String id;

对于GeneratedValue,您需要为javax persistence API添加依赖项。你可以在你的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'
于 2018-02-08T18:07:12.807 回答