Chapter 06 데이터베이스 연동 지원 작성자 : 장은호 소속팀 : 네이버메인개발 작성년월일 : 2009.08.26.

Slides:



Advertisements
Similar presentations
5 Copyright © 2005, Oracle. All rights reserved. Accessing the Database with Servlets.
Advertisements

1 juni 30, 2005 Spring JDBC. 2 juni 30, 2005 Doel Database acties Flexibel Gecontroleerd Productief.
Exercises of the Tutorial on Advanced Web Programming Authors: Miroslava Mitrovic Dragan Milicev Nino.
Ch 7. Spring EL (Spring Framework 3.0 M3) 백기선
19 augustus 2003augustus 2003 JSP-2. BICT 2JDBC BICT 3Install MySQL Download MySQL daemon – Free – Windows version… Start Daemon – Mysqld-nt.exe Download.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
Introduction to XML CS348 Information System Guest Lecture Hazem Elmeleegy.
JDBC Dr Jim Briggs. WEBP JDBC2 JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets) to databases Largely.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 Lecture 05: Database Programming (JDBC). 2 Outline JDBC overview JDBC API Reading: Chapter 10.5 Pointbase Developer Manual.
Object-Oriented Enterprise Application Development Introduction to JDBC.
Three-Tier Architecture Oracle DB Server Apache Tomcat App Server Microsoft Internet Explorer HTML Tuples HTTP Requests JDBC Requests Java Server Pages.
UPortal Developers MIT August 2004 Persistence Strategy for uPortal 3 Mike DeSimone the r-smart group
Implement distributed transations Management in the Campus System Zhuo Zeng.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
SOAP 실전예제 Internet Computing KUT Youn-Hee Han.
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
HR B DD HRB 아카이브 + xxx.jar EJB. Service EJB Engine JNDI B DD.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
Database Programming using JSP and MySQL Byung-Hyun Ha
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
1 JDBC Resource Registration on WebSphere Console javax.naming.InitialContext ctx = new javax.naming.InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("jdbc/DB2UDB");
1 KC Web & Java – 29 november 2005 – Design Patterns – The Template Method AJAX! KC Web & Java 29 november 2005.
Spring Data Access By, Srinivas Reddy.S
 What software components are required?  How do I install the Oracle JDBC driver?  How do I connect to the database?  What form is the data in and.
CS 160: Software Engineering October 1 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
Spring Database Access Ojitha Kumanayaka Copyright © Virtusa, 2007.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
이경화 Ch13. 웹 프로그래밍 설계 및 실습 MVC2 Member.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
JDBC. A Basic MySQL Tutorial MySQL is an open source database management software that helps users store, organize, and retrieve data. It is a very powerful.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
웹 프로그래밍 설계 및 실습 MVC1 Member 이경화
Presentation On How To Create Connection To A Database.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Tasks Needed for MissionMapEditor Martin Q. Zhao September 18, 2010.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Basics of JDBC.
Text 16 de mayo de 2009 Spring Framework Part III. Portable Service Abstractions Buenos Aires, June 2009.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring JDBC Simplifying.
Connection Pooling 2001/4/3 Kang Seungwoo. Connection Pooling Database Connection cost is very high Connection Pool DB 와 연결된 여러 개의 Connection 객체를 미리 확보.
방명록 제작. 목차  기본 레이아웃  DB 구조  방명록 구조  코드 설명  화면 설명.
JDBC I IS Why do we have databases?
Spring in Action Craig Walls Gateway Software Symposium 2007 Blog: Wiki:
Using Oracle JDBC How to Run JDBC on Your Account Communication Mechanism Using Metadata Building a Database Auto Commit v.s Atomic Transaction.
JSP/Database Connectivity Instructor: Dr. M. Anwar Hossain.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
ㅇ 데이터베이스 연동 지원 - 템플릿 클래스를 통한 데이터 접근 지원 - 의미있는 예외 클래스 제공 - 트랜잭션 처리 ㅇ Connection / PreparedStatement / ResultSet / try-catch 등 JDBC 중복 코드 제거 JDBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
JDBC 15-Apr-18.
JDBC 21-Aug-18.
JDBC 15-Nov-18.
Bolat Azamat, Kim Dongmin
Using a Database with JDBC
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Chapter 06 데이터베이스 연동 지원 작성자 : 장은호 소속팀 : 네이버메인개발 작성년월일 :

