SlideShare a Scribd company logo
Hibernate




            KSA-in Project   AUG 25st 2012
            프로젝트 상위기획        KSA-in Project Team
00
 Contents




            01. Hibernate?
            02. Spring+maven+mysql+hibernate
            03. Basic O/R mapping
            04. Association mappings
01
     Hibernate?




  • POJO-style domain models

  • Object/Relational Mapping

  • Remove or encapsulate vendor-specific SQL code




 • http://hibernate.org/
 • http://docs.jboss.org/hibernate/orm/4.1/quickstart/en-US/html_single/#d5e25
02
     Spring+maven+mysql




     1. Spring Hello world tutorial




     2. Download and install MySQL




                                      <mysql-version>5.1.21</mysql-version>

     3. Maven config – pom.xml        <!-- MySQL -->
                                      <dependency>
                                      <groupId>mysql</groupId>
                                      <artifactId>mysql-connector-java</artifactId>
                                      <version>${mysql-version}</version>
                                      </dependency>
02
     Spring+maven+mysql (Simple example using JDBC)

     CREATE SCHEMA ` helloworld` ;              public User get(String id) throws ClassNotFoundException, SQLException
                                                {
     CREATE TABLE ` helloworld` .` users` (             User user = new User();
           ` uid` INT NOT NULL ,
           ` id` VARCHAR(45) NOT NULL ,                Connection c = getConnection();
           ` password` VARCHAR(45) NOT NULL ,          PreparedStatement ps = c.prepareStatement("select * from users
           PRIMARY KEY (` uid` )                       where id=?");
     );                                                ps.setString(1, id);
                                                       ResultSet rs = ps.executeQuery();
                                                       rs.next();

                                                       user.setUid(rs.getInt("uid"));
                                                       user.setId(rs.getString("id"));
                                                       user.setPassword(rs.getString("password"));

                                                       rs.close();
                                                       ps.close();
                                                       c.close();

                                                       return user;
                                                }

                                                private Connection getConnection() throws ClassNotFoundException,
                                                SQLException
                                                {
                                                        Class.forName("com.mysql.jdbc.Driver");
                                                        Connection c =
                                                        DriverManager.getConnection("jdbc:mysql://localhost/helloworld
                                                        ", "njurn", “123123");
                                                        return c;
                                                }
02
     Spring+maven+mysql+hibernate

                                                                             <mysql-version>5.1.21</mysql-version>

                                                                             <!– Spring orm -->
                                                                             <dependency>
                                                                                    <groupId>org.springframework</groupId>
 1. Add maven dependency <pom.xml>                                                  <artifactId>spring-orm</artifactId>
                                                                                    <version>${springframework-version}</version>
                                                                             </dependency>

                                                                             <!-- Hibernate -->
                                                                             <dependency>
                                                                                    <groupId>org.hibernate</groupId>
 2. Add config files                                                                <artifactId>hibernate-core</artifactId>
  1) resources/properties/database.properties                                       <version>${hibernate-version}</version>
                                                                             </dependency>
  2) resources/database/DataSource.xml                                       <dependency>
  3) resources/database/Hibernate.xml                                               <groupId>cglib</groupId>
                                                                                    <artifactId>cglib</artifactId>
                                                                                    <version>2.2.2</version>
                                                                                    <scope>runtime</scope>
                                                                             </dependency>


 3. Modify <root-context.xml>                                                <!-- Hibernate Configurations -->
                                                                             <import resource="classpath:database/DataSource.xml"/>
                                                                             <import resource="classpath:database/Hibernate.xml"/>




 • http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/
 • http://www.mkyong.com/spring/maven-spring-hibernate-annotation-mysql-example/
 • http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single #d5e4729
02
     Spring+maven+mysql+hibernate (Simple hibernate example)


     @Entity
     @Table(name = "stock")
     public class Stock {

            @Id
            @GeneratedValue(strategy = IDENTITY)
            @Column(name = "STOCK_ID", unique = true, nullable = false)
            public Integer stockId;

            @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
            public String stockCode;

            @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
            public String stockName;
     }


     SessionFactory sessionFactory;

     /* Insert */
     Stock stock = new Stock();
     stock.stockCode = "abcd";
     stock.stockName = "temp1";
     sessionFactory.getCurrentSession(). save(stock);

     /* Update */
     stock2.stockName = "temp2";
     sessionFactory.getCurrentSession(). update(stock2);
