大家好,又见面了,我是你们的朋友全栈君。
通过第一篇的介绍,相信大家也对Db4o有一定的了解,接下来就详细说一下有关查询的话题。
Db4o原生支持3中查询模式:
- Query-By-Example: 简称 QBE ,根据模板类进行匹配查询,这是最简单的一种模式
- Native Query: 简称 NQ ,Db4o推荐的查询模式
- The SODA API :这是Db4o底层查询API ,官网文档解释,此API提供向后的兼容性,适用于动态生成的查询
准备测试数据
下面给出一个职工类
/// <summary>
/// 职工
/// </summary>
class Employee
{
/// <summary>
/// 姓名
/// </summary>
string _name;
public string Name
{
set { _name = value; }
get { return _name; }
}
/// <summary>
/// 职位
/// </summary>
public Position Position { get; set; }
public override string ToString()
{
return string.Format("姓名:{0},职位:{1}",this.Name,this.Position.PositionName);
}
}
/// <summary>
/// 职位
/// </summary>
class Position
{
/// <summary>
/// 职称
/// </summary>
public string PositionName { get; set; }
}
填充测试数据
static List<Employee> GetEmployee()
{
List<Employee> _Employees = new List<Employee>();
Employee _Employee = new Employee { Name = "Sunth", Position = new Position { PositionName = "CEO" } };
_Employees.Add(_Employee);
_Employee = new Employee { Name = "Jerry", Position = new Position { PositionName = "CTO" } };
_Employees.Add(_Employee);
_Employee = new Employee { Name = "Tom", Position = new Position { PositionName = "COO" } };
_Employees.Add(_Employee);
return _Employees;
}
Query-By-Example
static void Main(string[] args)
{
string DbPath = "Pilot.yap";
if (File.Exists(DbPath))
File.Delete(DbPath);
using (IObjectContainer Container = Db4oEmbedded.OpenFile(DbPath))
{
//对数据库进行初始化,并存入测试数据
var Query = GetEmployee();
Query.ForEach
(
(a) => { Container.Store(a); }
);
//查询一个叫做Sunth的职工
Employee _Employee = new Employee();
_Employee.Name = "Sunth";
IObjectSet Result = Container.QueryByExample(_Employee);
//打印结果
PrintResult(Result);
}
Console.ReadKey();
}
NativeQuery
static void Main(string[] args)
{
string DbPath = "Pilot.yap";
if (File.Exists(DbPath))
File.Delete(DbPath);
using (IObjectContainer Container = Db4oEmbedded.OpenFile(DbPath))
{
//对数据库进行初始化,并存入测试数据
var Query = GetEmployee();
Query.ForEach
(
(a) => { Container.Store(a); }
);
//查询一个叫做Sunth的职工
Employee _Employee = new Employee();
var Result = Container.Query<Employee>
(
delegate(Employee employee)
{
return employee.Name == "Sunth";
}
);
//打印结果
PrintResult(Result);
}
Console.ReadKey();
}
The SODA API
static void Main(string[] args)
{
string DbPath = "Pilot.yap";
if (File.Exists(DbPath))
File.Delete(DbPath);
using (IObjectContainer Container = Db4oEmbedded.OpenFile(DbPath))
{
//对数据库进行初始化,并存入测试数据
var Query = GetEmployee();
Query.ForEach
(
(a) => { Container.Store(a); }
);
//查询一个叫做Sunth的职工
IQuery _IQuery = Container.Query();
//强制约束Employee类型
_IQuery.Constrain(typeof(Employee));
//注意此“_name”为字段名称,非属性名称
_IQuery.Descend("_name").Constrain("Sunth");
//执行查询
IObjectSet Result = _IQuery.Execute();
//打印结果
PrintResult(Result);
}
Console.ReadKey();
}
结束语
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/162575.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...