본문 바로가기

IT/C#, NHibernate

NHibernate Many-to-one, one-to-Many tutorial, example

반응형
1. NHibernate sample project를 구현하는데 있어서 개발 순서는 다음과 같다.
 - DB 구성
 - *.hbm.xml , cfg.xml 파일 구성 및 속성 변경
 - class 생성
 - DB insert 

2. DB 구성
DB 구성은 다음과 같다.

ContactID와 ContactDetailID는 PK이며, ContactDetail에 있는 parentID는 FK로 Contact의 ContactID랑 연결되어있다.


3. hibernate.cfg.xml, Contact.hbm.xml, ContactDetail.hbm.xml 구성

hibernate.cfg.xml 은 다음과 같이 구성하였다.

<?xml version=" 1.0" encoding=" utf-8" ?>

<hibernate-configuration xmlns=" urn:nhibernate-configuration-2.2" >
  <session-factory>
    < property name ="connection.provider ">
      NHibernate.Connection.DriverConnectionProvider
    </ property>
    < property name ="dialect ">
      NHibernate.Dialect.MsSqlCeDialect
    </ property>
    < property name ="connection.driver_class ">
      NHibernate.Driver.SqlClientDriver
    </ property>
    < property name ="connection.connection_string ">
      Data Source=localhost; Initial Catalog=<!-- DB 명 -->; Integrated Security=True; Pooling=False
    </ property>
    < property name ="show_sql ">true </property>
    < mapping assembly ="nHibernateTest "/> <!-- 프로젝트 명 -->
  </session-factory>
</hibernate-configuration>

Contact.hbm.xml은 다음과 같이 구성하였다.

<?xml version=" 1.0" encoding=" utf-8"?>
<hibernate-mapping assembly=" nHibernateTest"
                   namespace=" nHibernateTest"
                   xmlns=" urn:nhibernate-mapping-2.2">

  <class name=" Contact" table=" Contact" lazy=" true" >
    < id name ="ContactID " column ="ContactID ">
      < generator class ="identity " />
    </ id>
    < property name ="FirstName ">
      < column name ="FirstName " sql-type ="varchar " not-null ="false " />
    </ property>
    < property name ="LastName ">
      < column name ="LastName " sql-type ="varchar " not-null ="false " />
    </ property>
    < bag name ="ContactDetail " inverse ="true ">
      < key column ="parentID " />
      < one-to-many class ="ContactDetail " />
    </ bag>
  </class>
 
</hibernate-mapping>


ContactDetail.hbm.xml은 다음과 같이 구성하였다.


<?xml version=" 1.0" encoding=" utf-8"?>
<hibernate-mapping assembly=" nHibernateTest"
                   namespace=" nHibernateTest"
                   xmlns=" urn:nhibernate-mapping-2.2"
                  auto-import=" true">
  <class name=" ContactDetail" table=" ContactDetail" lazy=" true" >
    < id name ="ContactDetailID " column ="ContactDetailID " />
    < many-to-one name ="Contact ">
      < column name ="parentID " sql-type ="int " not-null ="false " />
    </ many-to-one>
    < property name ="email ">
      < column name ="email " sql-type ="varchar " not-null ="false " />
    </ property>
  </class>
 
</hibernate-mapping>


Contact.hbm.xml과 ContactDetail.hml 속성을 변경해야 한다.


빌드 작업 : 포함 리소스
출력 디렉터리로 복사 : 항상 복사

4. Class 구현

Contact 클래스 구현

public class Contact
    {
        public Contact()
        {
            ContactDetail = new List <ContactDetail>();
        }
        public virtual int ContactID { get; set ; }
        public virtual string FirstName { get; set ; }
        public virtual string LastName { get; set ; }
        public virtual IList< ContactDetail> ContactDetail { get ; set; }
    }

ContactDetail 클래스 구현

  public class ContactDetail
    {
        public virtual int ContactDetailID { get; set ; }
        public virtual Contact Contact { get; set ; }
        public virtual string email { get; set ; }
    }
}


5. DB Insert 기능 구현

 static void Main(string [] args)
        {
            Configuration cfg;
            ISessionFactory mySessionFactory;
            ISession mySession;

            cfg = new Configuration ();cfg.Configure("hibernate.cfg.xml");

            mySessionFactory = cfg.BuildSessionFactory();
            mySession = mySessionFactory.OpenSession();


            using (mySession.BeginTransaction())
            {
                int tong_id_1 = 1;
                Contact loContact = new Contact { FirstName = "abc", LastName = "Last" };
                mySession.Save(loContact);

                ContactDetail de = new ContactDetail
                {
                    ContactDetailID = 11,
                    Contact = loContact,
                    email = "abc@gmail.com"
                   
                };
                loContact.ContactDetail.Add(de);
                mySession.Save(de);
                //mySession.Save(de);
               
                mySession.Transaction.Commit();
                mySession.Close();
               
            }
        }