2013-07-19 52 views
0

我正在使用Spring Data Neo4J。Spring Data/Neo4J存儲庫:findByXXX返回地圖,而不是實體

我已經擴展了基本GraphRepository接口,添加一個方法,如下:

/** 
* Extension to the repository interface for standard Spring Data repo's that 
* perform operations on graph entities that have a related RDBMS entity. 
* 
* @author martypitt 
* 
* @param <T> 
*/ 
public interface RelatedEntityRepository<T> extends GraphRepository<T>, 
RelationshipOperationsRepository<T>,CypherDslRepository<T> { 
    public T findByEntityId(Long id); 
} 

然而,我發現,這個接口的子類不按預期行爲。

public interface UserRepository extends RelatedEntityRepository<UserNode>{ 
} 

當我打電話UserRepository.findByEntityId(1L),我希望得到的返回UserNode,或null一個實例。

取而代之,我得到一個scala.collection.JavaConversions$MapWrapper

但是,如果我改變UserRepository指定類型,然後一切正常(雖然違背了基類的目的)

public interface UserRepository extends RelatedEntityRepository<UserNode>{ 
    public UserNode findByEntityId(Long id); 
} 

這是一個測試:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration({"/graph-test-context.xml"}) 
@Transactional 
public class UserRepositoryTests { 

    @Autowired 
    private UserRepository userRepository; 

    // For Bug 
    @Test 
    public void canFindByEntityId() 
    { 
     UserNode userNode = new UserNode(1L); 
     userRepository.save(userNode); 

     UserNode node = userRepository.findByEntityId(1L); 
     assertThat(node, notNullValue()); 
     assertThat(node, isA(UserNode.class)); 
    } 
} 

運行這個測試UserRepository中的額外行註釋失敗。 Otherwsie,測試通過。

這是一個錯誤?我是否正確編寫了repo界面?

+0

似乎存儲庫方法正在返回* Result *對象而不是正確的類對象,您可以嘗試將* findB返回的對象yEntityId *方法將它傳遞給* Neo4jOperations *類的* convert *方法:'UserNode node = neo4jOperations.convert(userRepository.findByEntityId(1L),UserNode.class);' – remigio

回答

0

remigio是正確的,它返回一個包裝的對象,你必須轉換。

但是,對於不同的實體類型,使用公共基類是不可能的。

這裏的原因:

你會想創造與@MapResult註釋應該工作,如查詢結果的包裝類。

@MapResult 
public interface ResultMap<T> { 
    @ResultColumn("usernode") <T> getNode(); 
} 

而且在你的倉庫類使用這樣的:

ResultMap<T> findByEntityId(Long id); 

而且像這樣在您的測試:

ReultMap<UserNode> = userRepository.findByEntityId(1L); 

不幸的是,不,原因有二:

  • 存儲庫返回一個NodeProxy類在地圖內而不是用戶節點
  • @ResultColumn註釋必須配置一個列名,這似乎是根據類的類型,在您的情況下,「usernode」在結果中自動生成的。

什麼工作是這樣的,那麼:

@MapResult 
public interface ResultMap { 
    @ResultColumn("usernode") NodeProxy getNode(); 
} 

ResultMap rm = userRepository.findByEntityId(1L); 
NodeProxy proxy = rm.getNode(); 
UserNode userNode = template.convert(proxy, UserNode.class); 

template是自動裝配這樣的:

@Autowired Neo4jOperations template; 

遺憾的是並沒有真正工作,要麼,由於第2點上方:(

相關問題