在NHibernate的应用中,添加Entity层,添加实体类和Mappings文件。
实体层 SupplierEntity
public class SupplierEntity { /// <summary> /// 供应商ID /// </summary> public virtual int SupplierID { get; set; } /// <summary> /// 名称 /// </summary> public virtual string Name { get; set; } /// <summary> /// 联系人 /// </summary> public virtual string Linkman { get; set; } /// <summary> /// 地址 /// </summary> public virtual string Address { get; set; } /// <summary> /// 电话 /// </summary> public virtual string Tel { get; set; } /// <summary> /// 手机 /// </summary> public virtual string Phone { get; set; } /// <summary> /// 邮编 /// </summary> public virtual string Postcode { get; set; } /// <summary> /// 备注 /// </summary> public virtual string Descr { get; set; } }
SupplierEntity.hbm.xml
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TBManage.Entity" namespace="TBManage.Entity"> <class name="TBManage.Entity.SupplierEntity, TBManage.Entity" table="TSupplier" lazy="false"> <id name="SupplierID" column="Supplierid" type="Int32"> <generator class="native" /> </id> <property name="Name" column="Name" type="string" length="50" not-null="true"/> <property name="Linkman" column="Linkman" type="string" length="50"/> <property name="Address" column="Address" type="string" length="50"/> <property name="Phone" column="Phone" type="string" length="50"/> <property name="Postcode" column="Postcode" type="string" length="50"/> <property name="Descr" column="Descr" type="string" length="200"/> </class> </hibernate-mapping>
数据库表
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[TSupplier]( [SupplierID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) NULL, [Linkman] [varchar](50) NULL, [Address] [varchar](100) NULL, [Tel] [varchar](50) NULL, [Phone] [varchar](50) NULL, [Postcode] [varchar](50) NULL, [Descr] [varchar](100) NULL, [CreateUser] [varchar](50) NULL, [CreateDate] [date] NULL, [UpdateUser] [varchar](50) NULL, [UpdateDate] [date] NULL, CONSTRAINT [PK_T_Supplier] PRIMARY KEY CLUSTERED ( [Supplierid] 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 SET ANSI_PADDING OFF GO
PS:需要特别注意的是:在hbm.xml中,column中Supplierid不可写成SupplierID,否则在HQL转换成sql时,会将SupplierID转换成Supplier_ID,如果数据库字段为Supplier_ID,在hbm.xml中,column中请写为supplier_id。
HQL转化SQL的时,会自动在第二个大写字母之前添加“_”。
具体原因待查证!