목차 1. 스프링의 데이터베이스 연동 지원 2.DataSource 설정 3. 스프링의 JDBC 지원 4.iBATIS/ 하이버네이트 /JPA 연동 지원

1. 스프링의 데이터베이스 연동 지원

 중복된 코드 제거를 위한 템플릿 클래스 제공 (GoF 의 템플릿 패턴 ) Connection conn = null; … try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(“…”); } catch(SQLException e) { … } finally { … if(conn != null) conn.close(); }  DaoSupport : DAO 에서 사용하는 기본적인 기능을 제공, 상속받아서 사용  구체적인 Exception 을 발생시킴

2. DataSource 설정

2.1. 커넥션 풀을 이용한 Datasource 설정 <bean id="dataSource” class="org.apache.commons.dbcp.BasicDataSource" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost/test" p:userName="test" p:password="1234" />  dataSource : DAO 가 데이터에 접근하기 위한 포인트  DBCP(Jakarta Commons Database Connection Pool) API(connection library) 이용

2.2. JNDI 를 이용한 DataSource 설정 <beans xmlns=" xmlns:jee=" xmlns:p=" xmlns:xsi=" xsi:schemaLocation="  JEE App server, Tomcat, Resin 등 web container 사용하는 경우 태그 사용하여 JNDI 에 등록된 객체명 명시

2.3. DriverManager 를 이용한 DataSource 설정 <bean id=“dataSource“ class=“org.springframework.jdbc.dataSource.DriverManagerDataSource” p:driverClassName=“com.mysql.jdbc.Driver” p:url=“jdbc:mysql://localhost/test” p:username=“test” p:password=“root” />

2.4. DataSource 로부터 Connection 구하기 public class JdbcMessageDao omplements MessageDao { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource=dataSource; public int selectCount() { Connection conn=null; try { // conn=dataSource.getConnection(); conn=DataSourceUils.getConnection(dataSource); } finally { // JdbcUtils.closeConnection(conn); datasourceutils.releaseConnection(conn,dataSource); }  DataSource 로부터 Connection 구하기  getConnection() 활용하면 되나 스프링이 제공하는 트랜잭션 관리 기능 활용할 수 없음  이를 방지하기 위해 DataSourceUtils 클래스를 이용하여 connection 을 구하고 반환함.

3. 스프링의 JDBC 지원

3.1. JdbcTemplate 클래스를 이용한 JDBC 프로그래밍 <bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource” p:driverClassName=“com.mysql.jdbc.Driver” p:url=“jdbc:mysql://localhost/test” p:username=“test” p:password=“1234” /> <bean id=“jdbcTemplate” class=“org.springframework.jdbc.core.JdbcTemplate” p:dataSource-ref=“dataSource” /> <bean id=“messageDao” class=“JdbcTemplateMessageDao” p:jdbcTemplate-ref=“jdbcTemplate” /> jdbcTemplate p:dataSource-ref dataSource messageDao p:jdbcTemplate-ref

3.1. JdbcTemplate 클래스를 이용한 JDBC 프로그래밍 Private static final string INSERT_SQL = “insert into GUESTBOOK” + “(GUEST_NAME,CONTENT) values (?,?)”; Public void insert(Message message){ jdbcTemplate.update(INSERT_SQL, new Object[]{message.getGuestName(),message.getContent()}); } private static final String SELECT_SQL = "select * from GUESTBOOK desc limit ?,?"; public List selectList(int page,int size) { List list=jdbcTemplate.query(SELECT_SQL,new Object[] {page, size}, new public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Message message = new Message(); message.setId(rs.getInt("ID")); message.setName(rs.getString("NAME")); message.setContent(rs.getString("CONTENT")); } }); return list; }  List query(SQL query(SELECT), arguments, Results) : Prepared statement  List query(SQL query(SELECT), Results) : 정적 SQL  int update(SQL query(INSERT, UPDATE, DELETE), (arguments)) : Prepared SQL  int update(SQL query(INSERT, UPDATE, DELETE) : static SQL 결과값을 원하는 방식으로 가공하여 리턴

3.2. NamedParameterJdbcTemplate 클래스를 이용한 JDBC 프로그래밍 private static final String SELECT_SQL = "select * from GUESTBOOK desc limit :startRow, :size"; public List selectList(int page,int size) { Map params = new HashMap (); params.put("startRow",startRow); params.put("size",size); List list=jdbcTemplate.query(SELECT_SQL,params, new public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Message message = new Message(); message.setId(rs.getInt("ID")); message.setName(rs.getString("NAME")); message.setContent(rs.getString("CONTENT")); } }); return list; }  이름 기반의 파라미터 설정 (MAP 형식 )

