服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - SqlServer与MongoDB结合使用NHibernate

SqlServer与MongoDB结合使用NHibernate

2020-05-09 16:08MongoDB教程网 MongoDB

这篇文章主要为大家详细介绍了SqlServer与MongoDB结合使用NHibernate的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了SqlServer与MongoDB结合使用NHibernate的代码,供大家参考,具体内容如下

Program.cs代码内容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
class Program
 {
   private const string SqlServerConnectionString =
     @"Data Source=.;Initial Catalog=SqlWithMongo;Persist Security Info=True;User ID=sa;Password=123456";
 
   private const string MongoConnectionString = "mongodb://localhost:27017";
   private const int NumberOfNodes = 1000;
 
   private static void Main(string[] args)
   {
     Console.WriteLine("Clearing database...");
     ClearDatabases();
     Initer.Init(SqlServerConnectionString, MongoConnectionString);
     Console.WriteLine("Completed");
 
     Console.WriteLine("Creating nodes...");
     //创建sqlserver的Node节点
     CreateNodes();
     Console.WriteLine("Completed");
 
     Console.WriteLine("Linking nodes...");
     long milliseconds1 = LinkSqlNodes(); //创建sqlserver的LinkNode节点
     Console.WriteLine("SQL : " + milliseconds1);
     long milliseconds2 = LinkMongoNodes(); //同时创建Node,LinkNode节点
     Console.WriteLine("Mongo : " + milliseconds2);
     Console.WriteLine("Completed");
 
     Console.WriteLine("Fetching nodes...");
     long milliseconds3 = FetchSqlNodes(); //取出sqlserver节点数据
     Console.WriteLine("SQL : " + milliseconds3);
     long milliseconds4 = FetchMongoNodes(); //取出Mongodb节点数据
     Console.WriteLine("Mongo : " + milliseconds4);
     Console.WriteLine("Completed");
 
     Console.ReadKey();
   }
 
 
   private static long FetchMongoNodes()
   {
     var stopwatch = new Stopwatch();
     stopwatch.Start();
 
     for (int i = 0; i < NumberOfNodes; i++)
     {
       using (var unitOfWork = new UnitOfWork())
       {
         var repository = new MongoNodeRepository(unitOfWork);
 
         MongoNode node = repository.GetById(i + 1);
         IReadOnlyList<NodeLink> links = node.Links;
       }
     }
     stopwatch.Stop();
     return stopwatch.ElapsedMilliseconds;
   }
 
 
   private static long FetchSqlNodes()
   {
     var stopwatch = new Stopwatch();
     stopwatch.Start();
 
     for (int i = 0; i < NumberOfNodes; i++)
     {
       using (var unitOfWork = new UnitOfWork())
       {
         var repository = new NodeRepository(unitOfWork);
 
         Node node = repository.GetById(i + 1);
         IReadOnlyList<Node> links = node.Links;
       }
     }
 
     stopwatch.Stop();
     return stopwatch.ElapsedMilliseconds;
   }
 
 
   private static long LinkSqlNodes()
   {
     var stopwatch = new Stopwatch();
     stopwatch.Start();
 
     using (var unitOfWork = new UnitOfWork())
     {
       var repository = new NodeRepository(unitOfWork);
 
       IList<Node> nodes = repository.GetAll();
       foreach (Node node1 in nodes)
       {
         foreach (Node node2 in nodes)
         {
           node1.AddLink(node2);
         }
       }
       unitOfWork.Commit();
     }
 
     stopwatch.Stop();
     return stopwatch.ElapsedMilliseconds;
   }
 
 
   private static long LinkMongoNodes()
   {
     var stopwatch = new Stopwatch();
     stopwatch.Start();
 
     using (var unitOfWork = new UnitOfWork())
     {
       var repository = new MongoNodeRepository(unitOfWork);
 
       IList<MongoNode> nodes = repository.GetAll();
       foreach (MongoNode node1 in nodes)
       {
         foreach (MongoNode node2 in nodes)
         {
           node1.AddLink(node2);
         }
       }
       unitOfWork.Commit();
     }
 
     stopwatch.Stop();
     return stopwatch.ElapsedMilliseconds;
   }
 
 
   private static void CreateNodes()
   {
     using (var unitOfWork = new UnitOfWork())
     {
       var repository = new NodeRepository(unitOfWork);
 
       for (int i = 0; i < NumberOfNodes; i++)
       {
         var node = new Node("Node " + (i + 1)); //实例化 构造函数初始化name
         repository.Save(node);
       }
 
       unitOfWork.Commit();
     }
 
     using (var unitOfWork = new UnitOfWork())
     {
       var repository = new MongoNodeRepository(unitOfWork);
 
       for (int i = 0; i < NumberOfNodes; i++)
       {
         var node = new MongoNode("Node " + (i + 1));
         repository.Save(node);
       }
 
       unitOfWork.Commit();
     }
   }
 
   //清空数据
   private static void ClearDatabases()
   {
     new MongoClient(MongoConnectionString)
       .GetDatabase("sqlWithMongo")
       .DropCollectionAsync("links")
       .Wait();
 
     string query = "DELETE FROM [dbo].[MongoNode];" +
             "DELETE FROM [dbo].[Node_Node];" +
             "DELETE FROM [dbo].[Node];" +
             "UPDATE [dbo].[Ids] SET [NextHigh] = 0";
 
     using (var connection = new SqlConnection(SqlServerConnectionString))
     {
       var command = new SqlCommand(query, connection)
       {
         CommandType = CommandType.Text
       };
 
       connection.Open();
       command.ExecuteNonQuery();
     }
   }
 }

