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        ...
01     Hibernate?  • POJO-style domain models  • Object/Relational Mapping  • Remove or encapsulate vendor-specific SQL co...
02     Spring+maven+mysql     1. Spring Hello world tutorial     2. Download and install MySQL                            ...
02     Spring+maven+mysql (Simple example using JDBC)     CREATE SCHEMA ` helloworld` ;              public User get(Strin...
02     Spring+maven+mysql+hibernate                                                                             <mysql-ver...
02     Spring+maven+mysql+hibernate (Simple hibernate example)     @Entity     @Table(name = "stock")     public class Sto...
03     Basic O/R mapping     import   javax.persistence.Entity;     import   javax.persistence.Table;     import   javax.p...
03     Basic O/R mapping    @Column          Type               Element                                                Sum...
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     publ...
04     Association mappings (One-to-Many)     @Entity                                                     @Entity     @Tab...
04     Association mappings (Many-to-Many)     @Entity                                                     @Entity     @Ta...
05     Others (Transaction)     import org.springframework.transaction.annotation.Transactional;     @Transactional     pu...
05     Others (hbm2ddl.auto)                 Value                                  Explanation                 create    ...
05     Others (Documents)     Hibernate docs        http://docs.jboss.org/hibernate/orm/4.1/quickstart/en-US/html/        ...
06     The end
Upcoming SlideShare
Loading in …5
×

Hibernate

793 views

Published on

하이버네이트 스터디 슬라이드

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
793
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
14
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Hibernate

  1. 1. Hibernate KSA-in Project AUG 25st 2012 프로젝트 상위기획 KSA-in Project Team
  2. 2. 00 Contents 01. Hibernate? 02. Spring+maven+mysql+hibernate 03. Basic O/R mapping 04. Association mappings
  3. 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. 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. 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. 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. 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. 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. 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. 10. 03 Basic O/R mapping http://docs.oracle.com/javaee/5/api/javax/persistence/package-summary.html
  11. 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. 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. 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. 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. 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. 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. 17. 06 The end

×