自己动手写ORM框架(一):目标效果预览(一)

2014-11-24 11:47:21 · 作者: · 浏览: 27
以前还在大学中学习java的时候,就学着使用Hibernate进行持久化层的操作。当时只是觉得这框架很神奇,能够不写SQL语句就能操作数据库。当时也不知道其内部原来是什么,就只知道怎么去用,怎么去写XML配置文件。毕竟当时来讲,代码量有限,接触的 编程思想也不多,也没有办法去做深入的研究。最近一段时间以来一直在做.net的开发,其ORM框架有微软自带的Framework,当然也有从Hibernate演化而来的.net平台下的NHibernate. 最近学东西,就很好奇其内部的转换过程。恰巧在博客园中,很幸运到读到了“奋斗”前辈关于自己动手写ORM的一系列文章,用C#完成。特此转载,希望大家一起学习。以下是转载内容,这一篇主要是描述最终的框架效果,以后会一步一步的去用代码实现这个框架。
最终实现后达到的效果,只需写少量代码就可实现CURD操作。
DAL层代码:
StudentDAL代码
public class StudentDAL
{
EntityManager entityManager = EntityManagerFactory.CreateEntityManager();
public StudentDAL() { }
public StudentDAL(IDbTransaction transaction)
{
entityManager.Transaction = transaction;
}
public List FindAll()
{
return entityManager.FindAll();
}
public int Save(StudentEntity entity)
{
return entityManager.Save(entity);
}
public int Update(StudentEntity entity)
{
return entityManager.Update(entity);
}
public int Remove(StudentEntity entity)
{
return entityManager.Remove(entity);
}
public int Remove(object id)
{
return entityManager.Remove(id);
}
public List FindById(object id)
{
return entityManager.FindById(id);
}
public List FindByProperty(string propertyName,object value)
{
return entityManager.FindByProperty(propertyName, value);
}
}
实体类与
数据库
表的映射关系配置:
StudentEntity代码
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Orm.CustomAttributes;
namespace Entity
{
[Serializable]
[Table(name="Student")]
public class StudentEntity
{
private string stuid;
private string stuno;
private string name;
private int sex;
private int age;
private string address;
private string telphone;
[Id(Name=”stuid”,Strategy = GenerationType.SEQUENCE)]
public string Stuid
{
get { return stuid; }
set { stuid = value; }
}
[Column(Name = "studentno")]
public string Stuno
{
get { return stuno; }
set { stuno = value; }
}
[Column(IsInsert = true)]
public string Name
{
get { return name; }
set { name = value; }
}
[Column(IsUpdate = true)]
public int Sex
{
get { return sex; }
set { sex = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string Telphone
{
get { return telphone; }
set { telphone = value; }
}
}
}
BLL层代码:
StudentBLL代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using DAL;
using Entity;
using System.Orm.DBTransaction;
namespace BLL
{
public class StudentBP
{
public List FindAll()
{