5. Use nhib.pdf to write the persistent Layer Code 1. the following describes the seven basic steps for using nhib.pdf: 1. construct the ConfigurationconfignewConfiguration () configuration object (). configure (); 2. construct the SessionFactory object ISessionFactorysessi
5. Use nhib.pdf to write the persistent Layer Code 1. the following describes the seven basic steps for using nhib.pdf: // 1. construct the Configuration object Configuration config = new Configuration (). configure (); // 2. construct the SessionFactory object ISessionFactory sessi
5. Use nhib.pdf to write the persistent Layer Code
1. Seven basic steps for using nhib.pdf:
The following describes the seven steps to persist an object:
// 1. construct the Configuration object Configuration config = new Configuration (). configure (); // 2. construct the SessionFactory object ISessionFactory sessionFactory = config. buildSessionFactory (); ISession session = null; ITransaction tx = null; try {// 3. open Session session = sessionFactory. openSession (); // 4. open transaction tx = session. beginTransaction (); // 5. process persistent service sessions. persist (obj); // 6. commit transaction tx. commit ();} catch {// 6. roll back the transaction tx. rollback (); throw; } Finally {// 7. Close Session if (session! = Null) {session. Close ();}}
2. You may have to spend some time studying many basic theories about nhib.pdf. I am here only for people who have studied nhib.pdf,
To reduce code writing, the following is my encapsulation of the persistent layer code:
First Class: HibernateSessionFactory:
Namespace OfficeDAL {public class HibernateSessionFactory {const String CONFIG_FILE = "hibernate. cfg. xml "; const String ASSEMBLY =" BookShopModel "; static Configuration config = null; static ISessionFactory sessionFactory = null; /// <summary> /// Constructor (equivalent to the static code block of Java) /// </summary> static HibernateSessionFactory () {// config = new Configuration (). configure (CONFIG_FILE ). addAssembly (ASSEMBLY); // config = new Configuration (). addAssembly (ASSEMBLY); config = new Configuration (). configure (); sessionFactory = config. buildSessionFactory ();} // <summary> // get SessionFactory /// </summary> /// <returns> </returns> public static ISessionFactory GetSessionFactory () {return sessionFactory;} // <summary> // obtain the Session // </summary> /// <returns> </returns> public static ISession GetSession () {return sessionFactory. openSession ();}}}
Class 2: BaseService, basic class of all Service classes
This class involves paging, and the object definition of paging is stored in another project (OfficeModel ).
Therefore, I will first explain the entities here:
NCondition: class that encapsulates paging Conditions
Namespace OffficeModel. pagination {public class NCondition {private String _ propertyName; public String PropertyName {get {return _ propertyName;} set {_ propertyName = value;} private Operation _ operate; public Operation Operate {get {return _ operate;} set {_ operate = value ;}} private Object _ propertyValue; public Object PropertyValue {get {return _ propertyValue ;} set {_ propertyValue = value ;}} public NCondition () {}public NCondition (String propertyName, Operation op, object propertyValue) {this. _ propertyName = propertyName; this. _ operate = op; this. _ propertyValue = propertyValue ;}}}
Operation: enumerative encapsulation and comparison operationsNamespace OffficeModel. Pagination {public enum Operation {GT, LT, GE, LE, NE, EQ, LIKE, BETWEEN, IN }}
Order: class that encapsulates sorting
Namespace OffficeModel. pagination {public class NOrder {public enum OrderDirection {ASC, DESC} private String _ propertyName; public String PropertyName {get {return _ propertyName;} set {_ propertyName = value ;}} private OrderDirection _ orderType; public OrderDirection OrderType {get {return _ orderType;} set {_ orderType = value ;}} public NOrder () {} public NOrder (String propertyName, OrderDirection orderType) {this. _ propertyName = propertyName; this. _ orderType = orderType ;}}}
PageInfo: class that encapsulates paging information
Namespace OffficeModel. pagination {public class PageInfo {public PageInfo () {} public PageInfo (Type entityType, int pageIndex) {this. _ entityType = entityType; this. _ pageIndex = pageIndex;} public PageInfo (Type entityType, int pageIndex, params NCondition [] conditions) {this. _ entityType = entityType; this. _ pageIndex = pageIndex; this. _ conditions = conditions;} public PageInfo (Type entityType, int pageIndex, NCondition [] conditions, NOrder [] orders) {this. _ entityType = entityType; this. _ pageIndex = pageIndex; this. _ conditions = conditions; this. _ orderFields = orders;} private Type _ entityType; // class public Type EntityType {get {return _ entityType;} set {_ entityType = value ;}} private int _ pageIndex = 1; // page number public int PageIndex {get {return _ pageIndex;} set {_ pageIndex = value ;}} private NCondition [] _ conditions; // condition public NCondition [] Conditions {get {return _ conditions;} set {_ conditions = value ;}} private NOrder [] _ orderFields; // sort public NOrder [] OrderFields {get {return _ orderFields;} set {_ orderFields = value ;}} private int pageSize = 10; public int PageSize {get {return pageSize;} set {pageSize = value ;}} private int _ recordCount; public int RecordCount {get {return _ recordCount ;} set {_ recordCount = value ;}} private int pageCount; public int PageCount {get {return pageCount ;}set {pageCount = value ;}} private System. collections. IList list; public IList List {get {return list;} set {list = value ;}}}}
Next, we finally return to the BaseService class that we are most concerned about. This class is used to define some more common methods. Other classes on the persistence layer inherit from this class.
Using System; using System. collections. generic; using System. text; using nhibmodel; using OffficeModel. pagination; using nhib.pdf. criterion; using System. collections; using log4net; namespace OfficeDAL {public class BaseService {protected ILog log = LogManager. getLogger (typeof (BaseService); protected ISession GetSession () {log. info ("Office: Session"); return HibernateSessionFactory. getSession ();}// /<Summary> /// save /// </summary> /// <param name = "obj"> </param> public void Persist (Object obj) {ISession session = null; ITransaction tx = null; try {session = HibernateSessionFactory. getSession (); tx = session. beginTransaction (); session. persist (obj); tx. commit ();} catch {tx. rollback (); throw;} finally {session. close () ;}/// <summary> // delete an object /// </summary> /// <param name = "obj"> </par Am> public void Remove (Object obj) {ISession session = null; ITransaction tx = null; try {session = HibernateSessionFactory. getSession (); tx = session. beginTransaction (); session. delete (obj); tx. commit ();} catch {tx. rollback (); throw;} finally {session. close ();}} /// <summary> /// query all /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "entiyType"> </param> // <returns> </r Eturns> public IList <T> findAll <T> () where T: new () {log. info ("Office: BaseService FindAll"); ISession session = null; try {session = HibernateSessionFactory. getSession (); return session. createCriteria (typeof (T )). list <T> ();} finally {session. close ();}} /// <summary> /// query all /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "entiyType"> </param> // <returns> </returns> public IList GetAll (Type entityType) {ISession session = null; try {session = HibernateSessionFactory. getSession (); return session. createCriteria (entityType ). list ();} finally {session. close ();}} /// <summary> /// query object oid /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "oid"> </param> // <returns> </returns> public T findById <T> (object oid) where T: new () {ISession session = Null; try {session = HibernateSessionFactory. GetSession (); return session. Get <T> (oid) ;}finally {if (session! = Null) {session. close ();}}} /// <summary> /// modify the object /// </summary> /// <param name = "obj"> </param> public void Update (object obj) {using (ISession session = HibernateSessionFactory. getSession () {session. update (obj); session. close () ;}} public void DoPager (PageInfo pi) {log. info ("Office: DoPager"); if (pi. entityType = null) {throw new Exception ("the paging class name cannot be blank");} using (ISession session = Hibe RnateSessionFactory. getSession () {ICriteria qbc = session. createCriteria (pi. entityType); // The total number of items qbc. setProjection (nhib.pdf. criterion. projections. rowCount (); prepareConditions (qbc, pi. conditions); pi. recordCount = qbc. setMaxResults (1 ). uniqueResult <int> (); // total page number pi. pageCount = pi. recordCount % pi. pageSize = 0? Pi. recordCount/pi. pageSize: pi. recordCount/pi. pageSize + 1; // qbc. setProjection (null); // The paging result ICriteria _ qbc = session. createCriteria (pi. entityType); prepareConditions (_ qbc, pi. conditions); // you can specify prepareOrder (_ qbc, pi. orderFields); // The paging result pi. list = _ qbc. setFirstResult (pi. pageIndex-1) * pi. pageSize ). setMaxResults (pi. pageSize ). list () ;}/// <summary> /// processing condition /// </summary> /// <param n Ame = "qbc"> </param> // <param name = "conditions"> </param> private void prepareConditions (ICriteria qbc, params NCondition [] conditions) {if (qbc = null | conditions. length = 0) {return;} foreach (NCondition condition in conditions) {switch (condition. operate) {case Operation. EQ: qbc. add (Expression. eq (condition. propertyName, condition. propertyValue); break; case Operati On. GT: qbc. add (Expression. gt (condition. propertyName, condition. propertyValue); break; case Operation. LT: qbc. add (Expression. lt (condition. propertyName, condition. propertyValue); break; case Operation. GE: qbc. add (Expression. ge (condition. propertyName, condition. propertyValue); break; case Operation. LE: qbc. add (Expression. le (condition. propertyName, condition. propertyValue); break; case Operation. N E: qbc. add (Expression. not (Expression. eq (condition. propertyName, condition. propertyValue); break; case Operation. BETWEEN: qbc. add (Expression. between (condition. propertyName, (condition. propertyValue as Object []) [0], (condition. propertyValue as Object []) [1]); break; case Operation. LIKE: qbc. add (Expression. like (condition. propertyName, condition. propertyValue. toString (), MatchMode. anywhere )); Break; case Operation. IN: qbc. add (Expression. in (condition. propertyName, condition. propertyValue as object []); break ;}}} /// <summary> /// sort by processing /// </summary> /// <param name = "qbc"> </param> /// <param name = "orderFields"> </param> private void prepareOrder (ICriteria qbc, params OffficeModel. pagination. NOrder [] orderFields) {if (qbc = null | orderFields. length = 0) {r Eturn;} foreach (OffficeModel. Pagination. NOrder order in orderFields) {qbc. AddOrder (order. OrderType = OffficeModel. Pagination. NOrder. OrderDirection. ASC? Order. asc (order. propertyName): Order. desc (order. propertyName ));}} /// <summary> /// query an object based on a single attribute /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "propertyName"> </param> // <param name = "propertyValue"> </param> // <returns> </returns> public T FindByProperty <t> (String propertyName, object propertyValue) {using (ISession session = HibernateSessionFactory. getSession () {return Session. createCriteria (typeof (T )). add (Restrictions. eq (propertyName, propertyValue )). setMaxResults (1 ). uniqueResult <T> () ;}} public T FindByProperty <T> (String [] propertyNames, Object [] propertyValues) {if (propertyNames = null | propertyValues = null | propertyNames. length = 0 | propertyValues. length = 0 | propertyNames. length! = PropertyValues. length) {return default (T);} using (ISession session = HibernateSessionFactory. getSession () {ICriteria qbc = session. createCriteria (typeof (T); for (int I = 0; I <propertyNames. length; I ++) {qbc. add (Restrictions. eq (propertyNames [I], propertyValues [I]);} qbc. setMaxResults (1); return qbc. uniqueResult <T> ();}}}}
Time relationship. There are few annotations for the above classes. Please forgive me. If necessary, you can discuss them with each other.