03
     Basic O/R mapping
     import   javax.persistence.Entity;
     import   javax.persistence.Table;
     import   javax.persistence.Id;
     import   javax.persistence.GeneratedValue;
     Import   javax.persistence.GenerationType;
     import   javax.persistence.Column;

     …



    @Entity
           Type               Element                                                Summary

           String              name           The name of an entity.



    @Table
           Type               Element                                                Summary

           String              catalog        (Optional) The catalog of the table.

           String              name           (Optional) The name of the table.

           String             schema          (Optional) The schema of the table.

     UniqueConstraint[]   uniqueConstraints   (Optional) Unique constraints that are to be placed on the table.




 • http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
03
     Basic O/R mapping

    @Column
          Type               Element                                                Summary

           String        columnDefinition     (Optional) The SQL fragment that is used when generating the DDL for the column.

          boolean           insertable        (Optional) Whether the column is included in SQL INSERT statements generated by
                                              the persistence provider.
            int               length          (Optional) The column length.

          String              name            (Optional) The name of the column.

          boolean            nullable         (Optional) Whether the database column is nullable.

            int              precision        (Optional) The precision for a decimal (exact numeric) column.

            int                scale          (Optional) The scale for a decimal (exact numeric) column.

          String               table          (Optional) The name of the table that contains the column.

          boolean             unique          (Optional) Whether the property is a unique key.

          boolean           updatable         (Optional) Whether the column is included in SQL UPDATE statements generated by
                                              the persistence provider.




 • http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
03
     Basic O/R mapping




       http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
04
     Association mappings (One-to-One)




     @Entity                                                      @Entity
     public class Stock {                                         public class StockDetail {
             @Id                                                          @Id
             Integer stockId;                                             Integer stockId;

            @OneToOne (                                                  @OneToOne(fetch = FetchType.LAZY)
                  fetch = FetchType.LAZY,                                @PrimaryKeyJoinColumn
                  mappedBy = "stock",                                    Stock stock;
                  cascade = CascadeType.ALL )                             ...
            StockDetail stockDetail;                              }
             ...
     }




 • http://www.mkyong.com/hibernate/hibernate-one-to-one-relationship-example-annotation/
04
     Association mappings (One-to-Many)




     @Entity                                                     @Entity
     @Table(name = "stock“)                                      public class StockDailyRecord {
     public class Stock {                                                @Id
             @Id                                                         Integer recordId;
             Integer stockId;
                                                                        @ManyToOne(fetch = FetchType.LAZY)
            @OneToMany(                                                 @JoinColumn(
                   fetch = FetchType.LAZY,                                      name = "STOCK_ID",
                   mappedBy = "stock")                                          nullable = false)
            Set<StockDailyRecord> stockDailyRecords;                    Stock stock;
            ...                                                         ...
     }                                                           }




 • http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/
04
     Association mappings (Many-to-Many)




     @Entity                                                     @Entity
     @Table(name = "stock“)                                      public class Category {
     public class Stock {                                                @Id
             @Id                                                         Integer categoryId;
             Integer stockId;
                                                                        @ManyToMany(
            @ManyToMany(                                                       fetch = FetchType.LAZY,
                  fetch = FetchType.LAZY,                                      mappedBy = "categories"))
                  cascade = CascadeType.ALL)                            Set<Stock> stocks;
            @JoinTable(name = "stock_category",                         ...
                  catalog = "mkyongdb",                          }
                  joinColumns = {
                         @JoinColumn(
                                name = "STOCK_ID",
                                nullable = false,
                                updatable = false) },
                  inverseJoinColumns = {
                         @JoinColumn(
                                name = "CATEGORY_ID",
                                nullable = false,
                                updatable = false) })
            Set<Category> categories;
            ...
     }


 • http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/
05
     Others (Transaction)



     import org.springframework.transaction.annotation.Transactional;

     @Transactional
     public void testSaveAndGet() {
             String username = "test";

            User user = new User();
            user.username = username;
            user.password = "";
            user.koreanName = “test";
            long id = userDao.save(user);

            user = userDao.get(id);
            assertEquals("Saved user and retrieved user should have the same username", username,
            user.username);
     }

     … xmlns:tx="http://www.springframework.org/schema/tx" …

     <tx:annotation-driven transaction-manager="transactionManager" />
     <bean id="transactionManager"
     class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
     </bean>
