我开始使用 Spring Data Elasticsearch 并发现问题。在通过存储库调用 findAll() 的运行测试期间,我得到:
No id property found for class com.example.domain.entity.Project!
当我在我的项目实体中添加字段@Transient private Long id;
时,我能够正确检索结果。但我不想添加此字段,因为我已经定义了名为projectId
. 该字段也有注释@Id
,为什么我的字段projectId
不被视为 ID?看起来@Id
注释不适用于spring-data-elasticsearch,有可能吗?
我应该怎么做才能避免向id
我的实体添加瞬态字段?它更像是解决方法而不是解决方案......
项目类:
@Entity
@Document(indexName = "project_list", type = "external")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "PROJECT_ID_GENERATOR", sequenceName = "PROJECT_SEQ", initialValue = 100, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PROJECT_ID_GENERATOR")
@Column(name = "PROJECT_ID")
private Long projectId;
.... other fields and getters/setters
}
存储库:
@Repository
public interface EsProjectRepository extends ElasticsearchRepository<Project, Long> {
List<Project> findByName(String name);
}
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-es-context.xml" })
public class ProjectRepositoryTest {
@Autowired
private EsProjectRepository esProjectRepository;
@Test
public void shouldGetAllDocuments() {
// when
Iterable<Project> actuals = esProjectRepository.findAll();
// then
assertThat(actuals).isNotEmpty();
}
}
配置(test-es-context.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath:test.properties" />
<context:component-scan base-package="com.example.domain.entity, com.example.elasticsearch.*" />
<elasticsearch:repositories base-package="com.example.elasticsearch.repository" />
<elasticsearch:transport-client id="client" cluster-name="${es.cluster}" cluster-nodes="${es.host}:${es.port}" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client"/>
</bean>
</beans>