composite key

Implementation of CompositeKey Implementation of
 CompositeKey primary key. If a table in the database is a composite primary key, then use

NHibernate will be a little troublesome, let's not talk about it, let's talk with code examples:
 1: Preparation, create a table structure in Oracle, the following SQL statement to create a table (you can use Toad For

Oracle)
 CREATE TABLE ROBOT_TRACKING
(
  LUNGUID VARCHAR2(9 BYTE) NOT NULL,
  POS VARCHAR2(2 BYTE) NOT NULL,
  ACT VARCHAR2(2 BYTE) NOT NULL,
  TIMESTAMPS DATE NOT NULL,
  TOC DATE DEFAULT sysdate
);
CREATE UNIQUE INDEX ROBOT_TRACKING_PK ON ROBOT_TRACKING
(LUNGUID, ACT);
ALTER TABLE ROBOT_TRACKING ADD (
  CONSTRAINT ROBOT_TRACKING_PK
 PRIMARY KEY
 (LUNGUID, ACT)
    USING INDEX )
 
 2: Prepare the data entity of the data table object, this step is the key. Or speak in code:
using System;
using System.Collections.Generic;
using System.Collections;

namespace OKEC.Sample.NHibernate.NHibernateTest
{
    public partial class RobotTracking
    {

        public override bool Equals(object obj)
        {
            if ((obj == this))
            {
                return true;
            }
            if (((obj == null)
                        || (obj.GetType() != this.GetType())))
            {
                return false;
            }
            RobotTracking test = obj as RobotTracking;
            return (Id.Equals(test.Id));
        }
        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
        private System.DateTime _tIMESTAMPS;

        private System.DateTime _tOC;

        public RobotTracking()
        {
            this._idPK = new RobotTrackingPK();
        }

        public RobotTracking(string lunguid, string act)
        {
            this._idPK = new RobotTrackingPK();
            this._idPK.LUNGUID = lunguid;
            this._idPK .ACT = act;
            this.lunguId  = lunguid;
            this.act  = act;
            
        }
        
        private string _pOS;

        private string lunguId;

        private string act;
        public string ACT
        {
            get
            {
                return act;
            }
            set
            {
                this.Id.ACT = value;
                act = value;
            }
        }

        public override string ToString()
        {
            return string.Format("RobotTracking:{0} {1} {2} {3}

{4}",lunguId,act,_pOS ,_tIMESTAMPS ,_tOC );
        }

        public string LUNGUID
        {
            get
            {
                return lunguId;
            }
            set
            {
                this.Id.LUNGUID = value;
                lunguId = value;
            }
        }
     
        private RobotTrackingPK _idPK;

        public virtual System.DateTime TIMESTAMPS
        {
            get
            {
                return this._tIMESTAMPS;
            }
            set
            {
                this._tIMESTAMPS = value;
            }
        }

        public virtual System.DateTime TOC
        {
            get
            {
                return this._tOC;
            }
            set
            {
                this._tOC = value;
            }
        }

        public virtual string POS
        {
            get
            {
                return this._pOS;
            }
            set
            {
                this._pOS = value;
            }
        }

        public virtual RobotTrackingPK Id
        {
            get
            {
                return this._idPK;
            }
            set
            {
                this._idPK = value;
            }
        }

        [Serializable]
        public partial class RobotTrackingPK
        {
            private string _aCT;

            private string _lUNGUID;

            public virtual string ACT
            {
                get
                {
                    return this._aCT;
                }
                set
                {
                    this._aCT = value;
                }
            }

            public virtual string LUNGUID
            {
                get
                {
                    return this._lUNGUID;
                }
                set
                {
                    this._lUNGUID = value;
                }
            }

            public override string ToString()
            {
                return String.Join(":", new string[] {
                        this._aCT.ToString(),
                        this._lUNGUID.ToString()});
            }

            public override bool Equals(object obj)
            {
                if ((obj == this))
                {
                    return true;
                }
                if (((obj == null)
                            || (obj.GetType() != this.GetType())))
                {
                    return false;
                }
                RobotTrackingPK test = ((RobotTrackingPK)(obj));
                return (((_aCT == test._aCT)
                            || ((_aCT != null)
                            && _aCT.Equals(test._aCT)))
                            && ((_lUNGUID == test._lUNGUID)
                            || ((_lUNGUID != null)
                            && _lUNGUID.Equals(test._lUNGUID))));
            }

            public override int GetHashCode()
            {
                return XorHelper(_aCT.GetHashCode(), _lUNGUID.GetHashCode());
            }

            private int XorHelper(int left, int right)
            {
                return left ^ right;
            }
        }
    }
}

Some explanations for the above code:
 Set the composite key to the embedded class of the data entity (that is, the class RobotTracking), this step is very critical. I

Tried, if it is not an inline class, the code behind will not compile. The exception entity class must overload the Equals() method,

At the same time it is best to overload the GetHash() method as well. Another point to point out is that the class of the composite key must be [Serializable]

sex. After building.
 3: For the RobotTrakcing configuration file (RobotTracking.hbm.xml) file, this file can pass

It has been generated by CodeSmith, but it should be noted that the files generated by the NHibernate template of CodeSmith I downloaded from the Internet are not

It can be used directly, but needs to be modified. The following is the configuration file, continue to speak with code.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="OKEC.Sample.NHibernate.NHibernateTest.RobotTracking,NHibernateTest" 

table="ROBOT_TRACKING" lazy="false">
    <composite-id>
      <key-property  name="LUNGUID"  type="String">
        <column name="LUNGUID" length="9"/>
      </key-property>
      <key-property name="ACT" type="String">
        <column name="ACT" length="2"/>
      </key-property>
    </composite-id>

