Working with database
Agenda
• Building web application using JDBC
• Handling Exception
• Using JNDI with JDBC
• Using ServletConfig in an application
• Using ServletContext
• Understanding JPA
JDBC Revisited
JDBC provides a standard library for accessing relational
databases
– API standardizes
• Way to establish connection to database
• Approach to initiating queries
• Method to create stored (parameterized) queries
• The data structure of query result (table)
JDBC Revisited
JDBC provides a standard library for accessing relational
databases
– Determining the number of columns
– Looking up metadata, etc.
– API does not standardize SQL syntax
• JDBC is not embedded SQL
– JDBC classes are in the java.sql package
• Note: JDBC is not officially an acronym;
unofficially, “Java DataBase Connectivity”
JDBC Drivers
JDBC consists of two parts:
– JDBC API, a purely Java-based API
– JDBC Driver Manager, which communicates with
vendor-specific drivers that perform the real communication
with the database.
• Point: translation to vendor format is performed on the client
– No changes needed to server
– Driver (translator) needed on client
JDBC Data Types
Seven Steps in JDBC
1. Load the driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection
Using Metadata
System-wide data
– connection.getMetaData().getDatabaseProductName()
– connection.getMetaData().getDatabaseProductVersion()
• Table-specific data
– resultSet.getMetaData().getColumnCount()
• When using the result, remember that the index starts at 1, not
0
– resultSet.getMetaData().getColumnName()
Using Metadata(Example)
public class NorthwindServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
… out.println(docType + …);
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:Northwind";
String username = "";
String password = ""; String tableName =
request.getParameter("tableName");
if ((tableName == null) || (tableName.equals("")))
{
tableName = "employees";
}
showTable(driver, url, username, password,
tableName, out);
out.println("</CENTER></BODY></HTML>");
Using Metadata(Example) cont
private void showTable(String driver,
String url,
String username,
String password,
String tableName,
PrintWriter out) {
try {
Class.forName(driver);
Connection connection =
DriverManager.getConnection(url, username,
password);
DatabaseMetaData dbMetaData =
connection.getMetaData();
out.println("<UL>");
String productName =
dbMetaData.getDatabaseProductName();
out.println(" <LI><B>Database:</B> " +
productName);
String productVersion =
dbMetaData.getDatabaseProductVersion();
out.println(" <LI><B>Version:</B> " +
Using Metadata(Example) cont
• Statement statement = connection.createStatement();
• String query =
• "SELECT * FROM " + tableName;
• ResultSet resultSet = statement.executeQuery(query);
• out.println("<TABLE BORDER=1>");
• ResultSetMetaData resultsMetaData =
• resultSet.getMetaData();
• int columnCount = resultsMetaData.getColumnCount();
• out.println("<TR>");
• for(int i=1; i<columnCount+1; i++) {
• out.print("<TH>" +
• resultsMetaData.getColumnName(i));
• }
• out.println();
• while(resultSet.next()) {
• out.println("<TR>");
• for(int i=1; i<columnCount+1; i++) {
• out.print("<TD>" + resultSet.getString(i));
Using Metadata Output
Using JNDI
• • Idea
• – Use abstract name to get connection from a data source
• • Advantages
• – Lets you change data source without changing code
• – Available in multiple Web apps
• • Disadvantage
• – Requires server-specific registration of data source
• • Code for steps 1-3 replaced by:
• Context context = new InitialContext();
• DataSource dataSource = (DataSource)context.lookup
• ("java:comp/env/jdbc/dbName");
• Connection connection = dataSource.getConnection();
Configuring DataSource for JNDI
• Inside tomcat_dir/conf/server.xml
<DefaultContext reloadable="true">
<Resource name="jdbc/Northwind"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/Northwind">
<parameter>
<name>factory</name>
<value>
org.apache.commons.dbcp.BasicDataSourceFactory
</value>
</parameter>
<parameter><name>driverClassName</name>
<value>sun.jdbc.odbc.JdbcOdbcDriver</value>
</parameter>
<parameter><name>url</name>
<value>jdbc:odbc:Northwind</value></parameter
<parameter><name>username</name>
<value></value></parameter>
<parameter><name>password</name>
<value></value></parameter>
Transactions
Tranactions
– By default, after each SQL statement is executed the
changes are automatically committed to the database
– Turn auto-commit off to group two or more statements
together into a transaction
connection.setAutoCommit(false)
– Call commit to permanently record the changes to the
database after executing a group of statements
– Call rollback if an error occurs
Transactions example
Connection connection =
DriverManager.getConnection(url, username, passwd);
connection.setAutoCommit(false);
try {
statement.executeUpdate(...);
statement.executeUpdate(...);
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException sqle) {
// report problem
}
} finally {
try {
connection.close();
} catch (SQLException sqle) { }
}
Transactions
• getAutoCommit/setAutoCommit
– By default, a connection is set to auto-commit
– Retrieves or sets the auto-commit mode
• commit
– Force all changes since the last call to commit to become
permanent
– Any database locks currently held by this Connection
object are released
• rollback
– Drops all changes since the previous call to commit
– Releases any database locks held by this Connection object
Using ServletConfig and Servlet
• Use ServletConfig for Servlet Specifc Information
• Use ServletContext for Application Specific Information
• Configure Driver Information
• Configure URL information
• Use ServletConfig to read the data from init parameter
• Use ServletContext to read the data from context parameter
Introduction to JPA
• What is ORM
• Become acquainted with the Java Persistence API (JPA)
• Learn how to setup and use JPA
What is ORM
•ORM stands for Object Relational Mapping
• POJO’s directly mapped to Database tables
• ORM framework takes care of
- Synchronization
- Transaction
- Performance
- Database Independence
JPA Architecture
Main Components of JPA
•Entity Classes
• Entity Manager
– Persistence Context
• EntityManagerFactory
• EntityTransaction
• Persistence Unit
– persistence.xml
• Java Persistence Query Language
(JPAQL)
– Query
Persistence Unit
•Defines all entity classes that are managed by JPA
• Identified in the persistence.xml configuration file
• Entity classes and configuration files are packaged together
– The JAR or directory that contains the persistence.xml is called the root of
the persistence unit
– Needs to be inside a META-INF directory
• Whether or not inside a jar
Benefits of ORM
•No need to deal with the SQL Queries to save and retrieve the data
•Simple configuration
•Standardized API to persist the business objects
•Fast development of application
•Concurrency support
•Excellent cashing support for better performance of the
application
•Injected transaction management
•Configurable logging
•Easy to learn and use
Drawback of ORM
•Slow performance in case of large batch updates
• Little slower than JDBC
Summary
• We can connect directly to the database or to a database registered
in an Directory Service
• Use init parameter and Context parameter for database specific
configuration information
• JPA is a standard ORM specification
• JPA can take care of boiler plate code like
- Try catch block
- Obtaining Connection
- Mapping of Datatypes
- Synchronizing models with tables

Advance java session 5

  • 1.
  • 2.
    Agenda • Building webapplication using JDBC • Handling Exception • Using JNDI with JDBC • Using ServletConfig in an application • Using ServletContext • Understanding JPA
  • 3.
    JDBC Revisited JDBC providesa standard library for accessing relational databases – API standardizes • Way to establish connection to database • Approach to initiating queries • Method to create stored (parameterized) queries • The data structure of query result (table)
  • 4.
    JDBC Revisited JDBC providesa standard library for accessing relational databases – Determining the number of columns – Looking up metadata, etc. – API does not standardize SQL syntax • JDBC is not embedded SQL – JDBC classes are in the java.sql package • Note: JDBC is not officially an acronym; unofficially, “Java DataBase Connectivity”
  • 5.
    JDBC Drivers JDBC consistsof two parts: – JDBC API, a purely Java-based API – JDBC Driver Manager, which communicates with vendor-specific drivers that perform the real communication with the database. • Point: translation to vendor format is performed on the client – No changes needed to server – Driver (translator) needed on client
  • 6.
  • 7.
    Seven Steps inJDBC 1. Load the driver 2. Define the Connection URL 3. Establish the Connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection
  • 8.
    Using Metadata System-wide data –connection.getMetaData().getDatabaseProductName() – connection.getMetaData().getDatabaseProductVersion() • Table-specific data – resultSet.getMetaData().getColumnCount() • When using the result, remember that the index starts at 1, not 0 – resultSet.getMetaData().getColumnName()
  • 9.
    Using Metadata(Example) public classNorthwindServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); … out.println(docType + …); String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String url = "jdbc:odbc:Northwind"; String username = ""; String password = ""; String tableName = request.getParameter("tableName"); if ((tableName == null) || (tableName.equals(""))) { tableName = "employees"; } showTable(driver, url, username, password, tableName, out); out.println("</CENTER></BODY></HTML>");
  • 10.
    Using Metadata(Example) cont privatevoid showTable(String driver, String url, String username, String password, String tableName, PrintWriter out) { try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, username, password); DatabaseMetaData dbMetaData = connection.getMetaData(); out.println("<UL>"); String productName = dbMetaData.getDatabaseProductName(); out.println(" <LI><B>Database:</B> " + productName); String productVersion = dbMetaData.getDatabaseProductVersion(); out.println(" <LI><B>Version:</B> " +
  • 11.
    Using Metadata(Example) cont •Statement statement = connection.createStatement(); • String query = • "SELECT * FROM " + tableName; • ResultSet resultSet = statement.executeQuery(query); • out.println("<TABLE BORDER=1>"); • ResultSetMetaData resultsMetaData = • resultSet.getMetaData(); • int columnCount = resultsMetaData.getColumnCount(); • out.println("<TR>"); • for(int i=1; i<columnCount+1; i++) { • out.print("<TH>" + • resultsMetaData.getColumnName(i)); • } • out.println(); • while(resultSet.next()) { • out.println("<TR>"); • for(int i=1; i<columnCount+1; i++) { • out.print("<TD>" + resultSet.getString(i));
  • 12.
  • 13.
    Using JNDI • •Idea • – Use abstract name to get connection from a data source • • Advantages • – Lets you change data source without changing code • – Available in multiple Web apps • • Disadvantage • – Requires server-specific registration of data source • • Code for steps 1-3 replaced by: • Context context = new InitialContext(); • DataSource dataSource = (DataSource)context.lookup • ("java:comp/env/jdbc/dbName"); • Connection connection = dataSource.getConnection();
  • 14.
    Configuring DataSource forJNDI • Inside tomcat_dir/conf/server.xml <DefaultContext reloadable="true"> <Resource name="jdbc/Northwind" auth="Container" type="javax.sql.DataSource"/> <ResourceParams name="jdbc/Northwind"> <parameter> <name>factory</name> <value> org.apache.commons.dbcp.BasicDataSourceFactory </value> </parameter> <parameter><name>driverClassName</name> <value>sun.jdbc.odbc.JdbcOdbcDriver</value> </parameter> <parameter><name>url</name> <value>jdbc:odbc:Northwind</value></parameter <parameter><name>username</name> <value></value></parameter> <parameter><name>password</name> <value></value></parameter>
  • 15.
    Transactions Tranactions – By default,after each SQL statement is executed the changes are automatically committed to the database – Turn auto-commit off to group two or more statements together into a transaction connection.setAutoCommit(false) – Call commit to permanently record the changes to the database after executing a group of statements – Call rollback if an error occurs
  • 16.
    Transactions example Connection connection= DriverManager.getConnection(url, username, passwd); connection.setAutoCommit(false); try { statement.executeUpdate(...); statement.executeUpdate(...); connection.commit(); } catch (Exception e) { try { connection.rollback(); } catch (SQLException sqle) { // report problem } } finally { try { connection.close(); } catch (SQLException sqle) { } }
  • 17.
    Transactions • getAutoCommit/setAutoCommit – Bydefault, a connection is set to auto-commit – Retrieves or sets the auto-commit mode • commit – Force all changes since the last call to commit to become permanent – Any database locks currently held by this Connection object are released • rollback – Drops all changes since the previous call to commit – Releases any database locks held by this Connection object
  • 18.
    Using ServletConfig andServlet • Use ServletConfig for Servlet Specifc Information • Use ServletContext for Application Specific Information • Configure Driver Information • Configure URL information • Use ServletConfig to read the data from init parameter • Use ServletContext to read the data from context parameter
  • 19.
    Introduction to JPA •What is ORM • Become acquainted with the Java Persistence API (JPA) • Learn how to setup and use JPA
  • 20.
    What is ORM •ORMstands for Object Relational Mapping • POJO’s directly mapped to Database tables • ORM framework takes care of - Synchronization - Transaction - Performance - Database Independence
  • 21.
  • 22.
    Main Components ofJPA •Entity Classes • Entity Manager – Persistence Context • EntityManagerFactory • EntityTransaction • Persistence Unit – persistence.xml • Java Persistence Query Language (JPAQL) – Query
  • 23.
    Persistence Unit •Defines allentity classes that are managed by JPA • Identified in the persistence.xml configuration file • Entity classes and configuration files are packaged together – The JAR or directory that contains the persistence.xml is called the root of the persistence unit – Needs to be inside a META-INF directory • Whether or not inside a jar
  • 24.
    Benefits of ORM •Noneed to deal with the SQL Queries to save and retrieve the data •Simple configuration •Standardized API to persist the business objects •Fast development of application •Concurrency support •Excellent cashing support for better performance of the application •Injected transaction management •Configurable logging •Easy to learn and use
  • 25.
    Drawback of ORM •Slowperformance in case of large batch updates • Little slower than JDBC
  • 26.
    Summary • We canconnect directly to the database or to a database registered in an Directory Service • Use init parameter and Context parameter for database specific configuration information • JPA is a standard ORM specification • JPA can take care of boiler plate code like - Try catch block - Obtaining Connection - Mapping of Datatypes - Synchronizing models with tables