NHibernate and XML Column Type
这是Ayende Rahien对NHibernate所做的一个扩展,让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; }
}
}
{
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>
<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),1) as Document;
Console.WriteLine(document.Xml.OuterXml);
Console.ReadLine();
session.Flush();
}
}
}
数据库中的结果
{
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),1) as Document;
Console.WriteLine(document.Xml.OuterXml);
Console.ReadLine();
session.Flush();
}
}
}