C#框架NHibernate的学习

        今天对C#中的框架NHibernate进行了一番学习,与Java中的Hibernate十分类似。

        我这里只介绍一下简单的使用,通过数据库进行语句的查询,然后把数据显示在界面上。

        首先是将NHibernate的包导入项目中,在Java中有Maven来解决,在c#中通过Visual studio的NuGet可以解决,点击工具—>NuGet包管理器—>管理解决方案的NuGet包,然后在浏览中输入NHibernate,查找到之后安装即可:

        待以上成功之后,我们来按照项目基本要求建立文件夹,首先建立一个Config文件夹,里面编写NHibernate的配置文件,配置文件中的具体信息我就不做过多描述,跟Java中Hibernate差不多,具体各个节点的解释,网上一大堆,我这里只说一点,<mapping assembly="">这里面填写自的项目命名空间,这是我在使用中踩过得坑,配置文件代码如下:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.connection_string">填写具体的连接数据库的信息</property>
        <property name="adonet.batch_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">NHibernate.Dialect.MsSql2008Dialect(我这里使用的selserver需要这样填写)</property>
        <property name="query.substitutions">true 1,false 0,yes 'YES',no 'N'</property>
        <mapping assembly="NHibernateTest" />
</hibernate-configuration>

        接着建立Controller、Service、Impl、Mapper、Entity、Utile、Views文件夹,在Controller文件夹中建立UserController类,代码如下:

public class UserController
{
    UserInfoService userInfoService = new UserInfoServiceImpl();

    public IList<UserInfo> GetUser(string name)
    {
        return userInfoService.GetUser(name);
    }
}

        在Service文件夹中建立UserInfoService类,代码如下:

public interface UserInfoService
{
    IList<UserInfo> GetUser(string name);
}

        在Impl文件夹中建立UserInfoServiceImpl.cs类,代码如下:

private class UserInfoServiceImpl:UserInfoService
{
    UserInfoMapper userInfoMapper = new UserInfoMapper();
    public IList<UserInfo> GetUser(string name)
    {
        return userInfoMapper.GetUser(name);
    }
}

        在Entity文件夹中建立UserInfo类,代码如下:

public class UserInfo
{
    private int id;

    private string name;

    private string sex;

    private int age;

    public virtual int Id { get => id;set => id =value;}
    public virtual string Name {get => name;set => name = value;}
    public virtual string Sex {get => sex;set => sex = value;}
    public virtual int Age {get => age;set => age = value;}
}

        在Utils文件夹中建立NHibernateHelper类,这个类的主要作用是用来读取配置文件,然后连接数据库用的,代码如下:

public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory;
    private static ISessionFactory SessionFactory
    {
        get
        {
            if(_sessionFactory == null)
            {
                var configuration = new Configuration();
                configuration.Configure(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"..\..\Config\hibernate.cfg.xml");
                _sessionFactory = configuration.BuildSessionFactory();
            }
            return _sessionFactory;
        }
    }

    public static ISession OpenSession()
    {
        try
        {
            return SessionFactory.OpenSession();
        }
        catch (Exception e)
        {
            MessageBox.Show("打开数据库失败:" +ex.ToString());
            return null;
        }
    }
    
}

        在Mapper文件夹中建立UserInfoMapper类,代如下:

public calsss UserInfoMapper
{
    public IList<UserInfo> GetUser(string name)
    {
        IList<UserInfo> list = NHibernateHelper.OpenSession().CreateSQLQuery(@"select * from Test where name like ?").AddEntity(typeof(UserInfo)).SetString(0,"%" + name + "%").List<UserInfo>();
        return list;
    }
}

        接着在Mapper中建立实体与数据库关联的配置文件UserInfo.hbm.xml,其中的<class name=“” table=“”>,name中填写两个信息,第一个是你的实体类的具体位置,第二个是命名空间,table中填写的是数据库表的名字。然后其中id、property中的name指实体类中名字,column指数据库表中的列名,代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <calss name="NHibernateTest.Entity.UserInfo,NHibernateTest" table="Test">
        <id name="Id" column="id" type="Int64" unsaved-value="0">
            <generator class="assigned" />
        </id>
        <property name="Name" type="string" column="name" />
        <property name="Sex" typr="string" column="sex" />
        <property name="Age" type="Int64" column="age" />
    </class>
</hibernate-mapping>

       最后我们的窗口这样来编写,其实就是个很简单的显示而已,好不好看无所谓窗口如图:

       其中的代码如下:

public partial class Form1:Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender,EventArgs e)
    {
        string name = texBox1.Test;
        UserController userController = new UserController();
        IList<UserInfo> list = userController.GetUser(name);
        if(list != null && list.Count > 0)
        {
            textBox2.Text = list[0].Name;
            textBox3.Text = list[0].Age.ToString();
            textBox4.Text = list[0].Sex;
        }
        else
        {
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            MessageBox.Show("没有符合的查询条件!");
        }
    }
}

       我们的数据库表字段四个:id、name、sex、age。

       当我们输入名字,点击查询的时候,就会在界面给我们显示出查询出来的结果。

       这就是NHibernate的基本使用,我这里使用的是SQL语句进行查询,NHibernate中有自己的HQL语句,跟Java中的Hibernate差不多,这里我就不做详细的介绍了,可以去看看其它博主的介绍。

发布了165 篇原创文章 · 获赞 41 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_41061437/article/details/98966132