CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 18 George Koutsogiannakis/Spring 2011 1 Topics • Registering a database with the IDE. • Creating a Derby Data Source. – Create Tables with SQL scripting. – Create Tables using a Dialog Box. • Building a Persistence Unit with NetBeans. • Web Tier Persistence. • EJB Tier Persistence. 2 Databases • NetBeans comes with Derby database (visible in the services window). – New databases ( i.e. MySQL, Oracle etc) can be added but they need to register with the IDE. • Once a database is registered, a data source or connection can be created or a connection to an existing data source can be opened. • Once the data source is created a Persistence Unit can be created. 3 Java DB (Derby) • The Java DB database is Sun's supported distribution of the open source Apache Derby database. • Java DB is a fully transactional, secure, standards-based database server, written fully in the Java programming language, and fully supports SQL, JDBC API, and Java EE technology. 4 Java DB (Derby) • The Java DB database server is bundled with the Sun Java System Application Server/Glassfish. • If you install the Sun Java Application Server/GlassFish during the IDE installation, the Java DB database server is automatically registered in the IDE. 5 Registering A Data Source • First make sure that the proper drivers are registered with the IDE. – In services window expand the database node and then expand the drivers node. – Next, you need to register a connection to your data source: 6 Drivers 7 Sample databases • Under Services you will see the Java DB node • You can right click on the name and choose start server to start the database server. • Example of using Derby can be found in http://netbeans.org/kb/docs/ide/java-db.html 8 Sample databases • At least two sample databases are available • You can click on the node of the sample database:jdbc:derby//localhost:1527/sample[ app on API] and expand it to see the tables of the database and their fields : – Right click on the node and click on connect – Then right click on a table’ s name and choose view data 9 Customer Table Fields Query Table Customer data 10 Registering A Data Source-Creating a connection • Right-click the Databases node and choose New Connection. Alternatively, expand the Drivers node, right-click your driver's instance node and choose Connect Using. • Provide the JDBC database URL for the database connection in the Database URL field. – This URL typically begins with jdbc:and a short code name for the driver, followed by another colon. The rest of the URL depends on the type of driver you are using. For example, you might need to specify a host and port; alternatively, the name of a database file might suffice, or an ODBC DSN. – For MySQL, the Database URL might look as follows: • jdbc:mysql://localhost:3306/mydatabase 11 Registering A Data Source-Creating a connection – Provide the user name and password, if required by your database configuration. – Click OK to create the database connection and connect to the database from the IDE. • To disconnect from the database: – Right-click the database connection node and choose Disconnect. 12 Connecting to a database • After you create the database connection you can do the following: – Disconnect and reconnect to the database – Browse the database structure – View data contained in a table in the database 13 Creating A Data Source • A database needs to be registered with NetBeans. • Notice that a number of data sources can be part of the domain of the application. – Each database needs to be registered with a separate JNDI name. – For example, a database name MyDatabase, specify jdbc/MyDatabase as the JNDI name. 14 Creating A Data Source – Specify a table generation strategy for your database. – Click Finish. • When you click Finish, the file persistence.xml opens in the Source Editor. • In the IDE, you can find persistence.xml in the Projects window under the Configuration Files node. In the Files window, persistence.xml is located in the src/conf directory. • When packaged, persistence.xml is located in the META-INF directory of an EJB JAR file or the WEB-INF/classes directory of a WAR file 15 Creating A Derby Data Source First of course the database needs to be created outside the IDE. In services window right click on databases and choose create database In the Create Java DB Database Window: Type a name for the database i.e MyTestDB Type a User Name i.e george Type a Password i.e george Click O.K. Two things will take place 1. The DB server for Derby should be activated 2. The new database name should appear under databases node in services window 16 17 Creating A Derby Data Source • Right-click the MyTestDB node and choose Connect. • If the Connect dialog box appears, type the password that you have set for the database server. – If the Advanced tab of the dialog box opens, click OK to close the dialog box. --> Scroll down to the node for connection that you have just created. The node should have the icon. • Right-click the connection node and choose Execute Command. • In the editor part of the IDE type the SQL script to create the tables of the database : • A sample script is given on the next slides: 18 Creating A Derby Data Source CREATE TABLE WEB_BOOKSTORE_BOOKS (bookId VARCHAR(8), surname VARCHAR(24), firstName VARCHAR(24), title VARCHAR(96), price FLOAT, onSale SMALLINT, calendar_year INT, description VARCHAR(30), inventory INT) PRIMARY KEY (bookId) ); 19 Creating A Derby Data Source INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('201', 'Duke', '', 'My Early Years: Growing up on *7', 30.75, 0, 1995, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('202', 'Jeeves', '', 'Web Servers for Fun and Profit', 40.75, 1, 2000, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('203', 'Masterson', 'Webster', 'Web Components for Web Developers', 27.75, 0, 2000, 'What a cool book.', 20); 20 Creating A Derby Data Source INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('205', 'Novation', 'Kevin', 'From Oak to Java: The Revolution of a Language', 10.75, 1, 1998, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('206', 'Gosling', 'James', 'Java Intermediate Bytecodes', 30.95, 1, 2000, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('207', 'Thrilled', 'Ben', 'The Green Project: Programming for Consumer Devices', 30.00, 1, 1998, 'What a cool book', 20); 21 Creating A Derby Data Source INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('208', 'Tru', 'Itzal', 'Duke: A Biography of the Java Evangelist', 45.00, 0, 2001, 'What a cool book.', 20); 22 23 Creating A Derby Data Source • Next we need to run the script: – Click the Run SQL button () in the toolbar of the Source Editor to run the script. Output of the script should appear in the Output window. • Right-click the connection node of the database and choose refresh. – Expand the node, and expand its Tables subnode. You should see the database tables created. • In the properties window you should have a view of the properties of the table. 24 25 Creating A Derby Data Source • The data sources are located in C:\Documents and Settings\George\.netbeans-derby on my machine. • You can discover the location of your Derby data sources by right clicking on JavaDB (services window) and choosing properties. • By default, the IDE creates the database in the .netbeansderby folder of your home directory. • To change the default location, click Properties in the Create Java DB Database dialog box, or in the Services window, rightclick the Java DB node and choose Properties. Type the new database location in the appropriate field. 26 View Table Data • To view Table data expand the Data Source node • Expand the Tables node – Right click on the name of the Table and choose view data. – The Table data can be viewed as in the next slide: 27 28 Using the Create Table Dialog • We can create a Table via a dialog box without having to write the SQL statements: – This dialog box appears when you right-click a database's Tables node in the Services window and choose Create Table. Using this dialog box, you can create a table, add columns, specify parameters for columns, and select an owner for the table. – The Create Table dialog opens. – In the Table name text field, type the name of the Table – In the first row displayed, select the Key check box. – You are specifying the primary key for your table. All tables found in relational databases must contain a primary key. 29 Using the Create Table Dialog – Note that when you select the Key check box, the Index and Unique check boxes are also automatically selected and the Null check box is deselected. This is because primary keys are used to identify a unique row in the database, and by default form the table index. Because all rows need to be identified, primary keys cannot contain a Null value. – For Column Name, enter id for example. For Data Type, choose SMALLINT for example from the drop-down list, then click the Add Column button. – Keep repeating the procedure adding columns and their data types. • Check. When the check box is selected, the IDE performs a check of the column to determine if it meets the required criteria. 30 Web Client for a Data Source We can create a simple web client that communicates with The Database Server where the Data Source is deployed (Derby) . 31 Web Client for a Data Source • Data that is shared between web components and is persistent between invocations of a web application is usually maintained by a database. • Web components use the Java Persistence API (JPA) to access relational databases. 32 Persistence Unit • A Persistence Unit is a collection of entities (data tables) that are managed together. • A Persistence Unit specifies some or all of: – Persistence provider name i.e. xmlsn=“http://java.sun.com/xml/ns/persistence – Persistence Unit name i.e. name=OnlineStore – Entity class names i.e. org.com.Orders – Database connection URL – Driver – User and password – The type of Entity Manager Object – Other properties of a data source. 33 Persistence Unit • The information about the Persistence Unit is kept in the descriptor file persistence.xml • An Entity Manager object needs to be created that will manage the persistence unit created. 34 Persistence.xml • <persistence> <persistence-unit name="OrderManagement"> <description>This unit manages orders and customers. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. </description> <jta-data-source>jdbc/MyOrderDB</jta-data-source> <jar-file>MyOrderApp.jar</jar-file> <class>com.widgets.Order</class> <class>com.widgets.Customer</class> </persistence-unit> </persistence> 35 Building a Persistence Unit with NetBeans 1. Let us create a new project in NetBeans. Under categories choose Enterprise Application. Allow for ejb and web applications inside the Enterprise Application. – • Let us name the project ExampleEnterpiseApplication Follow the steps in the next slide to create a persistence unit within either the web application or the ejb application of the Enterprise Application project. 36 Building a Persistence Unit with NetBeans • To create a persistence unit (from NetBeans IDE): • In the Projects window, right-click a web or EJB module project node and choose New > Other. • Select Persistence Unit in the Persistence category and click Next. • Specify a unique Persistence Unit Name. In most cases you can keep the default name suggested by the IDE. • Select a persistence provider or library from the drop-down menu, or add a new library by choosing New Persistence Library. Notice that a number of choice providers are shown including CODO (openSource JPA). 37 Building a Persistence Unit with NetBeans • Select a data source from the drop-down menu. The data source can be a JDBC connection or a database connection. To appear in the list, the data source needs to be registered with the IDE. • Select Use Java Transaction APIs if you want the container to manage the entities. – Java Transaction APIs are only available if you are deploying to a Java EE 5 or EE6 container. If you are not deploying to a Java EE 5 or EE6 container, the transaction needs to be managed by the application. For more, see Transaction Types. 38 39 Ejb module of the example project Sample data source is chosen for the example 40 Building a Persistence Unit with NetBeans • When we click finish the persistence.xml file is added to the ejb module part of the project. • Right clicking and choosing edit displays the contents of the file on the editor section of NetBeans 41 Persistence.xml Persistence Unit name and Other information 42 43 Double clicking on the persistence.xml file can allow us to view properties of the file in a graphical type of a presentation. You can change data source, add/delete entity classes etc. 44 Web Tier Management of JPA • Data shared between web components that needs to be persistent, between invocations by the client, needs to be stored in a data source. • In Web Tier management we will use the JPA from the web tier (the web server) • Suppose we have a data source created named Books with a single Table named WEB_BOOKSTORE_BOOKS already populated (from Java EE5 Tutorial). 45 Web Tier Management of JPA • We need to create a Persistence Unit. – It identifies the schema – The name of the Persistence Unit and the transaction type – A jta-data-source element to indicate JTA transactions container managed. • We need to create an entity class to represent eachTable in the database. 46 Web Tier Management of JPA • Entity classes. Entity classes are used to represent tables in a database. The Java Persistence API enables you to use entity classes directly in your web application. • Entity Manager. An entity manager manages the entities and performs database functions. • Persistence Unit. A persistence unit specifies the data source and which entities are managed by the entity manager. 47 Web Tier Management of JPA • About Entity Classes – – – – Each entity class usually represents a table in a relational database. Each instance of an entity corresponds to a row in a table. Persistent fields or properties correspond to columns in a table. Unlike entity beans, entity classes are not restricted to EJB modules in enterprise applications. Entity classes can be located in an EJB module or a web module. 48 Web Tier Management of JPA • @Entity @Table(name = "WEB_BOOKSTORE_BOOKS") public class Book implements Serializable { @Id private String bookId; private String description; private String firstName; private String surname; private String title; private boolean onSale; …………………………………………. …………………………………………… //constructors and accessor/mutator methods 49 Web Tier Management of JPA • A class BookDB has set and get methods that allow access to Books. • An Application Object of BookDB needs to have access to an Entity Manager object. • The only way to do that is to have a ServletContextListener subclass create the EntityManagerFactory object and pass it to BookDBAO object. – This is called resource injection. Its intend is to have the web container manage the entity bean (which normally is done by the applications server’s container) . 50 EJB Tier Management of JPA • In this case we will have: – A client application (a web application) that communicates with a Session Bean. – The Session Bean carries the Business logic and communicates with the entities. – The entities that persist the data. – Data source. 51 EJB Tier Management of JPA • We can create two applications: – One that holds the session bean and the entities. – One that holds the client application. • It populates the entities with data, retrieves data and displays it. • Opening the Order project (available on the EE5 Tutorial text CD or the course’s web site javaeetutorial5.zip ) and expanding it we get: 52 General Project Files Client Related Files Remote Interface for Session Bean Entity Source files Session Bean Files 53 Client • Client is annotated to work with the Session Bean: public class OrderClient { @EJB • The client creates data and then displays it by getting it back from the data source: public static void main(String[] args) { OrderClient client = new OrderClient(args); try { client.createData(); client.printData(); } catch (Exception ex) {……….} } 54 Client • For example, method createData in Client does operations to populate the data source tables i.e. : private static void createData() { try { request.createPart( "1234-5678-01", 1, "ABC PART", new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null); Where request is a reference of the interface Request and createPart is one of the methods implemented by the Session Bean: RequestBean 55 Session Bean • The Session Bean implements the method createPart: @Stateful public class RequestBean implements Request { @PersistenceContext private EntityManager em; public void createPart( String partNumber, int revision, String description, java.util.Date revisionDate, String specification, Serializable drawing) { 56 Session Bean try { Part part = new Part( partNumber, revision, description, revisionDate, specification, drawing); em.persist(part); ……………………………….. Where Part is one of the entities and em is the Entity Manager object. 57 Entity Part @Entity @Table(name = "EJB_ORDER_PART") @SecondaryTable(name = "EJB_ORDER_PART_DETAIL", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "PARTNUMBER", referencedColumnName = "PARTNUMBER") , @PrimaryKeyJoinColumn(name = "REVISION", referencedColumnName = "REVISION") } ) 58 Summary • Create Persistence Unit • Create the Entity Classes defined in the persistence unit’ s descriptor file persistence.xml • Obtain access to an Entity Manager object • Access data in database by writing the proper SQL queries in client units to the database. 59 Creating Entity Classes from an Existing Data Source • In addition to writing entity classes from scratch, you can also generate a set of persistent entity classes for an existing database. • You can use the New Entity Classes from Database wizard to generate the entity classes from a connected database or from a database schema. 60 Creating Entity Classes from an Existing Data Source • To generate entity classes from a database: • Right-click the module project node in the Projects window and choose New > Other. • In the New File wizard, select Entity Classes from Database from the Persistence category. • Select the source database that contains the tables that you want to use to generate the entity classes: 61 Creating Entity Classes from an Existing Data Source • To create from a connected data source – Data Source. Choose a data source from the dropdown menu. Alternately, you can choose Add Data Source to create a new data source. The database must be running to choose this option. • When choosing a data source, the server must be running and the data source must be registered with the server. • After you select the source database, the tables in that database are listed in the Available Tables pane. 62 Creating Entity Classes from an Existing Data Source • Select any tables in the left pane and click the Add button. Any tables related to the tables you select are automatically added to the list in the right pane. The IDE will generate entity classes for each table listed in the right pane. – Deselect Include Related Tables if you do not want entity classes created for related tables. • Click Next. • Confirm the name of the classes that will be generated for each table listed. • Select the location where you want to save the entity classes. • Select an existing package from the Package drop-down menu or type the name of a new package. 63 Creating Entity Classes from an Existing Data Source • Confirm that you want the IDE to generate named query annotations in the entity classes. If you do not want the IDE to generate the annotations, deselect Generate Named Query Annotations for Persistent Fields. • Click Finish. • When you click Finish, the IDE creates entity classes for each of the tables you specified in the wizard. The package containing the generated entity classes is selected in the Projects window. 64 Study Guide • Read Chapter 25 of EE5 Tutorial. – Set up and run the bookstore example from the CD • Read Chapter 26 of EE5 Tutorial. – Set up and run the Order and Roster examples from the CD. 65