05
     Others (hbm2ddl.auto)




                 Value                                  Explanation

                 create       Session factory가 실행될 때에 스키마를 지우고 다시 생성합니다. 스키마를 생성한 다음
                              에 classpath에서 import.sql 파일이 있는지 찾아 이 파일에 등록된 쿼리문을 실행합니다.

              create-drop     create와 같지만 session factory가 내려갈 때 DB의 스키마를 삭제합니다.


                update        시작하면서 도메인 객체 구성과 DB의 스키마를 비교해 필요한 테이블이나 칼럼이 없을
                              때 도메인 객체에 맞춰 DB 스키마를 변경합니다. 데이터나 스키마를 지우지는 않습니다.

                validate      처음에 도메인 객체 구성과 DB 스키마가 같은지 확인만 할 뿐 DB 스키마에 전혀 손대지
                              않습니다. SessionFactory 시작 시 확인을 해서 문제가 있으면 예외를 토해내고 죽습니다.




 • http://gyumee.egloos.com/2483659
05
     Others (Documents)



     Hibernate docs
        http://docs.jboss.org/hibernate/orm/4.1/quickstart/en-US/html/
        http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/
        http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/
        http://docs.jboss.org/hibernate/orm/4.1/javadocs/


     Persistence annotation
        http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html



     Configuration properties
       http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e4729
06
     The end

More Related Content

What's hot

Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Nikhil Bhalwankar
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
Ignacio Coloma
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojo
sdeconf
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
GR8Conf
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
Arun Gupta
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
Arjun Shanka
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the Cloud
Stephen Chin
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
Simon Su
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
thirumuru2012
 
JBoss AS Upgrade
JBoss AS UpgradeJBoss AS Upgrade
JBoss AS Upgrade
sharmami
 
CRESTCon Asia 2018 - Config Password Encryption Gone Wrong
CRESTCon Asia 2018 - Config Password Encryption Gone WrongCRESTCon Asia 2018 - Config Password Encryption Gone Wrong
CRESTCon Asia 2018 - Config Password Encryption Gone Wrong
Keith Lee
 
Cassandra Summit 2013 Keynote
Cassandra Summit 2013 KeynoteCassandra Summit 2013 Keynote
Cassandra Summit 2013 Keynote
jbellis
 
Sequelize
SequelizeSequelize
Sequelize
Tarek Raihan
 
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsMoving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Bruce Schubert
 

What's hot (19)

Lecture17
Lecture17Lecture17
Lecture17
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code ExampleMaven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
Maven + Jsf + Richfaces + Jxl + Jdbc - Complete Code Example
 
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
#34.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자교육,국...
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojo
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the Cloud
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
 
JBoss AS Upgrade
JBoss AS UpgradeJBoss AS Upgrade
JBoss AS Upgrade
 
CRESTCon Asia 2018 - Config Password Encryption Gone Wrong
CRESTCon Asia 2018 - Config Password Encryption Gone WrongCRESTCon Asia 2018 - Config Password Encryption Gone Wrong
CRESTCon Asia 2018 - Config Password Encryption Gone Wrong
 
Cassandra Summit 2013 Keynote
Cassandra Summit 2013 KeynoteCassandra Summit 2013 Keynote
Cassandra Summit 2013 Keynote
 
Sequelize
SequelizeSequelize
Sequelize
 
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsMoving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
 

Viewers also liked

J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
ksain
 
Bahagian c 2011 ppt
Bahagian c 2011 pptBahagian c 2011 ppt
Bahagian c 2011 pptshafee1971
 
Curso ceibal
Curso ceibalCurso ceibal
Curso ceibal
elidabrenda
 
#3 media validation training 2013
#3 media validation training 2013#3 media validation training 2013
#3 media validation training 2013
kparkerslmc
 
Action Research
Action Research Action Research
Action Research
kparkerslmc
 

Viewers also liked (6)

J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Bahagian c 2011 ppt
Bahagian c 2011 pptBahagian c 2011 ppt
Bahagian c 2011 ppt
 
Curso ceibal
Curso ceibalCurso ceibal
Curso ceibal
 
#3 media validation training 2013
#3 media validation training 2013#3 media validation training 2013
#3 media validation training 2013
 
Rubric
RubricRubric
Rubric
 
Action Research
Action Research Action Research
Action Research
 

Similar to Hibernate

Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
Jonathan Wage
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
Lukas Smith
 
Pom
PomPom
Pom
akmini
 
Pom configuration java xml
Pom configuration java xmlPom configuration java xml
Pom configuration java xml
akmini
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
Gary Hockin
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
Muhammad Zeeshan
 
