ibatis Tips 之 xmlResultName

如何将查询结果集映射为 xml格式的数据?

映射文件:

<!--   mapping to xml data     -->
	<select id="selectXmlData" resultClass="xml" xmlResultName="Product" parameterClass="int">
		<![CDATA[
			select * from t_product where prd_id=#value#
		]]>
	</select>
	<select id="selectXmlDatas" resultClass="xml" xmlResultName="Product">
		<![CDATA[
			select prd_id as id,
       prd_description as description,
       prd_price as price
from t_product	
                ]]>
	</select>
<!--  END  mapping to xml data-->

 DAO层:

public Object getXmlData(int id) throws SQLException {
		init();
		Object obj = (Object)sqlMapClient.queryForObject("selectXmlData", id);
		return obj;
	}


	public List getXmlDatas() throws SQLException {
		init();
		List list = (List)sqlMapClient.queryForList("selectXmlDatas");
		return list;
	}

 测试类:

public class ProductTest {

	ProductDAO productDao = new ProductDAOImpl();
	
	public static void main(String[] args) throws SQLException {
		ProductTest ptest = new ProductTest();
		ptest.getXmlData(1);
		System.out.println("-------------------");
		ptest.getXmlDatas();
	}
	
	/**
	 * 获得XML格式的数据
	 * @throws SQLException
	 */
	public void getXmlData(int id) throws SQLException{
		// 查找t_product表,将其结果映射到xml!
		// 返回值是xml形式的字符串
		Object obj = (Object) productDao.getXmlData(1);
		if(obj instanceof Product) {
			System.out.println("return type is Product");
		}else if(obj instanceof String) {
			System.out.println("return type is String");
		}else {
			System.out.println("return type is unknow");
		}
		System.out.println(obj);
	}
	
	public void getXmlDatas() throws SQLException {
		List list = (List)productDao.getXmlDatas();
		Iterator i = list.iterator();
		while(i.hasNext()) {
			Object obj = i.next();
			System.out.println(obj.getClass());		
		}	
		System.out.println(list);
	}
}

 结果:

return type is String
<?xml version="1.0" encoding="UTF-8"?>

<Product>

      <prd_id> 1 </prd_id>

      <prd_description>basketball</prd_description>

     <prd_price>206.99</prd_price>

</Product>
-------------------
class java.lang.String
class java.lang.String
[<?xml version="1.0" encoding="UTF-8"?>

<Product>

      <id> 1</id>

      <description>basketball</description>

     <price>206.99</price>

</Product>,

<?xml version="1.0" encoding="UTF-8"?>

<Product>

     <id> 2 </id>

     <description>football</description>

    <price>106.99</price>

</Product>]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值