3.3. SimpleJdbcTemplate 클래스를 이용한 JDBC 프로그래밍 private static final String SELECT_SQL = "select * from GUESTBOOK desc limit ?,?"; public List selectList(int page,int size) { List list=jdbcTemplate.query(SELECT_SQL,new ParameterizedRowMapper public Message mapRow(ResultSet rs, int rowNum) throws SQLException { Message message = new Message(); message.setId(rs.getInt("ID")); message.setName(rs.getString("NAME")); message.setContent(rs.getString("CONTENT")); return message; } }, page, size); return list; }  이름 기반의 파라미터 사용 : query(SQL, ParameterizedRowMapper, Map args)  가변 인수 사용 : query(SQL, ParameterizedRowMapper, Object … args)

4. iBATIS/Hibernate/JPA 연동 지원

sqlMapClient dataSource configLocation sqlMapConfig.xml GuestBook.xml sqlMapClient Template sqlMapClient-ref messageDAO sqlMapClient Template-ref dataSource, iBATIS 설정파일 명시 매핑 설정파일을 명시 매핑할 SQL 구문 Template : - 코드 중복을 없애고 -SQLException 을 스프링이 제공하는 예외 클래스로 변환하고 - iBATIS 의 sqlMapClient 와 거의 동일 한 메소드 제공 Template 을 이용해서 실제로 iBATIS 사용 4. iBatis

<bean id="sqlMapClient” class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" p:dataSource-ref="dataSource” p:configLocation="WEB_INF/sqlMap/sqlMapConfig.xml"> <bean id="messageDao” class="org.springframework.orm.ibatis.iBatisMessageDao” p:sqlMapClientTemplate-ref="sqlMapClientTemplate"> <!DOCTYPE sqlMapConfig PUBLIC "-//ibais.apache.org//DTD SQL Map Config 2.0//EN" " <!DOCTYPE sqlMapConfig PUBLIC "-//ibais.apache.org//DTD SQL Map Config 2.0//EN" " <sqlMap namespace="GuestBook" select * from GUESTBOOK_MESSAGE order by GUESTBOOK_MESSAGE_ID desc limit #startRow#, #size#

sessionFactory dataSource mappingResource Message.hbm.xml Hibernate Template sessionFactory-ref messageDAO hibernate Template-ref Session == connection dataSource, Hibernate 설정파일 명시 매핑 정보를 담고 있는 설정파 일 Template : - 코드 중복 (try-catch) 방지 - 스프링이 제공하는 예외에 맞게 변환 Template 을 이용해서 실제 로 Hibernate 사용 4. Hibernate

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean“ hibernate/Message.hbm.xml org.hibernate.dialect.MySQLInnoDBDialect <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate” p:ssesionFactory-ref="ssesionFactory" />

4. Hibernate  Hibernate Session 이 제공하는 메서드 (get(), load(), save() 등 ) 를 동일하게 제공  Hibernate Query 를 생성하지 않고 사용할 수 있는 find() List find(String queryString) List findByNamedParam(String queryString, String[] paramNames, Object[] values)  Hibernate 의 NamedQuery 실행 메소드 findByNamedQuery(String queryName)  Criteria 실행 메소드 List findByCriteria(DetachedCriteria criteria)

Thank you.