How to create a skeleton of a Java console application
How to create a skeleton of a Java console applicationHow to create a skeleton of a Java console application
How to create a skeleton of a Java console application
Dmitri Pisarenko
 
Java JDBC
Java JDBCJava JDBC
Jdbc
JdbcJdbc
GradleFX
GradleFXGradleFX
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
Jini Lee
 
J boss
J bossJ boss
J boss
jrfx448
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.ivanov
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
Lindsay Holmwood
 
JDBC
JDBCJDBC
Struts database access
Struts database accessStruts database access
Struts database access
Abass Ndiaye
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
Xebia IT Architects
 

Similar to Hibernate (20)

Dropwizard
DropwizardDropwizard
Dropwizard
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Pom
PomPom
Pom
 
Pom configuration java xml
Pom configuration java xmlPom configuration java xml
Pom configuration java xml
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
How to create a skeleton of a Java console application
How to create a skeleton of a Java console applicationHow to create a skeleton of a Java console application
How to create a skeleton of a Java console application
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
GradleFX
GradleFXGradleFX
GradleFX
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
 
J boss
J bossJ boss
J boss
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
JDBC
JDBCJDBC
JDBC
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 

Hibernate

  • 1. Hibernate KSA-in Project AUG 25st 2012 프로젝트 상위기획 KSA-in Project Team
  • 2. 00 Contents 01. Hibernate? 02. Spring+maven+mysql+hibernate 03. Basic O/R mapping 04. Association mappings
  • 3. 01 Hibernate? • POJO-style domain models • Object/Relational Mapping • Remove or encapsulate vendor-specific SQL code • http://hibernate.org/ • http://docs.jboss.org/hibernate/orm/4.1/quickstart/en-US/html_single/#d5e25
  • 4. 02 Spring+maven+mysql 1. Spring Hello world tutorial 2. Download and install MySQL <mysql-version>5.1.21</mysql-version> 3. Maven config – pom.xml <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-version}</version> </dependency>
  • 5. 02 Spring+maven+mysql (Simple example using JDBC) CREATE SCHEMA ` helloworld` ; public User get(String id) throws ClassNotFoundException, SQLException { CREATE TABLE ` helloworld` .` users` ( User user = new User(); ` uid` INT NOT NULL , ` id` VARCHAR(45) NOT NULL , Connection c = getConnection(); ` password` VARCHAR(45) NOT NULL , PreparedStatement ps = c.prepareStatement("select * from users PRIMARY KEY (` uid` ) where id=?"); ); ps.setString(1, id); ResultSet rs = ps.executeQuery(); rs.next(); user.setUid(rs.getInt("uid")); user.setId(rs.getString("id")); user.setPassword(rs.getString("password")); rs.close(); ps.close(); c.close(); return user; } private Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection c = DriverManager.getConnection("jdbc:mysql://localhost/helloworld ", "njurn", “123123"); return c; }
  • 6. 02 Spring+maven+mysql+hibernate <mysql-version>5.1.21</mysql-version> <!– Spring orm --> <dependency> <groupId>org.springframework</groupId> 1. Add maven dependency <pom.xml> <artifactId>spring-orm</artifactId> <version>${springframework-version}</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> 2. Add config files <artifactId>hibernate-core</artifactId> 1) resources/properties/database.properties <version>${hibernate-version}</version> </dependency> 2) resources/database/DataSource.xml <dependency> 3) resources/database/Hibernate.xml <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> <scope>runtime</scope> </dependency> 3. Modify <root-context.xml> <!-- Hibernate Configurations --> <import resource="classpath:database/DataSource.xml"/> <import resource="classpath:database/Hibernate.xml"/> • http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/ • http://www.mkyong.com/spring/maven-spring-hibernate-annotation-mysql-example/ • http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single #d5e4729
  • 7. 02 Spring+maven+mysql+hibernate (Simple hibernate example) @Entity @Table(name = "stock") public class Stock { @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "STOCK_ID", unique = true, nullable = false) public Integer stockId; @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10) public String stockCode; @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20) public String stockName; } SessionFactory sessionFactory; /* Insert */ Stock stock = new Stock(); stock.stockCode = "abcd"; stock.stockName = "temp1"; sessionFactory.getCurrentSession(). save(stock); /* Update */ stock2.stockName = "temp2"; sessionFactory.getCurrentSession(). update(stock2);
  • 8. 03 Basic O/R mapping import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.GeneratedValue; Import javax.persistence.GenerationType; import javax.persistence.Column; … @Entity Type Element Summary String name The name of an entity. @Table Type Element Summary String catalog (Optional) The catalog of the table. String name (Optional) The name of the table. String schema (Optional) The schema of the table. UniqueConstraint[] uniqueConstraints (Optional) Unique constraints that are to be placed on the table. • http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
  • 9. 03 Basic O/R mapping @Column Type Element Summary String columnDefinition (Optional) The SQL fragment that is used when generating the DDL for the column. boolean insertable (Optional) Whether the column is included in SQL INSERT statements generated by the persistence provider. int length (Optional) The column length. String name (Optional) The name of the column. boolean nullable (Optional) Whether the database column is nullable. int precision (Optional) The precision for a decimal (exact numeric) column. int scale (Optional) The scale for a decimal (exact numeric) column. String table (Optional) The name of the table that contains the column. boolean unique (Optional) Whether the property is a unique key. boolean updatable (Optional) Whether the column is included in SQL UPDATE statements generated by the persistence provider. • http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
  • 10. 03 Basic O/R mapping http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
  • 11. 04 Association mappings (One-to-One) @Entity @Entity public class Stock { public class StockDetail { @Id @Id Integer stockId; Integer stockId; @OneToOne ( @OneToOne(fetch = FetchType.LAZY) fetch = FetchType.LAZY, @PrimaryKeyJoinColumn mappedBy = "stock", Stock stock; cascade = CascadeType.ALL ) ... StockDetail stockDetail; } ... } • http://www.mkyong.com/hibernate/hibernate-one-to-one-relationship-example-annotation/
  • 12. 04 Association mappings (One-to-Many) @Entity @Entity @Table(name = "stock“) public class StockDailyRecord { public class Stock { @Id @Id Integer recordId; Integer stockId; @ManyToOne(fetch = FetchType.LAZY) @OneToMany( @JoinColumn( fetch = FetchType.LAZY, name = "STOCK_ID", mappedBy = "stock") nullable = false) Set<StockDailyRecord> stockDailyRecords; Stock stock; ... ... } } • http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/
  • 13. 04 Association mappings (Many-to-Many) @Entity @Entity @Table(name = "stock“) public class Category { public class Stock { @Id @Id Integer categoryId; Integer stockId; @ManyToMany( @ManyToMany( fetch = FetchType.LAZY, fetch = FetchType.LAZY, mappedBy = "categories")) cascade = CascadeType.ALL) Set<Stock> stocks; @JoinTable(name = "stock_category", ... catalog = "mkyongdb", } joinColumns = { @JoinColumn( name = "STOCK_ID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn( name = "CATEGORY_ID", nullable = false, updatable = false) }) Set<Category> categories; ... } • http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/
  • 14. 05 Others (Transaction) import org.springframework.transaction.annotation.Transactional; @Transactional public void testSaveAndGet() { String username = "test"; User user = new User(); user.username = username; user.password = ""; user.koreanName = “test"; long id = userDao.save(user); user = userDao.get(id); assertEquals("Saved user and retrieved user should have the same username", username, user.username); } … xmlns:tx="http://www.springframework.org/schema/tx" … <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
  • 15. 05 Others (hbm2ddl.auto) Value Explanation create Session factory가 실행될 때에 스키마를 지우고 다시 생성합니다. 스키마를 생성한 다음 에 classpath에서 import.sql 파일이 있는지 찾아 이 파일에 등록된 쿼리문을 실행합니다. create-drop create와 같지만 session factory가 내려갈 때 DB의 스키마를 삭제합니다. update 시작하면서 도메인 객체 구성과 DB의 스키마를 비교해 필요한 테이블이나 칼럼이 없을 때 도메인 객체에 맞춰 DB 스키마를 변경합니다. 데이터나 스키마를 지우지는 않습니다. validate 처음에 도메인 객체 구성과 DB 스키마가 같은지 확인만 할 뿐 DB 스키마에 전혀 손대지 않습니다. SessionFactory 시작 시 확인을 해서 문제가 있으면 예외를 토해내고 죽습니다. • http://gyumee.egloos.com/2483659
  • 16. 05 Others (Documents) Hibernate docs http://docs.jboss.org/hibernate/orm/4.1/quickstart/en-US/html/ http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ http://docs.jboss.org/hibernate/orm/4.1/javadocs/ Persistence annotation http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html Configuration properties http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e4729
  • 17. 06 The end