2012-10-15 75 views
0

我必須使用到數據庫的調用休眠映射本地Java對象自己實現

List<Object> result = session.openSession().createSQLQuery(myNativeSQLQuery).list(); 

不,我可以在該列表

Iterator iter = result.iterator(); 
while(iter.hasNext()){ 
    Object[] item = (Object[]) iter.next(); 
} 

迭代但是,對象是沒有用的,爲自己和所以我想讓這個對象映射到我實現的類上。

public class MyClass { 

    private Long id; 

    private String name 

    private Set<MySecondClass> myList 

    public void myFunc(){ 
     // do sth with that id or any other attribute mapped 
    } 
} 

我不想使用Hibernate註釋之類的東西,因爲定義的類將數據由定義原生SQL查詢XML文件被填滿。這樣我就想將生成的文檔實現爲mongodb,以便快速訪問數據。

你看到下面

<?xml version="1.0" encoding="UTF-8"?> 
<mapping> 
<resource>myResource</resource> <!-- the resource table in mysql where the base query is executed --> 
<destination>myDestination</destination> <!-- the destination collection in mongodb --> 

<document mapped="MyClass"> <!-- that docuemnt and the base query will be mapped on the class "MyClass" 

    <base sql="select id, name from table1" /> 
    <reference id="_ID_" column="id" /> <!-- use the result from the base query and replace the placeholder _ID_ of all following sql querys with the value of id in that current iteration --> 

    <lists> 
     <myList mapped="MySecondClass" sql="select col1, col2 from table2 where referenceId=_ID_" /> <!-- each element of that listed will be mapped on MySecondClass and fills the property "myList" 
    </lists> 

</document> 

+0

目前還不清楚你想達到什麼目的。 「在課堂上映射對象」意味着什麼? –

+0

我從Hibernate獲得的對象的類型爲Object [],其中所有列都可用。所以從查詢「select id,name from table1」我會在每次迭代中得到一個_object [] obj_,其中列「id」在obj [0]處可用,但是我想將它映射到id屬性 – MatthiasLaug

+0

是的,我知道對象數組中的select語句結果。對於'在id屬性上映射'意味着什麼? –

回答

0

這樣的XML文件中的結果可知我不需要複製/映射對象的例子。我可以使用spring數據中的註釋org.springframework.data.mongodb.core.mapping.Document和摘錄類com.mongodb.BasicDBObject

@org.springframework.data.mongodb.core.mapping.Document 
public class BasicDocument extends BasicDBObject { 

} 

之後,我可以創建只是做

BasicDocument doc = new BasicDocument(); 
doc.put("key", "value"); 

和存儲文檔的mongodb成。這樣我甚至可以創建列表。