NHibernate 설정 및 HBM Mapping(3)

|

Table의 Key가 다중일 경우 처리


Database Table : TbCodeIfLayout

COLUMN

TYPE

LENTH

 TcId(PK)

VARCHAR

12

 ItemSeq(PK)

NUMBER

4

 ItemName

VARCHAR

50

 DataType

VARCHAR

10

 DataLength

 NUMBER

3

 Remark

 VARCHAR

30

위와 같이 Pk가 2개 이상일 경우 정의 방법은 구별이 된다.

Model 부터 확인해 보자


model : TbCodeIfLayout.cs

public class TbCodeIfLayout
    {
        public virtual TbCodeIfLayoutKey id { get; set; }
        public virtual string ItemName { get; set; }
        public virtual string DataType { get; set; }
        public virtual int DataLength { get; set; }
        public virtual string Remark { get; set; }
    }

    public class TbCodeIfLayoutKey
    {
        public virtual string TcId { get; set; }
        public virtual int ItemSeq { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            var t = obj as TbCodeIfLayoutKey;
            if (t == null) return false;
            if (TcId == t.TcId && ItemSeq == t.ItemSeq) return true;
            return false;
        }
        public override int GetHashCode()
        {
            return (TcId + "|" + ItemSeq + "|").GetHashCode();
        }
    }

보기와 같이 Pk가 여러개 일 경우 Pk로만 이루어진 Class를 따로 정의 해 준다.

이때 Equals와 GetHashCode를 oerride 해 주는데 이유는 NHibernate에서 Pk로 정의 된 항목이 어떤것인지 구별해 주기 위해서라고 한다.

즉 여러개 있을경우 필수적으로 override해 줘야 된다 이야기가 되겠다.


여기에 대응되는 mapper정의는

TbCodeIfLayout.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DBRepository" namespace="DBRepository.model">
  <class name="TbCodeIfLayout" table="TbCodeIfLayout">
    <composite-id name="id" class="TbCodeIfLayoutKey">
      <key-property name="TcId" column="TcId" type="string" length="12"/>
      <key-property name="ItemSeq" column="ItemSeq" type="Int32" length="4"/>
    </composite-id>
    <property name="ItemName" column="ItemName" type="string" length="50" not-null="true"/>
    <property name="DataType" column="DataType" type="string" length="10" not-null="true"/>
    <property name="DataLength" column="DataLength" type="Int32" length="3" not-null="true"/>
    <property name="Remark" column="Remark" type="string" length="30" not-null="true"/>
  </class>
</hibernate-mapping>

위와 같은형태로 composite-id tag로 따로 PK를 정의한 Class를 mapping 시켜 준다.

나머지 매핑은 앞장에서 설명한 내용과 같다.


And