相关辅助类代码如下:

?
1
2
3
4
5
6
7
8
9
10
public static class Initer
 {
   public static void Init(string sqlServerConnectionString, string mongoConnectionString)
   {
     //SqlServer初始化
     SessionFactory.Init(sqlServerConnectionString);
     //Mongodb初始化
     NodeLinkRepository.Init(mongoConnectionString);
   }
 }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static class SessionFactory //工厂
  {
    private static ISessionFactory _factory;
 
 
    internal static ISession OpenSession()
    {
      return _factory.OpenSession(new Interceptor());
    }
 
 
    internal static void Init(string connectionString)
    {
      _factory = BuildSessionFactory(connectionString);
    }
 
 
    private static ISessionFactory BuildSessionFactory(string connectionString)
    {
      //用编程的方式进行配置,让你能更好的理解,不需要编写复杂的映射文件,它能完全替换NHibernate的映射文件,让你在映射的时候能使用C#的强类型方式。
      FluentConfiguration configuration = Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString))
        .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
        .ExposeConfiguration(x =>
        {
          x.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[]
          {
            new EventListener()
          };
        });
 
      return configuration.BuildSessionFactory();
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
internal class NodeLinkRepository //仓库 Repository模式
  {
    private static IMongoCollection<NodeLinks> _collection;
 
 
    public IList<NodeLink> GetLinks(int nodeId)
    {
      NodeLinks links = _collection.Find(x => x.Id == nodeId).SingleOrDefaultAsync().Result;
       
      if (links == null)
        return new NodeLink[0];
 
      return links.Links;
    }
 
 
    public Task SaveLinks(int nodeId, IEnumerable<NodeLink> links)
    {
      var nodeLinks = new NodeLinks(nodeId, links);
      var updateOptions = new UpdateOptions
      {
        IsUpsert = true
      };
 
      return _collection.ReplaceOneAsync(x => x.Id == nodeId, nodeLinks, updateOptions);
    }
 
 
    internal static void Init(string connectionString)
    {
      var client = new MongoClient(connectionString);
      IMongoDatabase database = client.GetDatabase("sqlWithMongo");
      var collectionSettings = new MongoCollectionSettings
      {
        WriteConcern = new WriteConcern(1)
      };
      _collection = database.GetCollection<NodeLinks>("links", collectionSettings);
    }
 
 
    private class NodeLinks
    {
      public int Id { get; private set; }
      public List<NodeLink> Links { get; private set; }
 
 
      public NodeLinks(int nodeId, IEnumerable<NodeLink> links)
      {
        Id = nodeId;
        Links = new List<NodeLink>();
        Links.AddRange(links);
      }
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class NodeRepository
  {
    private readonly UnitOfWork _unitOfWork;
 
 
    public NodeRepository(UnitOfWork unitOfWork)
    {
      _unitOfWork = unitOfWork;
    }
 
 
    public Node GetById(int id)
    {
      return _unitOfWork.Get<Node>(id);
    }
 
 
    public IList<Node> GetAll()
    {
      return _unitOfWork.Query<Node>()
        .ToList();
    }
 
 
    public void Save(Node mongoNode)
    {
      _unitOfWork.SaveOrUpdate(mongoNode);
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MongoNodeRepository
  {
    private readonly UnitOfWork _unitOfWork;
 
 
    public MongoNodeRepository(UnitOfWork unitOfWork)
    {
      _unitOfWork = unitOfWork;
    }
 
 
    public MongoNode GetById(int id)
    {
      return _unitOfWork.Get<MongoNode>(id);
    }
 
 
    public void Save(MongoNode mongoNode)
    {
      _unitOfWork.SaveOrUpdate(mongoNode);
    }
 
 
    public IList<MongoNode> GetAll()
    {
      return _unitOfWork.Query<MongoNode>()
        .ToList();
    }
  }

模型层数据:
Node.cs,NodeMap.cs类代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Node
  {
    public virtual int Id { get; protected set; }
    public virtual string Name { get; protected set; }
 
    protected virtual ISet<Node> LinksInternal { get; set; }
    public virtual IReadOnlyList<Node> Links
    {
      get { return LinksInternal.ToList(); }
    }
 
 
    protected Node()
    {
      LinksInternal = new HashSet<Node>();
    }
 
 
    public Node(string name)
      : this()
    {
      Name = name;
    }
 
 
    public virtual void AddLink(Node node)
    {
      LinksInternal.Add(node);
      node.LinksInternal.Add(this);
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class NodeMap : ClassMap<Node> //FluentNHibernate.Mapping.ClasslikeMapBase<T>
  {
    public NodeMap()
    {
      Id(x => x.Id, "NodeId").GeneratedBy.HiLo("[dbo].[Ids]", "NextHigh", "10", "EntityName = 'Node'");
      Map(x => x.Name).Not.Nullable();
 
      HasManyToMany<Node>(Reveal.Member<Node>("LinksInternal"))
        .AsSet()
        .Table("Node_Node")
        .ParentKeyColumn("NodeId1")
        .ChildKeyColumn("NodeId2");
    }
  }

MongoNode.cs和MongoNodeMap.cs的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MongoNode
 {
   public virtual int Id { get; protected set; }
   public virtual string Name { get; protected set; }
 
   protected virtual HashSet<NodeLink> LinksInternal { get; set; }
   public virtual IReadOnlyList<NodeLink> Links
   {
     get { return LinksInternal.ToList(); }
   }
 
 
   protected MongoNode()
   {
     LinksInternal = new HashSet<NodeLink>();
   }
 
 
   public MongoNode(string name)
     : this()
   {
     Name = name;
   }
 
 
   public virtual void AddLink(MongoNode mongoNode)
   {
     LinksInternal.Add(new NodeLink(mongoNode.Id, mongoNode.Name));
     mongoNode.LinksInternal.Add(new NodeLink(Id, Name));
   }
 }
?
1
2
3
4
5
6
7
8
public class MongoNodeMap : ClassMap<MongoNode> //FluentNHibernate中的类继承
  {
    public MongoNodeMap()
    {
      Id(x => x.Id, "MongoNodeId").GeneratedBy.HiLo("[dbo].[Ids]", "NextHigh", "10", "EntityName = 'MongoNode'");
      Map(x => x.Name).Not.Nullable();
    }
  }

Utils层的类:
EventListener.cs内容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
internal class EventListener : IPostLoadEventListener //NHibernate.Event继承
  {
    public void OnPostLoad(PostLoadEvent ev)
    {
      var networkNode = ev.Entity as MongoNode;
 
      if (networkNode == null)
        return;
 
      var repository = new NodeLinkRepository();
      IList<NodeLink> linksFromMongo = repository.GetLinks(networkNode.Id);
 
      HashSet<NodeLink> links = (HashSet<NodeLink>)networkNode
        .GetType()
        .GetProperty("LinksInternal", BindingFlags.NonPublic | BindingFlags.Instance)
        .GetValue(networkNode);
      links.UnionWith(linksFromMongo);
    }
  }
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
internal class Interceptor : EmptyInterceptor //NHibernate中的类
 {
   public override void PostFlush(ICollection entities)
   {
     IEnumerable<MongoNode> nodes = entities.OfType<MongoNode>();
 
     if (!nodes.Any())
       return;
 
     var repository = new NodeLinkRepository();
     Task[] tasks = nodes.Select(x => repository.SaveLinks(x.Id, x.Links)).ToArray();
     Task.WaitAll(tasks);
   }
 }

UnitOfWork.cs代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class UnitOfWork : IDisposable
 {
   private readonly ISession _session;
   private readonly ITransaction _transaction;
   private bool _isAlive = true;
   private bool _isCommitted;
 
   public UnitOfWork()
   {
     _session = SessionFactory.OpenSession();
     _transaction = _session.BeginTransaction(IsolationLevel.ReadCommitted);
   }
 
 
   public void Dispose()
   {
     if (!_isAlive)
       return;
 
     _isAlive = false;
 
     try
     {
       if (_isCommitted)
       {
         _transaction.Commit();
       }
     }
     finally
     {
       _transaction.Dispose();
       _session.Dispose();
     }
   }
    
   public void Commit()
   {
     if (!_isAlive)
       return;
 
     _isCommitted = true;
   }
 
 
   internal T Get<T>(int id)
   {
     return _session.Get<T>(id);
   }
 
 
   internal void SaveOrUpdate<T>(T entity)
   {
     _session.SaveOrUpdate(entity);
   }
 
 
   internal IQueryable<T> Query<T>()
   {
     return _session.Query<T>();
   }
 }

Database.sql建表语句:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
CREATE DATABASE [SqlWithMongo]
GO
USE [SqlWithMongo]
GO
/****** 表 [dbo].[Ids] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Ids](
  [EntityName] [nvarchar](100) NOT NULL,
  [NextHigh] [int] NOT NULL,
 CONSTRAINT [PK_Ids] PRIMARY KEY CLUSTERED 
(
  [EntityName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
/****** 表 [dbo].[MongoNode] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MongoNode](
  [MongoNodeId] [int] NOT NULL,
  [Name] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_MongoNode] PRIMARY KEY CLUSTERED 
(
  [MongoNodeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
/****** 表 [dbo].[Node] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Node](
  [NodeId] [int] NOT NULL,
  [Name] [nvarchar](100) NOT NULL,
 CONSTRAINT [PK_NetworkNode] PRIMARY KEY CLUSTERED 
(
  [NodeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
/****** 表 [dbo].[Node_Node] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Node_Node](
  [NodeId1] [int] NOT NULL,
  [NodeId2] [int] NOT NULL,
 CONSTRAINT [PK_NetworkNode_NetworkNode] PRIMARY KEY CLUSTERED 
(
  [NodeId1] ASC,
  [NodeId2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO
ALTER TABLE [dbo].[Node_Node] WITH CHECK ADD CONSTRAINT [FK_NetworkNode_NetworkNode_NetworkNode] FOREIGN KEY([NodeId1])
REFERENCES [dbo].[Node] ([NodeId])
GO
ALTER TABLE [dbo].[Node_Node] CHECK CONSTRAINT [FK_NetworkNode_NetworkNode_NetworkNode]
GO
ALTER TABLE [dbo].[Node_Node] WITH CHECK ADD CONSTRAINT [FK_NetworkNode_NetworkNode_NetworkNode1] FOREIGN KEY([NodeId2])
REFERENCES [dbo].[Node] ([NodeId])
GO
ALTER TABLE [dbo].[Node_Node] CHECK CONSTRAINT [FK_NetworkNode_NetworkNode_NetworkNode1]
GO
 
INSERT dbo.Ids (EntityName, NextHigh)
VALUES ('MongoNode', 0)
INSERT dbo.Ids (EntityName, NextHigh)
VALUES ('Node', 0)

结果如图:

SqlServer与MongoDB结合使用NHibernate

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐
  • MongoDBmongodb数据库基础知识之连表查询

    mongodb数据库基础知识之连表查询

    这篇文章主要给大家介绍了关于mongodb数据库基础知识之连表查询的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用mongodb具有一定的参...

    ZJW02155642020-05-22
  • MongoDBWindows下MongoDB配置用户权限实例

    Windows下MongoDB配置用户权限实例

    这篇文章主要介绍了Windows下MongoDB配置用户权限实例,本文实现需要输入用户名、密码才可以访问MongoDB数据库,需要的朋友可以参考下 ...

    MongoDB教程网3082020-04-29
  • MongoDB在mac系统下安装与配置mongoDB数据库

    在mac系统下安装与配置mongoDB数据库

    这篇文章主要介绍了在mac系统下安装与配置mongoDB数据库的操作步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪...

    CXYhh1219312021-11-14
  • MongoDBMongoDB系列教程(五):mongo语法和mysql语法对比学习

    MongoDB系列教程(五):mongo语法和mysql语法对比学习

    这篇文章主要介绍了MongoDB系列教程(五):mongo语法和mysql语法对比学习,本文对熟悉Mysql数据库的同学来说帮助很大,用对比的方式可以快速学习到MongoDB的命...

    MongoDB教程网3252020-05-01
  • MongoDBMongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    MongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    这篇文章主要给大家介绍了关于MongoDB查询之高级操作(多条件查询、正则匹配查询等)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者...

    w田翔3872020-12-19
  • MongoDBMongoDB的索引

    MongoDB的索引

    数据库中的索引就是用来提高查询操作的性能,但是会影响插入、更新和删除的效率,因为数据库不仅要执行这些操作,还要负责索引的更新 ...

    MongoDB教程网2532020-05-12
  • MongoDBMongoDB多条件模糊查询示例代码

    MongoDB多条件模糊查询示例代码

    这篇文章主要给大家介绍了关于MongoDB多条件模糊查询的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用MongoDB具有一定的参考学习价值...

    浅夏晴空5902020-05-25
  • MongoDBMongodb索引的优化

    Mongodb索引的优化

    MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。接下来通过本文给大家介绍Mongodb索引的优化,本文介绍的非常详细,具有参考借鉴价值,感...

    MRR3252020-05-05