目录
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();
}
}
}
=》