    <!--
      <id name="Id" type="String" unsaved-value="null">
   <column name="LUNGUID" length="9" sql-type="VARCHAR2" not-

null="true" index="ROBOT_TRACKING_PK"/>
   <column name="ACT" length="2" sql-type="VARCHAR2" not-

null="true" index="ROBOT_TRACKING_PK"/>
   <generator class="native" />
  </id>
-->


    <property name="POS" type="String">
   <column name="POS" length="2" sql-type="VARCHAR2" not-

null="true"/>
  </property>
  <property name="TIMESTAMPS" type="DateTime">
   <column name="TIMESTAMPS" sql-type="DATE" not-null="true"/>
  </property>
  <property name="TOC" type="DateTime">
   <column name="TOC" sql-type="DATE" not-null="false"/>
  </property>
 </class>
</hibernate-mapping>

The key point of the configuration file is with
    <composite-id>
      <key-property name="LUNGUID" type="String">
        <column name="LUNGUID" length="9"/>
      </key-property>
      <key- property name="ACT" type="String">
        <column name="ACT" length="2"/>
      </key-property>
    </composite-id>
The primary key in the database corresponds to the one in the data entity class Field correspondence of RobotTrackingPK class.

 4: Then the whole configuration using NHibernate, speak in code:
<?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.OracleClientDriver</property>
  <property name="connection.connection_string">
   User ID=Soctt;Password=tiger;Data Source=localHost
  </property>
  <property name="show_sql">false</property>
  <property

name="dialect">NHibernate.Dialect.OracleDialect</property>
    <mapping assembly="NHibernateTest" />  
  </session-factory>
</hibernate-configuration>

After preparing the above content, you can start using the
following DLLs
Common.Logging.DLL
Common.Logging.Log4Net.DLL
logNet4.DLL
NHibernate.DLL
Iesi.Collections.DLL
speak in code:
using System;
using System.Collections;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Expression;

namespace OKEC.Sample.NHibernate.NHibernateTest
{
 class ClientApp
 {
  static void main(string[] args)
  {
    //得到NHibernate的配置
                Configuration cfg = new Configuration();
                cfg.Configure("Oracle.cfg.xml");

    ISessionFactory factory = cfg.BuildSessionFactory

();
    ISession session = factory.OpenSession();
    ITransaction transaction =

session.BeginTransaction();
                RobotTracking robotTracking ;

                     robotTracking = new RobotTracking(string.Concat("09060000",

i.ToString()), "US");
                    robotTracking.ACT = "US";
                    robotTracking.POS = "R2";
                    robotTracking.TIMESTAMPS = DateTime.Now;
                    robotTracking.TOC = DateTime.Now;
   //Determine the corresponding data Whether there is
                    object obj= session.Get(typeof(RobotTracking), robotTracking);
                     //There is no insert operation
   if (obj == null)
                        session.Save(robotTracking);
   //There is a delete operation
                    else
                        session.Delete(robotTracking );
     // commit all of the changes to the DB and

close the ISession
    transaction.Commit();
    session.Close();

    // open another session to retrieve the just

inserted user
    session = factory.OpenSession();

                //查询操作
               // IQuery query = session.CreateQuery("from RobotTracking where"+"

robotTracking.LUNGUID="+"090600005"+"");
                string lunguid = "090600001";
                string act="R3";
                string where = " where lunguid >= '" + lunguid +"' and

act<>'"+act+"'" ;

                IQuery query = session.CreateQuery("from RobotTracking "+where );
                IList<RobotTracking> list = query.List<RobotTracking>();
                foreach (RobotTracking  tracking in list )
                {
                    Console.WriteLine(tracking.ToString());
                }
                ICriteria creieria =  session.CreateCriteria(typeof

(RobotTracking));
                creieria.Add(Expression.Sql("LUNGUID >= '" + lunguid+"'"));
                creieria.Add(Expression.Sql(" ACT<>'" + act+"'"));
                list = creieria.List<RobotTracking>();
                foreach (RobotTracking tracking in list)
                {
                    Console.WriteLine(tracking.ToString());
                } 
 }  

 }
}
Description: The above code illustrates the general usage of Composite primary keys, and demonstrates insertion, deletion, and two different methods.

query operation.
To add, when inserting the TOC field, although the default value of the database is Sysdate, if there is no robotTracking.TCo=
DateTime.Now sentence, then the value inserted into the data is not the Sysdate we expect. I want to know what the value is

You can actually try it.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325202073&siteId=291194637