1、支持ORM,最基础的两个信息是表的信息和字段信息。这两个信息,如果用Attribute 来辅助,代码更简洁和可读性更好。可以把属性名当做真实字段名,也可以将特性里的属性当成真实姓名,再加上字段标题(可以当成注释)、必填字段、是否为主键、显示格式等等,如果没有Attribute ,类、属性的辅助信息必须用其他信息来描述,非常麻烦。

uses
SysUtils, RTTI, TypInfo,Types;

type
Table = class(TCustomAttribute)
private
FName: string;
FTitle: string;
published

public
constructor Create(ATableName, ATitle: string);
property Name: string read FName write FName;
property Title: string read FTitle write FTitle;
end;

FieldInfo = class(TCustomAttribute)
private
FFieldName: string;
FTitle: string;
published
public
constructor Create(AFieldName, ATitle: string);
//字段名
property FieldName: string read FFieldName write FFieldName;
//标题
property Title: string read FTitle write FTitle;
end;

2、有了这两个Attribute,我们必须创建一个解析属性和Attribute的类,并且能解析Insert、update、delete、select等SQL语句。我们姑且叫 TStorable。这个类可以根据需要扩展你所想要的东西。目前只实现了Insert方法,其他的方法,留给勤奋的人去遐想。

TStorable = class

public
//插入SQL语句
function Insert: string;
//获取字段标题
function GetFieldTitle(const AFieldName: string): string;
//设置
//function SetAttributeValue(const PropName, AttributeValue: string): Boolean;
end;

function TStorable.GetFieldTitle(const AFieldName: string): string;
var
Context: TRttiContext;
typ: TRttiType;
A1, A2: TCustomAttribute;
Prop: TRttiProperty;
begin
Context := TRttiContext.Create;
try
typ := Context.GetType(ClassType);
for Prop in typ.GetProperties do
begin
for A2 in Prop.GetAttributes do
begin
if (A2 is FieldInfo) and SameText(FieldInfo(A2).FieldName, AFieldName) then
begin
Result := FieldInfo(A2).Title;
Break;
end;
end;
end;
finally
Context.Free;
end;
end;

function TStorable.Insert: string;
var
Context:TRttiContext;
Prop:TRttiProperty;
typ:TRttiType;
A1,A2:TCustomAttribute;
Sqls,Fields,Values,Value:string;

begin
Context := TRttiContext.Create;
try
Sqls := '';
Fields := '';
Values := '';

typ := Context.GetType(ClassType);
for A1 in typ.GetAttributes do
begin
if A1 is Table then
begin
Sqls := 'Insert Into '+Table(A1).Name; //获取Insert表名
for Prop in typ.GetProperties do
begin
for A2 in Prop.GetAttributes do
begin
if A2 is FieldInfo then //AHa
begin
Fields := Fields + ','+ FieldInfo(A2).FieldName ;
// the value of the attribute
Value := Prop.GetValue(Self).ToString;
//根据数据类型对属性值加以编辑
case Prop.GetValue(Self).Kind of
tkString, tkChar, tkWChar, tkWString, tkUString:
Value := QuotedStr(Value);
tkInteger, tkInt64, tkFloat:
Value := Value;
else
Value := QuotedStr(Value);
end;
Values := Values + ',' + Value ;
end; //for A2 in Prop.GetAttributes
end;
end; //enf of for Prop
Delete(Fields,1,1);
Delete(Values,1,1);

Sqls := Sqls + ' (' + Fields + ') VALUES (' + Values + ');';

Result := Sqls;

end; //if A1 is Table then
end; //for A1 in typ.GetAttributes do

finally
Context.Free;
end;
end;

constructor FieldInfo.Create(AFieldName, ATitle: string);
begin
FFieldName := AFieldName;
FTitle := ATitle;
end;

3、有了上面的解析类和SQL基础,我们必须创建一个实体类。属性名是否为中文,可以有不同的说法。偶目前栖身在一个医疗行业公司,医疗专业英语术语又臭又长,奥巴马未必能拼写出几个术语。如果用属性名用中文描述,将其真实的字段名放在Attribute 里,或许更能提高程序的可读性和维护性。

unit uContact;

interface
uses SysUtils,uAttribute;

type
[Table('CONTACTS','联系人信息')]
TContact = class(TStorable)
private
FName: string;
FAge: integer;
F电话: string;
published
public
[FieldInfo('NAME','名称')]
property Name: string read FName write FName;
[FieldInfo('AGE','年龄')]
property Age: integer read FAge write FAge;
[FieldInfo('电话','联系电话')]
property 电话:string read F电话 write F电话; //尝试一下中文字段名,习惯就好
end;
implementation

end.

4、调用示例就很简单了:

procedure TForm4.btn1Click(Sender: TObject);
var
Contact:TContact;
begin
Contact := TContact.Create;
Contact.Age := 32;
Contact.Name := 'TinTin';
Contact.电话 := '135*****918';//你还会记得918的屈辱吗?

ShowMessage(Contact.Insert);

ShowMessage(Contact.GetFieldTitle('Age'));
Contact.Free;
end;

5、综述:

ORM确实在对象映射上使用起来非常方便,但并非万能,如果过分依赖于ORM,不仅不能了解数据库表与业务的关系,而且还容易写出低效的SQL查询语句。Update语句,须谨记,字段值变化才去更改,否则,会增加数据库的数据不一致风险及其增加数据库日志开销。Delete语句,配合有关键字信息的Attribute,必要时候,还要校验是否影响单条或多条记录。

