1、附:利用MVC+NHibernate+Jquery+JqueryUI这些技术可以做出一个比较好的前台+后台网站。下面是本人对这些技术的笔记,作为私人年底小结吧。呵呵
好久没写文章了,感觉下不了笔吐不出字来。也许想说的太多,也许压根就不会写了。好吧,省时间,下面就以新增用户功能为例吧。
2、练习用例:
相关DLL:
3、要点:
(1)NHibernate作用
(2)NHibernate配置
(3)建用户表、实体以及建立相应的映射
(4)定义数据访问层接口并实现
(5)定义业务层接口并实现
(6)控制器Controller实现
(7)视图层展现
(1)NHibernate作用:
NHibernate是一个面向.NET环境的对象/关系数据库映射工具。对象/关系数据库映射(object/relational mapping,ORM)这个术语表示一种技术,用来把对象模型表示的对象映射到基于SQL的关系模型数据结构中去。
参阅百度百科:NHibernate。
(2)NHibernate配置:
1、配置文件:
2、不同的数据库,NHibernate的配置稍有区别。这里练习用的数据库是MSSQL,所以我们的配置如下:
<?xml version="1.0" encoding="utf-8"?>
<!--
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.OracleClient.dll provider for Oracle from MS -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=WADE-PC\SQLEXPRESS;initial catalog=TestDB;Integrated Security=SSPI</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property> <property name="query.substitutions">true , false , yes 'Y', no 'N'</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="hbm2ddl.keywords">none</property> </session-factory>
</hibernate-configuration>
在此附上Oracle的配置以便自己以后用:
<!-- This is the System.Data.OracleClient.dll provider for Oracle from MS -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
<property name="connection.connection_string">
<!--Data Source=SDCGS;user=SDCGS;password=SDCGS2013;Pooling=true;Min Pool Size=;Max Pool Size=-->
Data Source=DMP;user=website;password=website;Pooling=true;Min Pool Size=;Max Pool Size= </property>
<property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
<property name="query.substitutions">true , false , yes 'Y', no 'N'</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name="hbm2ddl.keywords">none</property> </session-factory>
</hibernate-configuration>
(3)建用户表、实体以及建立相应的映射:
①用户表:
②实体类:
注意:1、Serializable——表示可序列化与反序列化。Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。可序列化类的所有子类型本身都是可序列化的。序列化接口没有方法或字段,仅用于标识可序列化的语义。
2、DataContract——数据契约。服务契约定义了远程访问对象和可供调用的方法,数据契约则是服务端和客户端之间要传送的自定义数据类型。一旦声明一个类型为DataContract,那么该类型就可以被序列化在服务端和客户端之间传送
③实体映射:
文件——
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Entity" namespace="Entity">
<class name="UserInfo" table="UserInfo">
<id name="UserId" column="UserId" type="int" unsaved-value="0">
<generator class="native" />
</id>
<bag name="UserRoleList" inverse="true" lazy="true" >
<key column="UserId" />
<one-to-many class="UsersInRoles" />
</bag>
<property column="UserName" type="String" name="UserName" />
<property column="PassWord" type="String" name="PassWord" />
</class>
</hibernate-mapping>
注意:UserInfo.hbm.xml需要设置”属性—复制到输出目录—始终复制”,以及“属性—生成操作—嵌入的资源“。要不然会报错找不到映射文件。
(4)定义数据访问层接口并实现:
①定义数据访问层接口
定义接口代码:(新增用户对应的方法:Save())
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity;
namespace IDao
{
public interface IUserInfoDao
{ UserInfo Get(int userId);
IList<UserInfo> LoadAll();
object Save(UserInfo entity);
void Update(UserInfo entity);
void Delete(UserInfo entity);
UserInfo Load(object id);
IList<UserInfo> GetListBySql(string sql);
IList<UserInfo> GetListByHQL(string HQL);
IList<Object[]> GetObjectsByHQL(string HQL);
UserInfo GetUserInfoByNameAndPwd(string userName, string pwd);
}
}
②数据访问层接口实现:
实现代码:(新增用户对应的方法:Save())
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IDao;
using NHibernate;
using Entity; namespace Dao
{
public class UserInfoDao : IUserInfoDao
{
/// <summary>
/// 添加
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public object Save(UserInfo entity)
{
ISession session = NHibernateHelper.getSession();
try
{
var id = session.Save(entity);
session.Flush();
return id;
}
finally
{
session.Close();
}
}
}
}
(5)定义业务层接口并实现
①定义业务层接口
定义代码:(对应的方法Save())
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entity; namespace IService
{
public interface IUserInfoService
{
UserInfo getEntityById(int Id);
IList<UserInfo> getAllEntitys();
int AddEntity(UserInfo ar);
void Delete(UserInfo ar);
void UpDate(UserInfo ar);
IList<UserInfo> GetListBySql(string sql);
IList<UserInfo> GetListByHQL(string HQL);
IList<Object[]> GetObjectsByHQL(string HQL); UserInfo GetUserInfoByNameAndPwd(string userName, string pwd);
}
}
②业务层接口并实现
实现代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IService;
using IDao;
using Entity;
using Dao; namespace Service
{
public class UserInfoService : IUserInfoService
{
private IUserInfoDao dao = new UserInfoDao(); public int AddEntity(UserInfo ar)
{
return int.Parse(dao.Save(ar).ToString());
} }
}
(6)控制器Controller实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using BLUS.Filters;
using BLUS.Models;
using Service;
using IService;
using Entity; namespace BLUS.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
IUsersInRolesService sr = new UsersInRolesService();
UserInfo user = new UserInfo();
user.UserName = model.UserName;
user.PassWord = model.Password;
int userId = service.AddEntity(user); UsersInRoles userRole = new UsersInRoles();
userRole.UserId = user;
Entity.Roles rl = new Entity.Roles();
rl.RoleId = 2;
rl.RoleName = "普通用户";
userRole.RoleId= rl;
sr.AddEntity(userRole);
UserInfo userInfoLogin = service.getEntityById(userId);
Session["userInfoLogin"] = null;
Session["userInfoLogin"] = userInfoLogin;
return RedirectToAction("Index", "Home");
}
catch (Exception e)
{
ModelState.AddModelError("", e);
}
} // If we got this far, something failed, redisplay form
return View(model);
}
}
}
(7)视图层展现:(这里可以省去,视图层的展现)
小结:MVC+NHibernate+Jquery+JqueryUI,结合这些技术可以建立一个功能和性能一般的网站。我也是第一次运用NHibernate,有很多地方都不怎么理解。有待今后继续研究。