Tài liệu Java Database Programming Bible- P2 ppt

50 450 0
Tài liệu Java Database Programming Bible- P2 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 2:Designing a Database -49- In practice, you are unlikely to encounter a problem with BCNF, since the purpose of assigning a unique ID column rather than relying on supposedly unique legacy data is to prevent problems of this sort. Law firm data Having created the tables required to manage the clients, you can move on to setting up the tables for the law firm itself. However, after a moment's thought, you will probably realize that the tables you have created will handle all the data for the law firm, too. Billable items In a time and materials invoicing system, there are two kinds of billable items: fees and expenses. Fees are charged in a number of different ways, the most common of which is hourly. Expenses are simply charged on a unit basis, as in the case of photo copies, which are billed per page copied. In either case, the id of the law firm employee, or timekeeper, making the charge is provided. The first table required for billable items, then, is the Timekeeper Table. This table includes a foreign key identifying the individual in the Contacts Table, as well as columns for level and hourly rate. The LEDES specification defines the following levels: § Partner § Associate § Paralegal § Legal Assistant § Secretary § Clerk § Other These levels are best stored in a Lookup Table of billing levels, accessed by a foreign key in the Timekeeper Table. Hourly rates, too, should be stored in a Lookup Table, to allow for increases. These two tables contain only an id column and a corresponding level or billing rate, so they are not shown here. The resulting Timekeeper Table might look like Table 2-4. Table 2-4: Timekeeper Table id contact_id level_code default_rate_code 1000 2001 1 1 1001 2002 1 2 1002 2007 5 9 TEAMFLY Team-Fly ® Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -50- Notice how this structure allows for two partners to bill at different rates. It is also intended that the rate code be overridden if the terms of a contract require it. The billable items are stored in a table that contains the date, a reference to the matter or project, and the id of the timekeeper, as well as information about the specific activity being billed. I have called the table Billable Items, as it is structured such that expense items can be inserted as easily as billable hours. The Billable_Items Table shown in Table 2-5 contains foreign keys linking it to the Timekeeper Table and the Client_Matter table, as shown in Figure 2-2. Figure 2-2: The Billable_Items table is linked to the Client_Matter and Timekeeper tables. Table 2-5: Billable Items Table id date matter_id tk_id task_code activity_code units rate_code description 1 4/12/02 7001 2002 L530 E112 300 0 Court fees 2 4/12/02 7001 2002 L110 A101 2.5 1 Review File The task and activity columns refer to the industry standard Litigation Code Set developed by the American Bar Association, the American Corporate Counsel Association, and a sponsoring group of major corporate law departments. A copy of the Litigation Code Set can be purchased from the ABA Member Services Department, or viewed on line at: http://http://www.abanet.org/litigation/litnews/practice/utbms.pdf In the example of Table 2-5, E112 is the Litigation Code Set code for court fees, while the rate code 0 is used to handle fixed-cost items, as opposed to items billed on a per-unit basis. This permits the merging of unit billings with fixed cost billings without introducing additional columns to handle them separately. If you add an extra column to handle fixed-cost billings, you introduce a possible ambiguity, because it becomes possible to enter both fixed and unit billings in a single row. This violates the requirements of the fourth normal form because it creates Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -51 - nonmeaningful combinations of column values. By handling the situation through the rate code, you can use just one table, conforming to the requirements of the fourth normal form. The tables also meet the requirements of the fifth normal form, which are as follows: § The table must be in fourth normal form. § It must be impossible to break down a table into smaller tables unless those tables logically have the same primary key as the original. By separating address information into a table separate from the Contacts and Clients tables, you can see that if this separation is necessary to conform to the fifth normal form. The addresses do not logically share the same primary key as either contacts or clients. Matter or Project Tables Having designed the simpler tables, it is time to move on to handling the Client Matter, or Project, Tables. These tables encapsulate the information specific to the service the law firm is performing for the client. As such, they contain the following: § Matter Data § Name § Client reference number § Law firm reference number § Law firm managing contact § Law firm billing contact § Client primary contact § Billing Data § Billing type § Electronic funds transfer agreement number § Tax rate information § Fee sharing information § Discount agreements information § Invoice currency and payment terms § Invoice Data § Date § Due date § Amount § Staffing The Matter Table and Billing Rates Table are separate; in an ongoing relationship with a client, a law firm may establish a billing agreement that applies to a number of individual matters, so billing data is not strictly specific to a single matter. Conversely, a billing agreement may be renegotiated during the life of a matter. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -52- The Client Matter Table illustrated in Table 2-6 contains the columns billing_cid and client_cid, which are foreign keys pointing to entries in the contacts table, and are labeled with a _cid suffix to denote contact_id in order to avoid confusion with client_id. Table 2-6: Client Matter Table id client_i d client_re f nam e billing_rat e manager_i d billing_ci d client_ci d 1000 1 1201 ref -3711 Jones v Biddle 2 1004 1007 2001 1000 2 1296 b7997 Jones v Biddle 1 1001 1007 2093 The Billing Rates Table shown in Table 2-7 includes a type code that simply points to a Lookup Table of billing types, including the following: § Time and Materials § Flat Fee § Contingency § Fee Sharing Table 2-7: Billing Rates Table id type_code discount_type discount tax_rate_fees tax_rate_exp terms 1 1 1 15 5 5 1 2 1 1 12.5 5 5 3 Discount types is also a reference to a Lookup Table containing the entries FLAT and PERCENT. Based on the selected discount type, the discount contains either a flat discount amount or a percentage discount rate. The terms column contains another lookup code pointing to a table of payment terms such as 10/30, which means that the billing firm accepts a 10 percent discount if the invoice is paid in full within 30 days. Generating an Invoice Generating an invoice involves retrieving a list of all open matters and summarizing the billable items outstanding against each open matter. For the purposes of this example, a Dedicated Billings Table will be created. This table has a one-to-one relationship with the Client Matter Table, as shown in Figure 2-4. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -53 - The process involved in creating an invoice is to scan the Billings Table for matters where the status indicates that the matter is still open. (When a client matter has been resolved, and the final invoice paid, the status is set to indicate that the matter is closed.) The links between the tables are shown in Figure 2-3. Figure 2-3: Invoices are generated by creating a list of billable items which have not been previously invoiced. The next step is to compare the Invoiced_Items Table against the Billable_Items Table to find items associated with an open Client_Matter that have not been invoiced. Items that have not been invoiced are added to the Invoiced_Items Table, with their Invoice_ID set to indicate which invoice they were billed on. The Invoiced_Items Table is shown in Table 2-8. Table 2-8: Invoiced Items Table id matter_id item_id invoice_id 10001 2006 2031 1007 10007 2119 2047 1063 Another way to handle this is to add an Invoice_Id column to the Billable_Items Table. The Invoice_Id is then updated when the item is invoiced. The advantage of this approach is that you are not adding a new table with a one-to-one relationship with an existing table. The disadvantage is that updating a table can be slow compared to adding a new row. Table 2-9 shows the Invoice Table. The Invoice Number column provides a legacy system compatible invoice number, and the start date and end date columns identify the billing period covered by the invoice. The Billing Rate Id column is a foreign key Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -54- pointing to the Billing Rate Table holding information about payment terms, discounts, and so forth. Table 2-9: Invoice Table id invoice_number date start_date end_date billing_rate_id description 1 2001 4/14/02 3/1/02 3/31/02 1021 Services, March 2002 2 2002 4/14/02 3/1/02 3/31/02 1021 Services, March 2002 Invoices are generated by creating a list of billable items which have not been previously invoiced. Billable items which have not been previously invoiced are identified using the links between the tables shown in Figure 2-3. The relationships between the main tables used to create an invoice are shown in Figure 2-4. Notice the one to one relationship between the Billings and Client_Matter tables mentioned earlier. Figure 2-4: These tables are used to create the invoice header. By combining the data from all these tables, you can generate an invoice containing all the information in Listing 2-1. In addition to itemizing the individual fee and expense items, the LEDES 2000 invoice format requires that fees be summarized by timekeeper. This is done by using the foreign key tk_id in the Billable Items Table. The final step is to create the invoice header using data from the Clients and Contacts Tables. The procedure to create the invoice header is straightforward, and follows the same basic steps as have been outlined in describing the detail sections of the invoice. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -55- This completes the table definitions required to implement the requirements of the LEDES specification. The next step is to ensure that the referential integrity requirements of the database have been met. Referential Integrity In addition to the definitions of the normal forms, the relational model defines certain integrity rules that are a necessary part of any relational database. There are two types of integrity rules: general and database-specific. General Integrity Rules The relational model specifies these two general integrity rules that apply to all databases: § Entity integrity rule § Referential integrity rule The entity integrity rule states that primary keys cannot contain NULLs. Obviously, you can't use a NULL to uniquely reference a row, so this is just common sense. It's important to note that, if you use composite keys, this rule requires that none of the individual columns making up the composite key contain NULLs. Most databases enforce this rule automatically when a primary key is declared. The referential integrity rule states that the database must not contain any unmatched foreign-key values. In other words, all references through foreign keys must point to primary keys identifying rows that actually exist. The referential integrity rule also means that corrective action must be taken to prevent changes or deletions to a row referenced by a foreign key leaving that foreign key with no primary key to reference. This can be handled in the following ways: § Such changes can be disallowed. § Changes can be cascaded, so that deleting a row containing a referenced primary key results in deleting all linked rows in dependent tables. § The dependent foreign-key values are set to NULL. The specific action you take depends on the circumstances. Many relational database systems support the automatic implementation of one or more of these ways of handling attempted violations of the referential integrity rule. For example, an attempt to insert a row with a foreign key that cannot be found in the appropriate table results in a SQL exception message such as the following: INSERT statement conflicted with COLUMN FOREIGN_KEY constraint 'FK_CONTACTS_ADDRESS_INFO'. The conflict occurred in database 'LEDES', Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 2:Designing a Database -56- table 'ADDRESS_INFO', column 'id'. Database-Specific Integrity Rules Database-specific integrity rules are all other integrity constraints on a specific database. They are handled by the business logic of the application. In the case of the LEDES application discussed in this chapter, they include the following: § The extensive use of lookup tables to manage such matters as billing and discount schedules § Validation rules on time captured by employees of the law firm Many of the integrity constraints can be handled by SQL Triggers, but some are be handled by the Java business logic. Triggers are SQL procedures triggered by events such as insertions or changes to the database. Cross-Reference Triggers are discussed in Chapter 3. Summary This chapter has illustrated a common-sense application of the normal forms to the design of a database. The main topics covered are the following: § Using primary and foreign keys to link tables § Applying the normalization rules § Explaining general and database-specific integrity rules Chapter 3 presents an overview of the SQL language, which you use to work with your relational database. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 3:SQL Basics -57 - Chapter 3: SQL Basics In This Chapter As discussed in Chapter 1, a clearly defined data-manipulation language is an important part of any Relational Database Management System. Codd defined the requirements of the language to include comprehensive support of data manipulation and definition, view definition, integrity constraints, transactional boundaries, and authorization. He also specified that the language must have the capability to insert, update, retrieve and delete data as a relational set. The language that has been adopted across virtually the entire database world is the Structured Query Language (SQL). The purpose of this chapter is to provide a comprehensive overview of the Structured Query Language. The SQL Language Structured Query Language (SQL) is a development of an IBM product of the 1970s called Structured English Query Language (SEQUEL). Despite its name, SQL is far more than a simple query tool. As discussed in Chapter 1, in addition to being used to query a database, SQL is used to control the entire functionality of a database system. To support these different functions, SQL can be thought of as a set of the following sublanguages: § Data Definition Language (DDL) § Data Manipulation Language (DML) § Data Query Language (DQL) § Data Control Language (DCL) Unlike Java and most other computer languages, SQL is declarative rather than procedural. In other words, instead of writing a class to perform some task, in SQL you issue a statement that updates a table or returns a group of records. The American National Standards Institute (ANSI) has published a series of SQL standards, notably SQL92 and SQL99 (also known as SQL-2 and SQL-3). These standards define several levels of conformance. SQL92 defines entry level, intermediate, and full; SQL99 defines Core SQL99 and Enhanced SQL99.You can get a copy of the ANSI SQL standard from the American National Standards Institute's Web store: http://webstore.ansi.org/ansidocstore/dept.asp The pertinent documents are: Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 3:SQL Basics -58- § ANSI/ISO/IEC 9075-1-1999 Information Technology - Database Language - SQL Part 1: Framework (SQL/Framework) § ANSI/ISO/IEC 9075-2-1999 Information Technology - Database languages - SQL - Part 2: Foundation (SQL/Foundation) § ANSI/ISO/IEC 9075-3-1999 Information Technology - Database Languages - SQL - Part 3: Call-level Interface (SQL/CLI) § ANSI/ISO/IEC 9075-4-1999 Information Technology - Database languages - SQL - Part 4: Persistent Stored Modules (SQL/PSM) § ANSI/ISO/IEC 9075-5-1999 Information Technology - Database Languages - SQL - Part 5: Host Language Bindings (SQL/Bindings) One of the difficulties you encounter when working with SQL is that each provider uses a slightly different dialect of the language. In the main, these differences amount to enhancements, in that they add to the functionality of SQL. However, they do mean that your SQL statements may not be entirely portable from one implementation to another. Cross-Reference Chapters 5 through 10 provide detailed examples of the use of SQL in the context of the Java Database Connectivity (JDBC) Core API. Appendix A provides a guide to common SQL commands. SQL Data Types SQL supports a variety of different data types that are listed in Table 3-1, together with JDBC data types to which they are mapped. It is important to realize that different SQL dialects support these data types in different ways, so you should read your documentation regarding maximum string lengths, or numeric values, and which data type to use for large-object storage. Table 3-1: Standard SQL Data Types with Their Java Equivalents SQL type Java Type Description BINARY byte[] Byte array. Used for binary large objects. BIT boolean Boolean 0 / 1 value CHAR String Fixed-length character string. For a CHAR type of length n, the DBMS invariably assignd n characters of storage, padding unused space. DATETIME java.sql.Date Date and Time as: yyyy-mm-dd hh:mm:ss DECIMAL java.math.BigDecimal Arbitrary-precision signed decimal numbers. These can be retrieved using either BigDecimal or String. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... SQL command used to remove a database is as simple as the CREATE DATABASE command The SQL DROP command is used: DROP DATABASE CONTACTS; Relational databases store data in tables Most databases may contain a number of different tables, each containing different types of data, depending on the application Tables are intended to store logically related data items together, so a database may contain one table... the database elements they can work with, are shown in Table 3 -2 Table 3-2: DDL Commands COMMAND DATA-BASE TABLE VIEW INDEX FUNC-TION PROCE-DURE TRIGGER CREATE YES YES YES YES YES YES YES ALTER NO YES YES NO NO NO NO DROP YES YES YES YES YES YES YES Creating, Dropping, and Altering Databases and Tables The basic SQL command used to create a database is straightforward, as you can see here: CREATE DATABASE. .. SQL Data Types with Their Java Equivalents SQL type Java Type Description FLOAT double Floating-point number, mapped to double INTEGER int 32-bit integer values LONGVARBINARY byte[] Variable-length character string JDBC allows retrieval of a LONGVARBINARY as a Java input stream LONGVARCHAR String Variable-length character string JDBC allows retrieval of a LONGVARCHAR as a Java input stream NCHAR String... NUMERIC java. math.BigDecimal Arbitrary-precision signed decimal numbers Can be retrieved using either BigDecimal or NTEXT String AM FL Y String Large string variables Used for character large objects NVARCHAR String National Character Unicode variable-length character string float Floating-point number, mapped to float SMALLINT short 16-bit integer values TIME java. sql.Time Thin wrapper around java. util.Date... java. util.Date TIMESTAMP java. sql.Timestamp Composite of a java. util.Date and a separate TE REAL nanosecond value VARBINARY byte[] Byte array VARCHAR String Variable-length character string For a VARCHAR of length n, the DBMS assigns upto n charcters of storage, as required Many SQL dialects also support additional data types, such as a MONEY or CURRENCY type These are handled in Java using the most appropriate... Transaction management refers to the capability of a relational database management system to execute database commands in groups, known as transactions A transaction is a group or sequence of commands, all of which must be executed in order and all of which must complete successfully If anything goes wrong during the transaction, the database management system allows the entire transaction to be cancelled... function of any database application is the ability to search for specific records or groups of records and return them in the desired form In SQL, this capability is provided by the Data Query Language (DQL) The process of finding and returning formatted records is known as querying the database The SELECT Statement The SELECT statement is the basis of data retrieval commands, or queries, to the database. .. expect to work, since JDBC will attempt to perform the required data type Data Definition Language SQL's Data Definition Language (DDL) is used to create and modify a database In other words, the DDL is concerned with changing the structure of a database The SQL2 standard refers to DDL statements as "SQL Schema Statements" and specifies only aspects of the DDL that are independent of the underlying operating... ways, a table is like a spreadsheet Each row contains a single record Unlike the rows in a spreadsheet, however, the rows in a database have no implicit order Table 3 -3 illustrates the way tables are designed to contain rows of related, unordered data elements Table 3-3: Part of a Database Table Contact_ID First_Name MI Last_Name Street City 1 Alex M Baldwin 123 St 2 Michael Q Cordell 1701 York Columbia... DISTINCT operator A basic SELECT statement tells the database management system to return all records matching the query in the ResultSet For example, you cab request all Last_Names from customers using this query: SELECT Last_Name FROM Customers; Using the data shown in Table 3-4, this gives you five repetitions of "Corleone." The DISTINCT operator tells the database management system not to return duplicate . 16-bit integer values TIME java. sql.Time Thin wrapper around java. util.Date TIMESTAMP java. sql.Timestamp Composite of a java. util.Date and a separate. used to remove a database is as simple as the CREATE DATABASE command. The SQL DROP command is used: DROP DATABASE CONTACTS; Relational databases store

Ngày đăng: 26/01/2014, 18:20

Tài liệu cùng người dùng

Tài liệu liên quan