这只是一个简单的例子,离真正的生产力还差一步,为了执行SQL语句,你可以在TStorable 实现数据集的读写,然后才调用执行SQL语句。

Delphi2010 RTTI + Attribute 简单实现ORM实例的更多相关文章

  1. D2010 RTTI + Attribute 简单实现ORM

    还记得David I 今年四月来盛大时,被问及“反射机制能再做得好一点吗?我们想放弃RTTI”,David I 回答“这的确是需要考虑的地方,当然RTTI我们不会放弃的”.(这个白胡子的老哥哥还真很可 ...

  2. 实现简单的ORM

    介绍 本篇将介绍实现简单的ORM,即:对数据表的通用操作:增.删.改.查 数据访问层 数据访问层类图 类说明: 1.DbProvider(供应):为数据操作提供基本对象,如:连接.操作对象.事务... ...

  3. C#基础笔记---浅谈XML读取以及简单的ORM实现

    背景: 在开发ASP.NETMVC4 项目中,虽然web.config配置满足了大部分需求,不过对于某些特定业务,我们有时候需要添加新的配置文件来记录配置信息,那么XML文件配置无疑是我们选择的一个方 ...

  4. C#基础---浅谈XML读取以及简单的ORM实现

    背景: 在开发ASP.NETMVC4 项目中,虽然web.config配置满足了大部分需求,不过对于某些特定业务,我们有时候需要添加新的配置文件来记录配置信息,那么XML文件配置无疑是我们选择的一个方 ...

  5. 审核流(3)低调奢华,简单不凡,实例演示-SNF.WorkFlow--SNF快速开发平台3.1

    下面我们就从什么都没有,结合审核流进行演示实例.从无到有如何快速完美的实现,然而如此简单.低调而奢华,简单而不凡. 从只有数据表通过SNF.CodeGenerator代码生成器快速生成单据并与审核流进 ...

  6. 一个简单的ORM制作(SQL帮助类)

    一个简单的ORM制作大概需要以下几个类: SQL执行类 CURD操作类 其他酱油类 先从SQL执行类说起,可能会涉及数据库的迁移等问题,所以需要定义一个接口以方便迁移到其他数据库, 事务没提供命名,若 ...

  7. 初学redux笔记,及一个最简单的redux实例

    categories: 笔记 tags: react redux 前端框架 把初学redux的一些笔记写了下来 分享一个入学redux很合适的demo, 用redux实现计数器 这是从阮一峰老师git ...

  8. HTML与CSS简单页面效果实例

    本篇博客实现一个HTML与CSS简单页面效果实例 index.html <!DOCTYPE html> <html> <head> <meta charset ...

  9. Java Tread多线程(0)一个简单的多线程实例

    作者 : 卿笃军 原文地址:http://blog.csdn.net/qingdujun/article/details/39341887 本文演示,一个简单的多线程实例,并简单分析一下线程. 编程多 ...

随机推荐

  1. mysqlbinlog 查看mysql bin 日志 mysqlbinlog: unknown variable 'default-character-set=utf8'

    mysqlbinlog  mysql-bin.000036 | less 查询包含几个字段的语句: mysqlbinlog mysql-bin.000036| egrep '(201103061000 ...

  2. oracle任务job

    1)创建测试表 1 create table test1(a date); 2)创建存储过程 1 2 3 4 5 create or replace procedure myproc as begin ...

  3. django startproject xxx:报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 13: ordinal not in range(128)

    django startproject xxx:报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 13: o ...

  4. Web前端开发规范文档你需要知道的事

    Web前端开发规范文档你需要知道的事 规范目的 为提高团队协作效率, 便于后台人员添加功能及前端后期优化维护, 输出高质量的文档, 特制订此文档. 本规范文档一经确认, 前端开发人员必须按本文档规范进 ...

  5. 《剑指offer》写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

    弱菜刷题还是刷中文题好了,没必要和英文过不去,现在的重点是基本代码能力的恢复. [题目] 剑指offer 写一个函数,求两个整数之和,要求在函数体内不得使用+.-.*./四则运算符号. [思路] 直觉 ...

  6. .NetCore中使用ExceptionLess记录Polly中的操作异常日志

    结合上一篇文章我写了一个demo测试下 重试2次 _polly.PollyRetry<Exception>(()=>_demoQuery.GetTestAOPAsync(), ); ...

  7. hdu 2519 求组合数

    求组合数 如果求C5 3 就是5*4*3/3*2*1 也就是(5/3)*(4/2)*(3/1) Sample Input5 //T3 2 //C3 25 34 43 68 0 Sample Outpu ...

  8. html屏幕旋转事件监听

    近期做微信服务号开发,在做图片展示的时候需要横竖屏的检测实现图片大小不同的展示. 添加屏幕旋转事件侦听,可随时发现屏幕旋转状态(左旋.右旋还是没旋). 摘自:http://bbs.phonegap10 ...

  9. CSS------如何让div中的div处于右下角

    如图: 代码: <div style="width:300px;height:300px"> <div style="position:absolute ...

  10. HDU4267 树状数组

    题意描述: 给定一个数组,有两种操作: 操作一:a b k c 对于区间a~b之间的元素如果下标满足(i-a)%k=0则给元素i加上c 操作二:a          查询下标为a的元素当前值 解题思路 ...