蓝白袜 番号:hibernate 动态pojo Map

来源:百度文库 编辑:九乡新闻网 时间:2024/04/30 14:36:20
动态domain,用一个Map来代替对像,把原来domain中的属性做key值存进来 
实体映射 
 
 
    
       
  
 
          type="big_decimal" 
       column="INIT_PRICE"/> 
          type="string" 
       column="DESCRIPTION"/> 
          entity-name="UserEntity" 
       column="USER_ID"/> 
       
 
 
          
               
  
 
           type="string" 
        column="USERNAME"/> 
    
        
        
  
 
 
 
注意: 
1.变为 
2. 中的class属性变为entity-name 

动态domain的工作方式 
Map user = new HashMap(); 
user.put("username","davide"); 

Map item1 = new HashMap(); 
item1.put("description","an item for auction"); 
item1.put("initialPrice",new BigDecimal(99)); 
item1.put("seller",user); 

Map item2 = new HashMap(); 
item2.put("description", "Another item for auction"); 
item2.put("initialPrice", new BigDecimal(123)); 
item2.put("seller", user); 

Collection itemsForSale = new ArrayList(); 
itemsForSale.add(item1); 
itemsForSale.add(item2); 
user.put("itemsForSale", itemsForSale); 
session.save("UserEntity", user); 
第一个Map为UserEntity,接下来的两个是ItemEntitys 
为两个Map建立了seller user链接. 
一个Collection在inverse方设置one-to-many关联初始化 

使用方法 
Long storedItemId = (Long) item1.get("id"); 
Map loadedItemMap = (Map) session.load("ItemEntity", storedItemId); 
loadedItemMap.put("initialPrice", new BigDecimal(100)); 

多次映射一个类 
 
        entity-name="ItemAuction" 
        table="ITEM_AUCTION"> 
   ... 
    
    
 
        entity-name="ItemSale" 
        table="ITEM_SALE"> 
   ... 
    
    
 
 
model.Item持久化类映射了id,description,initialPrice,salesPrice属性. 
处决于你运行时的实体名,有些属性是持久化的有的则不是. 
Item itemForAuction = new Item(); 
itemForAuction.setDescription("An item for auction"); 
itemForAuction.setInitialPrice( new BigDecimal(99) ); 
session.save("ItemAuction", itemForAuction); 

Item itemForSale = new Item(); 
itemForSale.setDescription("An item for sale"); 
itemForSale.setSalesPrice( new BigDecimal(123) ); 
session.save("ItemSale", itemForSale); 
正是由于有了逻辑名,hibernate才知道向哪个表中插入数据. 

将数据保存到xml文件 
Session dom4jSession = session.getSession(EntityMode.DOM4J); 
Element userXML = 
(Element) dom4jSession.load(User.class, storedUserId); 
可以通过以下方式打印到控件台 
try { 
    OutputFormat format = OutputFormat.createPrettyPrint(); 
    XMLWriter writer = new XMLWriter( System.out, format); 
    writer.write( userXML ); 
} catch (IOException ex) { 
   throw new RuntimeException(ex); 

若是继续的前面的例子,你可能会得以下结果 
 
   1 
   johndoe 
    
      
       2 
       99 
       An item for auction 
       1 
    
 
      
3 
123 
Another item for auction 
1