NHibernate and XML Column Type

这是Ayende RahienNHibernate所做的一个扩展,让NHibernate可以保存XML类型的数据到数据库中,这在某些情况下非常有用。可以把XML转换为XmlDocument保存,也可以直接把对象序列化成XML保存到数据库中。看一下简单的使用过程:

业务实体类

public class Document
{
    
int id;

    
string author;

    XmlDocument xml;


    
public Document(string author, XmlDocument xml)
    
{
        
this.author = author;

        
this.xml = xml;
    }


    
public Document()
    
{

    }


    
public int Id
    
{
        
get return id; }

        
set { id = value; }
    }


    
public string Author
    
{
        
get return author; }

        
set { author = value; }
    }


    
public XmlDocument Xml
    
{
        
get return xml; }

        
set { xml = value; }
    }

}

映射文件,注意xml属性的类型,下载的代码中有XmlType的实现。

<?xml version='1.0' encoding='utf-8'?>

<hibernate-mapping

     
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

     
xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='urn:nhibernate-mapping-2.0'>

  
<class name='NHibernate.Xml.Document,eXmlDataType2003' table='Documents'>

    
<id name='Id'>

      
<generator class='identity'/>

    
</id>

    
<property name='Author'/>

    
<property name='Xml' column='xml' type='NHibernate.Xml.XmlType, XmlDataType2003' />

  
</class>

</hibernate-mapping>

客户程序使用

public class Program
{
    
static void Main(string[] args)

    
{
        Configuration cfg 
= new Configuration();

        cfg.AddAssembly(
typeof (Document).Assembly);

        ISessionFactory factory 
= cfg.BuildSessionFactory();

        
using(ISession session = factory.OpenSession())

        
{
            XmlDocument xml 
= new XmlDocument();

            xml.Load(
"c:\\temp\\Municipalities.xml");

            Document doc1 
= new Document("Author1",xml);

            session.Save(doc1);

            session.Flush();


            Document document 
= session.Load(typeof (Document),1as Document;

           Console.WriteLine(document.Xml.OuterXml);

            Console.ReadLine();

           session.Flush();

        }


    }

}
数据库中的结果

 

最后把所有的感谢都给Ayende Rahien仁兄吧。

完整源码下载

.NET1.1版本:/Files/Terrylee/NHibernate.Xml-Sample2003.zip[Mircea Jivoin提供]

.NET2.0版本:/Files/Terrylee/NHibernate.Xml-Sample2005.zip[Ayende Rahien提供]

posted @ 2006-06-27 12:23  TerryLee  阅读(4059)  评论(6编辑  收藏  举报