Chapter2 j2ee

489 views
314 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
489
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
7
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Chapter2 j2ee

  1. 1. J2EE Java 2 Enterprise Edition.
  2. 2. Overview of J2EE  J2EE stands for Java 2 Enterprise Edition.  J2EE is a platform-independent  Java-centric environment from Sun for developing, building and deploying Web-based enterprise applications online.  The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitier, Web-based applications.
  3. 3.  J2EE architecture supports component-based development of multi-tier enterprise applications.  A J2EE application system typically includes the following tiers: ◦ Client Tier ◦ Web Tier ◦ EJB (Enterprise JavaBeans) Tier ◦ EIS (Enterprise Information Systems) Tier
  4. 4.  Client tier : Client tier consists of programs that interact with the user. It prompts the user for input and then convert the user’s response into requests that are forwarded to software on a component that processes the request and returns results to the client program.  Web tier :- Web tier accepts requests from other software that was sent using POST, GET, and PUT operations, which are part of HTTP transmissions.  The two major components of web tier Servlets and Java Server Pages.
  5. 5.  Enterprise java bean :- Enterprise java bean is a class that contains business logic and callable from a servlet or Jsp. EJB tier contains the enterprise java beans server that stores and manages enterprise java beans. This tier automatically handles concurrency issues that assure multiple clients have simultaneous access to the same object and also manages instances of components.  Enterprise Information Systems:- EIS tier provides flexibility to developers of J2EE applications since it include variety of resources and support connectivity to resources. It defines all the elements that are needed to communicate between J2EE application and non- J2EE software.
  6. 6. Tier  Tier: A tier is an abstract concept that defines a group of technologies that provides one or more services to its clients.  In multi-tier architecture each tier contains services that include software object or DBMS.  Multi-tier architecture is composed of clients, resources, components (service), and containers.  Client: A client refers to a program that requests a service from a component.  Resource: A resource is anything a component needs to provide a service.
  7. 7.  A container handles persistence, resource management, security, threading and other system-level services for components that are associated with the container.  Components are responsible for implementation of business logic. It helps the programmer to focus on coding business rules into components without becoming concerned about low-level system services.  The relationship between client, component and resource is shown below
  8. 8. Java 2 Standard Edition  j2SE is a widely used platform for development and deployment of portable application for desktop and server environment.  J2SE uses object oriented java program language
  9. 9. Difference Between J2EE & J2SE  J2EE is used to develop server-side application such as servlet and jsp.  J2SE is used to develop client side application or desktop application
  10. 10. JDBC  JDBC stands for Java Database Connectivity  JDBC is a standard Java API for database independent connectivity between the Java programming language and a wide range of databases.  JDBC helps you to query a database.  Using JDBC you can also established a connection to a relational database.  The classes and interfaces that make up JDBC can be found in that java.sql package.
  11. 11.  The JDBC library includes APIs for each of the tasks commonly associated with database usage:  Making a connection to a database  Creating SQL or MySQL statements  Executing that SQL or MySQL queries in the database  Viewing & Modifying the resulting records
  12. 12.  JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database.  Java can be used to write different types of executables, such as: ◦ Java Applications ◦ Java Applets ◦ Java Servlets ◦ Java Server Pages (JSPs) ◦ Enterprise JavaBeans (EJBs)  All of these different executables are able to use a JDBC driver to access a database and take advantage of the stored data.
  13. 13. JDBC Components JDBC includes four components:  The JDBC API — The JDBC API provides programmatic access to relational data from the Java programming language.  Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source.  The JDBC API is part of the Java platform, which includes the J2SE and J2EE.  The JDBC 4.0 API is divided into two packages: ◦ java.sql and javax.sql.
  14. 14.  JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.  DriverManager has traditionally been the backbone of the JDBC architecture.  The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface (JNDI) naming service to establish a connection with a data source.  You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.
  15. 15.  JDBC Test Suite — the JDBC driver test suite helps you to determine that JDBC drivers will run your program.  These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.  JDBC-ODBC Bridge — The Java Software Bridge provides JDBC access via ODBC drivers.  Note that you need to load ODBC binary code onto each client machine that uses this driver.  As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in three-tier architecture.
  16. 16. JDBC Architecture
  17. 17. JDBC Driver types There are four categories of drivers by which developer can apply a connection between Client (1) JDBC-ODBC Bridge. (2) Native-API Driver (Partly Java driver). (3) Network-Protocol Driver (Pure Java driver for database Middleware). (4) Native-Protocol Driver (Pure Java driver directly connected to database).
  18. 18. Type 1 Driver: JDBC-ODBC Bridge  The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC methods into ODBC function calls.  The driver is a platform dependent because it uses ODBC which is depends on native libraries of the operating system and also the driver needs other installation for example,  ODBC must be installed on the computer and the database must support ODBC driver.  Type 1 is the simplest compare to all other driver but it’s a platform specific i.e. only on Microsoft platform.  The JDBC-ODBC Bridge is use only when there is no PURE- JAVA driver available for a particular database.
  19. 19. Advantage: 1. Connect to almost any database on any system, for which ODBC driver is installed. 2. Its an easy for installation as well as easy(simplest) to use as compare the all other driver. Disadvantage: 1. The ODBC Driver needs to be installed on the client machine. 2. It is a not a purely platform independent because its use ODBC which is depends on native libraries of the operating system on client machine. 3. Not suitable for applets because the ODBC driver needs to be installed on the client machine.
  20. 20. Type 2 Driver: Native-API Driver (Partly Java driver):-  The JDBC type 2 driver is uses the libraries of the database which is available at client side and this driver converts the JDBC method calls into native calls of the database so this driver is also known as a Native-API driver.
  21. 21. Advantage: 1. There is no implantation of JDBC-ODBC Bridge so it’s faster than a type 1 driver; hence the performance is better as compare the type 1 driver (JDBC-ODBC Bridge). Disadvantage: 1. On the client machine require the extra installation because this driver uses the vendor client libraries. 2. The Client side software needed so cannot use such type of driver in the web-based application. 3. Not all databases have the client side library. 4. This driver supports all JAVA applications except applets.
  22. 22. Type 3 Driver: Network-Protocol Driver (Pure Java driver for database Middleware):-  The JDBC type 3 driver uses the middle tier (application server) between the calling program and the database and this middle tier converts JDBC method calls into the vendor specific database protocol and the same driver can be used for multiple databases also so it’s also known as a Network- Protocol driver as well as a JAVA driver for database middleware.
  23. 23. Advantage: 1. There is no need for the vendor database library on the client machine because the middleware is database independent and it communicates with client. 2. Type 3 driver can be used in any web application as well as on internet also because there is no any software require at client side. 3. A single driver can handle any database at client side so there is no need a separate driver for each database. 4. The middleware server can also provide the typical services such as connections, auditing, load balancing, logging etc. Disadvantage: 1. An Extra layer added, may be time consuming. 2. At the middleware develop the database specific coding, may be increase complexity.
  24. 24. Type 4 Driver: Native-Protocol Driver (Pure Java driver directly connected to database):-  The JDBC type 4 driver converts JDBC method calls directly into the vendor specific database protocol and in between do not need to be converted any other formatted system so this is the fastest way to communicate quires to DBMS and it is completely written
  25. 25. Advantage: 1. It is a 100% pure JAVA Driver so it’s a platform independence. 2. No translation or middleware layers are used so consider as a faster than other drivers. 3. The all process of the application-to-database connection can manage by JVM so the debugging is also managed easily. Disadvantage: 1. There is a separate driver needed for each database at the client side. 2. Drivers are Database dependent, as different database vendors use different network protocols.
  26. 26. JDBC Process The JDBC process consists of 5 steps as below. 1. Loading the JDBC driver. 2. Establish the connection to DBMS. 3. Create and execute the statements. 4. Processing the data returned by DBMS. 5. Close the connection with the DBMS.
  27. 27. Loading the JDBC driver  To load the driver, you need to load the appropriate class, make a driver instance and register it with the JDBC driver manager.  Use Class.forName(String) method.  This method takes a string representing a fully qualified class name and loads the corresponding class. Example: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  28. 28. Establish the connection to DBMS  Once you have loaded the JDBC driver, you need to specify the location of the database server.  Generally, the url format is: jdbc:odbc:studentinfo plus server host, port number and database name.  To make the actual network connection, pass the URL, the database username, and the password to the getConnection( ) method of the DriverManager class, as illustrated in the following example. String username = “bca"; String password = “1234"; Connection con = DriverManager.getConnection(url, username, password);
  29. 29. Create and execute the statements  A Statement object is used to send queries and commands to the database and is created from the Connection. Statement stmt = con.createStatement();  Once you have a Statement object, you can use it to send SQL queries by using the executeQuery method, which returns an object of type ResultSet. String query = "SELECT * FROM student"; ResultSet res = stmt.executeQuery(query);  To modify the database, use executeUpdate( ) instead of executeQuery( ), and supply a string that uses UPDATE, INSERT, or DELETE.
  30. 30. Processing the data returned by DBMS  The simplest way to handle the results is to process them one row at a time, using the ResultSet’s next( ) method to move through the table a row at a time.  Within a row, ResultSet provides various getXxx( ) methods that take a column index or column name as an argument and return the result as a variety of different Java types.  For example, use getInt( ) if the value should be an integer, getString( ) for a String, and so on for most other data types.  If you just want to display the results, you can use getString( ) regardless of the actual column type.  Note that the first column in a ResultSet row has index 1, not 0.
  31. 31. Example: while(res.next()) { System.out.println(res.getString(1) + " " + res.getString(2) + " " + res.getString(3)); }
  32. 32. Close the connection with DBMS  To close the connection explicitly, you should do: con.close( );  You should postpone this step if you expect to perform additional database operations, since the overhead of opening a connection is usually large.  In fact, reusing existing connections is such an important optimization.
  33. 33. JDBC Statements  Once a connection is obtained we can interact with the database.  The java application submits its request using jdbc statements.  The JDBC statement interface defines the methods and properties that enable you to send SQL commands and receive data from your database. There are 3 interfaces:  Statement  PreparedStatement  CallableStatement
  34. 34. Statement  Statement object is used when we are using a static query. It is created using createStatement ( ) method in Connection class. Example: Statement st=null; St=con.createStatement( );  It immediately executes the query without compilation.
  35. 35. PreparedStatement  PreparedStatement object when we are using query with different parameters. So it must be compiled before execution.  The PreparedStatement interface extends the Statement interface which gives you added functionality with a couple of advantages over a generic Statement object.  This statement gives you the flexibility of supplying arguments dynamically.
  36. 36.  PreparedStatement object is created using prepareStatement ( ) in Connection class. PreparedStatement pst = null; String SQL = "Update Student SET name = ? WHERE usn = ?"; pst = conn.prepareStatement(SQL);  All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement.
  37. 37. setXXX( ) methods  The setXXX( ) methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive a SQLException.  setXXX( ) method takes two arguments representing position of marker (?) and value to replace respectively.  Each parameter marker is referred to by its ordinal position.  The first marker represents position 1, the next position 2, and so forth. pst.setString(1, ”Babu”); pst.setString(2,”s105”);
  38. 38. CallableStatement  As a Connection object creates the Statement and PreparedStatement objects, it also creates the CallableStatement object which would be used to execute a call to a database stored procedure.  It is created using prepareCall ( ) method in Connection class. CallableStatement cstmt = null; String SQL = "{call getAllData}"; cstmt = conn.prepareCall (SQL);  Here getAllData is a stored procedure defined in database, which contains multiple SQL queries and gets executed when stored procedure is called.
  39. 39. Executing Statements  Once a Statement object is created, we can use it to execute a SQL statement with one of its three execute methods.  boolean execute(String SQL)  int executeUpdate(String SQL)  ResultSet executeQuery(String SQL)  boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. Example: Statement st=con.createStatement( ); st.execute(“select * from student”);
  40. 40. int executeUpdate(String SQL) :  Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. Example: Statement st=con.createStatement( ); int i=st.executeUpdate(“select * from student”);  Here value of i represent number of records selected.
  41. 41. ResultSet executeQuery(String SQL) :  Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.  Example: Statement st=con.createStatement( ); ResultSet res; res = st.execute(“select * from student”);
  42. 42. ResultSet  The ResultSet object contains the data returned by the database. executeQuery( ) method returns the ResultSet object that contains the data was requested by the query.  The ResultSet object contains methods that are used to copy data from ResultSet into java collection object or variable for further processing.  Data in a ResultSet object is logically organized into a virtual table consisting of rows and columns. In addition to data, it also contains meta data such as column name, column type etc.  The ResultSet uses a virtual cursor to point to a row of a virtual table. A J2EE component must move the virtual cursor to each row and the other methods of ResultSet object to interact with the data stored in columns in that row.
  43. 43.  The virtual cursor is positioned above the first row of the data when the ResultSet is returned by the executeQuery( ) method. So virtual cursor must be moved to first row using next( ) method.  The next( ) method returns a Boolean true if row contains the data, otherwise, a Boolean value false is returned indicating that no more rows exists in the ResultSet.  Once the virtual cursor points to arrow, the getXXX( ) method is used to copy data from the row to variable. Example: Statement stmt = connection.createStatement(); String selectquery = "select * from user"; ResultSet res = stmt.executeQuery(selectquery); while(res.next( )) { System.out.print("User ID :" + res.getInt(1)+ " "); System.out.println("User Name :" + res.getString(2)); }
  44. 44. Scrollable ResultSet  Until JDBC 2.1 API, the virtual cursor can be moved only downwards. Now virtual cursor can be moved backwards or even positioned at a specific row. Such ResultSet are called Scrollable ResultSet.  The statement object that is created using the createStatement( ) of Connection object must be set up to handle a scrollable ResultSet by passing one of the 3 constants below.  TYPE_FORWARD_ONLY:-restricts the cursor movement downward only.  TYPE_SCROLL_SENSITIVE:- permits cursor to move both directions.  TYPE_SCROLL_INSENSITIVE:- permits cursor to move both directions. And makes the ResultSet insensitive to changes made by another J2EE component to data in the table whose rows are reflected in the ResultSet.
  45. 45. Updatable ResultSet  Rows contained in the ResultSet can be updatable similar to how rows in table can be updated.  This is made possible by passing the createStatement ( ) method of the Connection object CONCUR_UPDATABLE. Alternatively, the CONCUR_READ_ONLY constant can be passed to the createStatement ( ) method to prevent the ResultSet being updated. There are 3 ways in which a ResultSet can be changed.  updating values in a row  deleting a row  inserting a new row All of these changes are accomplished by using methods of the Statement object.
  46. 46. Update ResultSet  Once the executeQuery( ) method of the statement object returns a ResultSet, the updateXXX()method is used to change the value of a column in the current row of the ResultSet. XXX in updateXXX( ) replaced with the data type of the column that is to be updated.  updateXXX( ) requires 2 arguments. First is either a number or name of the column, and the second parameter is the value that will replace.  A value in a column can be replaced with NULL value by using updateNull( ) method. It takes one parameter that is the column number in the current row of the ResultSet. It doesn’t accept the column name as a parameter.
  47. 47.  The updateRow( ) method is called after updateXXX( ) methods are called.  The updateRow( ) changes the values in the columns of current row of the ResultSet based on the values of updateXXX( ) methods.  Example: result.updateInt(1, 105); result.updateString(2, "Anil"); result.updateRow();
  48. 48. Insert ResultSet  Inserting a row into the ResultSet is accomplished using same technique as is used in update the ResultSet.  The updateXXX( ) is used to specify the column and value that will be placed into the column of the ResultSet.
  49. 49.  The insertRow( ) method is called after the updateXXX( ) methods, which causes a new row to be inserted into the ResultSet having the values that reflect the parameters in the updateXXX( ) methods. Example: result.updateInt(1, 115); result.updateString(2, "Naveen"); result.insertRow();
  50. 50. Delete a row in ResultSet  The deleteRow( ) method is used to remove a row from a ResultSet. It is used to eliminate rows in processing. The deleteRow( ) method is passed an integer that contains the number of the row to be deleted.  A good practice is to use the absolute( ) method to move the cursor to the row in the ResultSet that should be deleted. The deleteRow( ) method is then passed a zero integer indicating the current row must be deleted. Example: result.absolute(3); result.deleteRow(0);
  51. 51. JDBC Transaction Processing  If your JDBC Connection is in auto-commit mode, which it is by default, then every SQL statement is committed to the database upon its completion.  That may be fine for simple applications, but there are three reasons why you may want to turn off auto-commit and manage your own transactions:  To increase performance  To maintain the integrity of business processes  To use distributed transactions
  52. 52.  To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method.  If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again. For example, if you have a Connection object named conn, code the following to turn off autocommit: conn.setAutoCommit(false);
  53. 53. Commit & Rollback  Once you are done with your changes and you want to commit the changes then call commit() method on connection object as follows: conn.commit( );  Otherwise, to roll back updates to the database made using the Connection named conn, use the following code: conn.rollback( );
  54. 54. Example: try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String SQL = "INSERT INTO Employees " + "VALUES (106, 'Diya')"; stmt.executeUpdate(SQL); // If there is no error. conn.commit(); } catch(SQLException se) { // If there is any error. conn.rollback(); }
  55. 55. Meta Data  Meta data is data about data. J2EE component can access metadata by using Metadata interface.  In JDBC there are 2 Metadata interfaces available.  DatabaseMetaData  ResultSetMetaData
  56. 56. DatabaseMetaData  A J2EE component retrieves the metadata about the database by calling the getMetaData( ) method of Connection object.  The getMetaData( ) method returns a DatabaseMetaData object that contains the information about the database and its components.  DatabaseMetaData dm = connection.getMetaData();  Once the DatabaseMetaData object is obtained, we can call methods on it to obtain the meta data about the database.
  57. 57. ResultSetMetaData  A J2EE component retrieves the metadata about the ResultSet by calling the getMetaData( ) method of ResultSet object.  The getMetaData( ) method returns a ResultSetMetaData object that contains the information about the ResultSet. ResultSet res; ResultSetMetaData rm = res.getMetaData();  Once the ResultSet metadata is retrieved, the J2EE component can call methods of ResultSetMetaData object to retrieve Specific Meta data.
  58. 58. JDBC Data Types  The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the database. It uses a default mapping for most data types.  For example, a Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency between drivers.  The following table summarizes the default JDBC data type that the Java data type is converted to when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method.
  59. 59. JDBC Exceptions  Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion.  JDBC Exception handling is very similar to Java Exception handling but for JDBC, the most common exception is SQLException.  There are 3 kinds of exceptions that are thrown by JDBC methods:  SQLException  SQLWarning  DataTruncation Exception
  60. 60. SQLException  SQLException commonly reflect a SQL syntax error in the query and thrown by many of methods contained in the java.sql package. This exception is most commonly caused by connectivity issues with the database.  A SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause.  The passed SQLException object has the following methods available for retrieving additional information about the exception:
  61. 61. SQLWarning The SQLWarning throws warnings received by the connection from the DBMS. The getWarning( ) method of Connection object retrieves the warning and getNextWarning( )method of the Connection object retrieves subsequent warnings. DataTruncation Exception A DataTruncation exception is thrown whenever data is lost due to truncation of the data value.

×