PhotonServer伺服器端(二)
阿新 • • 發佈:2018-11-08
目錄
7.nhibernate程式包的引入(我上傳的資源裡面有此版本的nhibernate程式包)
13.利用NHibernate進行更新、刪除、通過ID查詢的操作
7.nhibernate程式包的引入(我上傳的資源裡面有此版本的nhibernate程式包)
8.nhibernate資料庫連線配置
<?xml version="1.0" encoding="utf-8" ?> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property> <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property> <property name="connection.connection_string">Server=localhost;Database=my_schema;UserId=root;Password=root</property> <property name="show_sql">true</property> </session-factory> </hibernate-configuration>
9.進行類和表的對映
新建兩個資料夾Mappings,Model。在Mappings下面新建xml檔案“User.hbm.xml”,並將其屬性中的生成操作設為嵌入的資源。在Model資料夾下新建類User。
namespace Lijiang.Model { class User { public virtual int Id { get; set; } public virtual string Username { get; set; } public virtual string Password { get; set; } } }
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Lijiang"
namespace="Lijiang.Model">
<class name="User" table="users">
<id name="Id" column="id" type="Int32">
<generator class="native" />
</id>
<property name="Username" column="username" type="String" />
<property name="Password" column="password" type="String" />
</class>
</hibernate-mapping>
10.建立會話session進行新增操作
using System;
using NHibernate;
using NHibernate.Cfg;
using Lijiang.Model;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Lijiang");//解析對映檔案 User.hbm.xml...
ISessionFactory sessionFactory = null;
ISession session = null;
try
{
sessionFactory = configuration.BuildSessionFactory();
session = sessionFactory.OpenSession();//開啟一個跟資料庫的回話
User user = new User() { Username = "qqqq", Password = "2222" };
session.Save(user);
}
catch(Exception e)
{
Console.WriteLine(e);
}finally
{
if(session !=null)
{
session.Close();
}
if(sessionFactory !=null)
{
sessionFactory.Close();
}
}
Console.ReadKey();
}
}
}
=》
11.利用NHibernate進行事務操作
using System;
using NHibernate;
using NHibernate.Cfg;
using Lijiang.Model;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Lijiang");//解析對映檔案 User.hbm.xml...
ISessionFactory sessionFactory = null;
ISession session = null;
ITransaction transaction = null;
try
{
sessionFactory = configuration.BuildSessionFactory();
session = sessionFactory.OpenSession();//開啟一個跟資料庫的回話
transaction = session.BeginTransaction();//事務(在連續的幾個操作中,只要有一個操作失敗,則所有的操作都會失敗!哪怕之前的幾個操作是成功的)
User user1 = new User() { Username = "dfhsfahfgdfhrtadgds123", Password = "5475" };
User user2 = new User() { Username = "dfhsfahfgdfhrtadgds1234", Password = "5475" };
//下面這種方式是執行不成功的。雖然可以新增user1,但是user2的使用者名稱和user1重複,所以user2會操作失敗,所以全過程的操作是不會成功的
//User user1 = new User() { Username = "wwww", Password = "1212" };
//User user2 = new User() { Username = "wwww", Password = "1212" };
session.Save(user1);
session.Save(user2);
transaction.Commit();
}
catch(Exception e)
{
Console.WriteLine(e);
}finally
{
if(transaction !=null)
{
transaction.Dispose();
}
if(session !=null)
{
session.Close();
}
if(sessionFactory !=null)
{
sessionFactory.Close();
}
}
Console.ReadKey();
}
}
}
=》
12.建立NHibernateHelper管理會話工廠
- IUserManager.cs:
using Lijiang.Model;
using System.Collections.Generic;
namespace Lijiang.Manager
{
interface IUserManager
{
void Add(User user);
void Update(User user);
void Remove(User user);
User GetById(int id);
User GetByUsername(string username);
ICollection<User> GetAllUsers();
}
}
- UserManager.cs:
using System;
using System.Collections.Generic;
using Lijiang.Model;
using NHibernate;
namespace Lijiang.Manager
{
class UserManager : IUserManager
{
public void Add(User user)
{
//ISession session = NHibernateHelper.OpenSession();
//session.Save(user);
//session.Close();如果使用下面的using,就不用寫session.Close()來釋放session了,因為using會自動釋放。下面的巢狀是先釋放transacion,再釋放session。
using(ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction=session .BeginTransaction())
{
session.Save(user);
transaction.Commit();
}
}
}
public ICollection<User> GetAllUsers()
{
throw new NotImplementedException();
}
public User GetById(int id)
{
throw new NotImplementedException();
}
public User GetByUsername(string username)
{
throw new NotImplementedException();
}
public void Remove(User user)
{
throw new NotImplementedException();
}
public void Update(User user)
{
throw new NotImplementedException();
}
}
}
- NHibernateHelper.cs:
using NHibernate;
using NHibernate.Cfg;
namespace Lijiang
{
class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if(_sessionFactory ==null)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Lijiang");//解析對映檔案 User.hbm.xml...
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
- Program.cs:
using Lijiang.Model;
using Lijiang.Manager;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
User user = new User() { Username = "eeee", Password = "3333" };
IUserManager userManager = new UserManager();
userManager.Add(user);
Console.ReadKey();
}
}
}
=》
13.利用NHibernate進行更新、刪除、通過ID查詢的操作
using System;
using System.Collections.Generic;
using Lijiang.Model;
using NHibernate;
namespace Lijiang.Manager
{
class UserManager : IUserManager
{
public void Add(User user)
{
//ISession session = NHibernateHelper.OpenSession();
//session.Save(user);
//session.Close();如果使用下面的using,就不用寫session.Close()來釋放session了,因為using會自動釋放。下面的巢狀是先釋放transacion,再釋放session。
using(ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction=session .BeginTransaction())
{
session.Save(user);
transaction.Commit();
}
}
}
public ICollection<User> GetAllUsers()
{
throw new NotImplementedException();
}
public User GetById(int id)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
User user = session.Get<User>(id);
transaction.Commit();
return user;
}
}
}
public User GetByUsername(string username)
{
throw new NotImplementedException();
}
public void Remove(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete(user);//根據主鍵來更新,所以需保證user裡面主鍵有值
transaction.Commit();
}
}
}
public void Update(User user)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(user);//根據主鍵來更新,所以需保證user裡面主鍵有值
transaction.Commit();
}
}
}
}
}
using Lijiang.Model;
using Lijiang.Manager;
using System;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
User user1 = new User() { Username = "eeeeEEE", Password = "3333444" };
User user2 = new User() { Id=5 };
IUserManager userManager = new UserManager();
userManager.Add(user1);
userManager.Remove(user2);
User user3 = userManager.GetById(2);
Console.WriteLine(user3.Username);
Console.WriteLine(user3.Password);
Console.ReadKey();
}
}
}
=>
14.通過CreateCriteria進行復雜查詢
UserManager:(記得引入名稱空間 using NHibernate.Criterion;)
public User GetByUsername(string username)
{
using (ISession session = NHibernateHelper.OpenSession())
{
User user = session.CreateCriteria(typeof(User)).Add(Restrictions.Eq("Username", username)).UniqueResult<User>();
return user;
}
}
using Lijiang.Model;
using Lijiang.Manager;
using System;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
IUserManager userManager = new UserManager();
User user = userManager.GetByUsername("eeee");
Console.WriteLine(user.Username);
Console.WriteLine(user.Password);
Console.ReadKey();
}
}
}
=>
15.多個查詢條件的新增和得到查詢的集合結果
- 查詢所有記錄
public ICollection<User> GetAllUsers()
{
using (ISession session = NHibernateHelper.OpenSession())
{
IList<User> users = session.CreateCriteria(typeof(User)).List<User>();
return users;
}
}
using Lijiang.Model;
using Lijiang.Manager;
using System;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
IUserManager userManager = new UserManager();
ICollection<User> users = userManager.GetAllUsers();
foreach (User u in users)
{
Console.WriteLine(u.Username + " " + u.Password);
}
Console.ReadKey();
}
}
}
=》
- 驗證使用者名稱和密碼是否輸入正確
using Lijiang.Model;
using System.Collections.Generic;
namespace Lijiang.Manager
{
interface IUserManager
{
void Add(User user);
void Update(User user);
void Remove(User user);
User GetById(int id);
User GetByUsername(string username);
ICollection<User> GetAllUsers();
bool VerifyUser(string username, string password);//驗證使用者名稱和密碼是否輸入正確
}
}
UserManager.cs:
public bool VerifyUser(string username,string password)
{
using (ISession session = NHibernateHelper.OpenSession())
{
User user = session.CreateCriteria(typeof(User)).Add(Restrictions.Eq("Username", username)).Add(Restrictions.Eq("Password", password)).UniqueResult<User>();
if (user == null)
{
return false;
}
return true;
}
}
using Lijiang.Manager;
using System;
namespace Lijiang
{
class Program
{
static void Main(string[] args)
{
IUserManager userManager = new UserManager();
Console.WriteLine(userManager.VerifyUser("eeee", "3333"));//存在,返回true
Console.WriteLine(userManager.VerifyUser("eeeem", "3333"));//不存在,返回false
Console.ReadKey();
}
}
}
=》