1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Teach Yourself PL/SQL in 21 Days- P8 pptx

50 362 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Thông tin cơ bản

Tiêu đề Writing Database Triggers
Trường học Standard University
Chuyên ngành Database Management
Thể loại Bài viết
Năm xuất bản 2023
Thành phố City Name
Định dạng
Số trang 50
Dung lượng 2,48 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

• How to create an object table, and how to use PL/SQL to store objects inthat table.5. • How to create an object column in a regular table, and then access the data in thatcolumn from P

Trang 1

Notice in line 1 that the previous trigger is dropped Be sure to do this Thetable-level before trigger in lines 3–9 is fired at the beginning of an INSERTor

UPDATEstatement It calls a package procedure that initializes the list counter The level trigger, named only_two_departments_2(defined in lines 11–19), is fired for eachrow added or changed This trigger adds the primary key of each record to the list main-tained in the package-level PL/SQL table The third trigger, defined in lines 21–52, is theone that does the actual validation work It is fired after the INSERTorUPDATEstatement

row-is complete It loops through each new or changed record and checks to be sure that eachemployee in question has a maximum of two department assignments

Now that you have created these triggers and the emp_dept_procspackage, you can cute the SQL statements shown in Listing 11.22 in order to demonstrate that it works

exe-L ISTING 11.22 Testing the Triggers and Package That Enforce the Two-Department Rule

1: INSERT INTO employee 2: (emp_id,emp_name) VALUES (403,’Freddie Fisher’);

Trang 2

23: (emp_id, dept_id) VALUES (404,405);

33: ORA-20000: Employees are limited to a max of two departments.

34: ORA-06512: at “MY_READER.ONLY_TWO_DEPARTMENTS_3”, line 21 35: ORA-04088: error during execution of trigger

➥’MY_READER.ONLY_TWO_DEPARTMENTS_3’

36: UPDATE emp_dept 37: SET dept_id = 406 38: WHERE emp_id = 403 AND dept_id = 405;

39: 1 row updated.

40: UPDATE emp_dept 41: SET emp_id = 403 42: WHERE emp_id = 404 43: AND dept_id = 405;

44: update emp_dept 45: * 46: ERROR at line 1:

47: ORA-20000: Employees are limited to a max of two departments.

48: ORA-06512: at “MY_READER.ONLY_TWO_DEPARTMENTS_3”, line 21 49: ORA-04088: error during execution of trigger

‘MY_READER.ONLY_TWO_DEPARTMENTS_3’

The first five inserts (lines 1–15) put some sample employees and departments inplace for testing purposes The next four inserts (lines 16–27) assign each of thetwo employees just inserted to two departments The tenth insert (lines 28–29) attempts

to assign employee number 403 to a third department This violates the two-departmentrule, causing the insert to fail (lines 30–35) There are two UPDATEstatements The firstupdate (lines 36–38) is allowed because it only changes a department assignment foremployee number 403 That employee still has exactly two departments The secondupdate (lines 40–43) fails because it is changing the emp_idfield in a record from 404 to

403, resulting in 403 having more than two department assignments

L ISTING 11.22 continued

A NALYSIS

Trang 3

Summary

This chapter has been complex, but it gave you the chance to see and experiment withtriggers implementing several different types of functionality To reiterate, some possibleuses for triggers are to enforce business rules, generate column values (Listing 11.3),enhance security, and maintain a historical record (Listing 11.6) These are just the tip ofthe iceberg The possibilities are limited only by your creativity and imagination Youhave also learned about the mutating table error, the bane of many trigger writers, andshould now have a good understanding of how to work around it

Q&A

Q If I am using a trigger to enforce a business rule or a referential integrity rule, does this affect the records that predate creation of the trigger?

A No, it doesn’t, and that’s a good point to keep in mind When you create a

declara-tive constraint, you are really making a statement about the data that must always

be true You cannot create a constraint if data is present that violates that constraint

Triggers, on the other hand, affect only records that have been inserted, updated, ordeleted after the trigger was created For example, creating the triggers limiting anemployee to only two department assignments will do nothing about preexistingcases where an employee has more than two assignments

Q The inserts in Listing 11.18 (lines 16–27) did not generate a mutating table error message, yet they did query the table Why is this?

A Single-row inserts are an exception to the rule about querying the underlying table.

However, if the insert is one that could possibly create more than one row, forexample an INSERT INTO emp_dept SELECT , the rule about not querying themutating table still applies

The solution shown in Listings 11.20 and 11.21 will work when triggers only need to query the mutating table The problem gets more complex if you need to update those rows Updating records in the mutating table from a trigger will fire off the very same set of triggers that will also try to use the very same package-level PL/SQL table to build a list of affected records, thus clobbering the data needed to validate the initial update.

Caution

Trang 4

Q What’s the difference between a statement-level trigger and a row-level trigger?

A A statement-level trigger is executed only once, either before or after the triggering

SQL statement executes It cannot refer to any values in the rows affected by thestatement A row-level trigger fires once for each row affected by the triggeringSQL statement and can reference the values for each of the rows

Q Why should I generally validate business rules in a before trigger rather than

an after trigger?

A It’s potentially more efficient because you can prevent Oracle from doing the work

involved in inserting, updating, or deleting a record By validating in an after ger, you are allowing Oracle to first update the table in question, update any index-

trig-es that might be affected by the change, and possibly fire off other triggers

Q The triggers in Listing 11.3 maintain employee counts for each department as records are inserted into, updated in, and deleted from the emp_depttable What happens, however, if a department record is deleted and then reinsert- ed? Won’t the employee count be reset to zero in that case, making it incorrect?

A Yes, this is absolutely true Typically, in a production database, you would also

have referential integrity constraints defined to prevent deletion of departmentrecords referenced by other tables

Q Can I define DDL triggers on a specific schema object such as a table?

A No, you cannot Oracle may have plans to change this The syntax certainly leaves

that possibility open For now though, you may only define DDL triggers at theschema level

Workshop

Use the following sections to test your comprehension of this chapter and put whatyou’ve learned into practice You’ll find the answers to the quiz and exercises inAppendix A, “Answers.”

Quiz

1 Which data manipulation statements can support triggers?

2 What are the four basic parts of a trigger?

3 In a trigger, what are the correlation names :OLDand:NEWused for?

Trang 5

4 What is the name of the system view that can be used to retrieve trigger definitions?

5 What is a mutating table?

6 Name some possible uses for triggers

Exercises

1 Write a set of triggers to maintain the emp_nameanddept_namefields redundantly

in the emp_depttable so that you do not have to join with the employee and ment tables just to get a simple department listing

depart-2 Write the SQL statements necessary to populate the emp_nameanddept_name

fields for any existing emp_deptrecords

Trang 7

Today you will learn:

• How to define an Oracle object type

• How to create an object table, and how to use PL/SQL to store objects inthat table

Trang 8

• How to create an object column in a regular table, and then access the data in thatcolumn from PL/SQL.

• How to write the ORDERandMAPmethods used when comparing objects

A Brief Primer on Object-Oriented Programming

Let’s begin by reviewing the basics of object-oriented programming (OOP) There isreally no magic to OOP: It’s simply a way of organizing code and data within your pro-grams, one that you can use to model your code to more closely match the real world.There are three pillars of good object-oriented design:

• Encapsulation

• Inheritance

• PolymorphismEach of these is described in more detail in the following sections, using as examplessome real-world objects that you interact with every day

Encapsulation

The term encapsulation refers to the fact that each object takes care of itself A

well-designed object has a clear and well-defined interface that is used to ulate the object All the program code necessary to perform any function on the object iscontained within the object definition itself Thus an object is completely self-containedand can be dropped in anywhere you need it

manip-A classic, and often used, real-world example of objects is audio/video components Sayyou are setting up a home theater You drive to the nearest appliance superstore and pickout whatever objects interest you—a big-screen TV, an FM tuner, an amplifier, and somespeakers All these components have well-defined interfaces, and each contains the inter-nal electronics and software that are necessary to make them work The FM tuner tunes

in radio stations, regardless of whether you plug it in to the amplifier The TV does notneed any circuitry that might be present in the speakers After integrating all these com-ponents, you might decide that you also want a subwoofer Adding one is simple Youdon’t have to rebuild your stereo system—you just run back to the store, buy the desiredcomponent, come home, and plug it in

It sounds pretty easy, but there are some gotchas In real life, interfaces are not alwayscompatible, and sometimes components have overlapping functionality That amplifier,

NEW TERM

Trang 9

for example, might also have a built-in tuner, and how often have you had to buy anadapter to mate two incompatible connectors? Often it’s easier to work with componentsthat have all been built by the same manufacturer and that have been designed to worktogether The same is true in OOP

Inheritance

Inheritance refers to the fact that as you design new objects, you often build on

objects that have been created previously In other words, you can create new

objects that inherit the functionality of previously created objects When you do this, you

might choose to modify some of the inherited functionality, or you might choose to addnew functionality The telephone is a good example of this Originally it was a very sim-ple device You picked up the phone, listened for a dial tone, and dialed a number byusing a rotary dial When pushbutton phones came out, the original functionality wasinherited, except for the dialing interface, which was replaced by buttons Cordlessphones inherited this functionality, added a radio to the implementation, and added anon/off switch to the handset interface so that the handset did not need to be returned tothe cradle after each call

One big advantage of inheritance in the OOP world, which is not present in the physicalworld, is that you can change the definition of a software object, and the change willpropagate through all objects of that type, all objects inherited from those objects, and soforth Imagine changing the definition of a telephone to include pushbutton dialing, and

as a result having all the rotary phones in the world suddenly transform themselves intopushbutton phones Of course that can’t be done, but the software equivalent of it can

Polymorphism

Polymorphism enables different objects to have methods of the same name that

accomplish similar tasks but in different ways Think back to the home ment system example for a moment Each of the components—the TV, the FM tuner, theamplifier, and so forth—has an on button Many components also have associatedremotes, each also with an on button Each of these buttons can invoke different process-

entertain-es inside each piece of equipment A TV remote, for example, has to send an infraredbeam of light to the TV set when the on button is pushed Despite the fact that each on

button invokes a different sequence of events, each button is still labeled on It would be

inconvenient if this were not the case Consistent naming frees your mind from having toremember specifically for each device how to turn it on You quickly become conditioned

to pushing the on button, or flipping a switch to on, no matter what device you are using

NEW TERM

NEW TERM

Trang 10

Polymorphism similarly enables your software objects to use method names that are sistent with the function being performed, even though the way in which that function isimplemented can differ from object to object

con-Classes, Objects, Attributes, and Methods

The term class refers to the definition for an object Like a blueprint for a house,

it tells you everything you need to build an object, and it tells you what thatobject will look like when it is built An employeeclass, for example, might be created tocontain all attributes of an employee Examples of employee attributes would be payrate, name, and address

Many objects can be built from a class, just as one set of blueprints can be used

to build numerous houses If you were writing code to process employee records,you would use the employeeclass to instantiate, or construct, an employeeobject foreach employee record

Objects consist of attributes and methods An attribute can be anything you need

to know about an object Name, phone number, Social Security number, pay rate,and pay type are all examples of attributes for an employeeobject Attributes are imple-

mented as variable declarations made within the object class definition Methods are the

functions and procedures used to perform functions related to the object Like attributes,methods are implemented as functions and procedures in the object class definition.Anything you want to do to an object should be implemented as a method If you want tocompare two objects, you should implement a compare method If you want to copy anobject, you should implement a copy method An employeeobject class, for example,might contain a method to calculate an employee’s yearly bonus based on pay type,longevity with the firm, and so on

Advantages of OOP Over Traditional Methods

Objects offer the opportunity for increased reliability because of their well-defined faces Reuse is made easier because all necessary code and data are part of the objectdefinition; thus object classes can easily be added to programs as new functionality isrequired Because you can model real-world business objects, as well as encapsulate andhide the details behind an object’s functionality, you can program at a higher level ofabstraction, minimizing the amount of detail you need to remember, which makes yourjob as a developer much easier

inter-NEW TERM

NEW TERM

NEW TERM

Trang 11

How Oracle8i Implements Objects

Oracle8i implements several constructs in support of object-oriented programming:

• Object types, with which you can define object classes.

• Object tables, with which you can store objects.

• Object views, which allow you to synthesize objects from the existing relational

data

Oracle also implements an object-relational database The underpinnings are still tional, but the underlying relational model has been extended to include support for newdatatypes, which in this case are object types By doing this, Oracle has maintained com-patibility with existing relational databases and provided a path for gradual migration toobjects

rela-Object Types

To use an object, first you need to define it To do this, you create an object type, which

is a database-level definition and is equivalent to the term class as used in object-oriented

languages such as Java and C++ It contains both the code and data definitions for anobject Object types are also treated as datatypes and can be used in PL/SQL programsfor declaring variables that will contain objects

Object Tables

Object tables are based on an object definition and essentially map each attribute of an

object to a column in the table

Object Views

An object view is the object analog of a view on a table A full discussion of object views

is beyond the scope of this book, but basically you should know that a database trator can use them to define pseudo-objects based on existing relational data Like arelational view, object views are based on a SQL statement that retrieves the data for theobject

adminis-Defining an Object Type

You should now have a good idea of what OOP is and how Oracle handles objects It’stime to get down to some practical examples To begin, let’s define an object type foremployee addresses Listing 12.1 shows one possible implementation

Trang 12

L ISTING 12.1 The address Object Type

1: CREATE OR REPLACE TYPE address AS OBJECT ( 2: street_1 VARCHAR2(40),

3: street_2 VARCHAR2(40), 4: city VARCHAR2(40), 5: state_abbr VARCHAR2(2), 6: zip_code VARCHAR2(5),

7: phone_number VARCHAR2(10), 8: MEMBER PROCEDURE ChangeAddress ( 9: st_1 IN VARCHAR2, st_2 IN VARCHAR2, cty IN VARCHAR2, 10: state IN VARCHAR2, zip IN VARCHAR2),

11: MEMBER FUNCTION getStreet (line_no IN number) RETURN VARCHAR2, 12: MEMBER FUNCTION getCity RETURN VARCHAR2,

13: MEMBER FUNCTION getStateAbbr RETURN VARCHAR2, 14: MEMBER FUNCTION getPostalCode RETURN VARCHAR2, 15: MEMBER FUNCTION getPhone RETURN VARCHAR2, 16: MEMBER PROCEDURE setPhone (newPhone IN VARCHAR2) 17: );

18: / 19 20: CREATE OR REPLACE TYPE BODY address AS 21: MEMBER PROCEDURE ChangeAddress ( 22: st_1 IN VARCHAR2, st_2 IN VARCHAR2, cty IN VARCHAR2, 23: state IN VARCHAR2, zip IN VARCHAR2) IS

24: BEGIN 25: IF (st_1 IS NULL) OR (cty IS NULL) OR 26: (state IS NULL) OR (zip IS NULL) 27: OR (upper(state) NOT IN (‘AK’,’AL’,’AR’,’AZ’,’CA’,’CO’, 28: ‘CT’,’DC’,’DE’,’FL’,’GA’,’HI’, 29: ‘IA’,’ID’,’IL’,’IN’,’KS’,’KY’, 30: ‘LA’,’MA’,’MD’,’ME’,’MI’,’MN’, 31: ‘MO’,’MS’,’MT’,’NC’,’ND’,’NE’, 32: ‘NH’,’NJ’,’NM’,’NV’,’NY’,’OH’, 33: ‘OK’,’OR’,’PA’,’RI’,’SC’,’SD’, 34: ‘TN’,’TX’,’UT’,’VA’,’VT’,’WA’, 35: ‘WI’,’WV’,’WY’))

36: OR (zip <> ltrim(to_char(to_number(zip),’09999’))) THEN 37: RAISE_application_error(-20001,’The new Address is invalid.’); 38: ELSE

Trang 13

49: BEGIN 50: IF line_no = 1 THEN 51: RETURN street_1;

52: ELSIF line_no = 2 THEN 53: RETURN street_2;

54: ELSE 55: RETURN ‘ ‘; send back a blank.

A NALYSIS

Trang 14

The Syntax for Defining an Object Type

CREATE TYPE type_name [IS | AS] OBJECT ( attribute_name datatype,

attribute_name datatype,

MEMBER [function_specification | procedure_specification], MEMBER [function_specification | procedure_specification],

[MAP | ORDER] MEMBER function_specification, pragma,

pragma,

);

CREATE TYPE BODY type_name [IS | AS]

MEMBER [function_definition | procedure_definition];

MEMBER [function_definition | procedure_definition];

[MAP | ORDER] MEMBER function_definition;

END;

In this syntax, the parameters are as follows:

• type_name—The name of the object type that you are defining This can be anyname you choose, but it must conform to Oracle’s naming rules Names may be up

to 30 characters long, must begin with a letter, and thereafter may contain letters,digits, underscores (_), pound signs (#), and dollar signs ($)

• attribute_name—The attribute can have any name you choose, and must conform

to the rules for naming variables An object must have at least one attribute

• datatype—This can be another object type or an Oracle datatype The OracledatatypesLONG,LONG RAW,NCHAR,NCLOB,NVARCHAR2, and ROWIDcannot be usedhere PL/SQL-specific datatypes, such as BINARY_INTEGERandBOOLEAN, are alsonot allowed That’s because objects are stored in database tables, and the databasedoes not recognize PL/SQL specific datatypes

• function_specification—This is the same kind of PL/SQL function tion that would appear in a package definition

specifica-• procedure_specification—This is the same kind of PL/SQL procedure cation that would appear in a package definition

specifi-• pragma—This is any pragma, or compiler directive, such as those used to defineexceptions or to tell Oracle whether a method modifies any database tables

• function_definition—This contains the code for a function

• procedure_definition—This contains the code for a procedure

Trang 15

An object must contain at least one attribute, and may contain as many as a thousand

Member functions and procedures are entirely optional, as are compiler directives (that

is, pragmas) The definition of a MAPfunction or an ORDERfunction is also optional, but ifpresent, only one type may be used MAPandORDERfunctions are discussed later in thislesson, in the section “Comparing Objects.”

As mentioned previously, an object type is a database-level definition After an objecttype is defined in the database, it can be used to create object tables, to define tablecolumns that are themselves objects, or to declare object variables in PL/SQL blocks

Constructor Methods

Each Oracle object type has a built-in constructor method that is used to create

an instance of that type This method is responsible for initializing all theobject’s attributes and for doing any internal housekeeping necessary You do not have todeclare or define this method, and in fact you cannot—Oracle does it for you

NEW TERM

The inability to declare and define your own constructor methods represents

a serious weakness in Oracle’s current implementation of objects Your bility is limited, and your control is limited as well because you have nowhere to write validation code, which can prevent an object from being created with an invalid combination of attribute values.

flexi-Note

The constructor method always has the same name as the object type, and has as itsarguments each of the object’s attributes, in the order in which you declared them Thusthe constructor method for the addressobject type would be

FUNCTION address (street_1 in VARCHAR2, street_2 in VARCHAR2,

city in VARCHAR2, state_abbr, zip_code, phone_number) returns address

The constructor function always returns an object of the same type In your code, youwould reference addressas a function, passing values for each argument, in order tocreate an object of the addresstype, such as the following:

address_variable := address(‘101 Oak’,’’,’Detroit’,’MI’,

‘48223’,’3135358886’);

You will see more examples of this later in the lesson, in the section “Instantiating andUsing Objects.”

Trang 16

Accessor Methods

Accessor methods are used to return an object’s attributes, and by convention,

they usually begin with get The implementation of the addressobject shown inListing 12.1 contains five accessor methods:

In most cases, these simply return the attribute in question The getStreetmethod does

a bit more: It returns a blank if an invalid street address line is requested

At first glance, it might seem silly to use a function like getStreetwhen you could just

as easily reference the street_1andstreet_2attributes directly However, accessormethods provide extra insulation between the underlying implementation of the objectsand the programs that use them Consider the implications if, for whatever reason, youdecided to remove the street_2attribute from the addressobject What impact wouldthat have on existing programs? None if they are using getStreet One small change tothat function, and your programs wouldn’t know the difference

NEW TERM

Most object-oriented languages allow you to force the use of accessor

func-tions by letting you define attributes as private, meaning that they cannot

be accessed directly Oracle does not yet do this, so even though the accessor functions exist, there is no way to be completely sure that they are always used.

Caution

Mutator Methods

A mutator method is the opposite of an accessor method It lets you set attribute

values without referencing them directly The advantages are the same as foraccessor methods Mutator methods simply provide an extra level of insulation between

a program and an object’s underlying implementation By convention, mutator methodnames typically start with set

TheChangeAddressmethod of the addressobject described previously, for example,would be considered a mutator method It could have been named setAddressto con-form more closely to convention, but the name ChangeAddresswas chosen because it ismore descriptive of the real-world event for which this method exists, and because in a

NEW TERM

Trang 17

real-life situation, changing an address might involve more than just setting a few utes

attrib-Instantiating and Using Objects

After you have defined an object type, you probably want to do something with it To use

an object from within PL/SQL, you need to follow these steps:

1 Declare one or more variables in which the datatype is the object type you want touse

2 Instantiate one or more of the objects

3 Use the object’s member methods to manipulate the objects

4 Optionally, store the objects in a database

This section discusses how to perform the first three of these four steps There are twodifferent approaches to storing objects, and those are discussed later in this lesson, in thesection “Storing and Retrieving Objects.”

Listing 12.2 shows some fairly simple code that uses the addressobject defined earlier

Several variables of the addressobject type are declared A few addressobjects areinstantiated, their values are manipulated, and the object’s attributes are displayed

L ISTING 12.2 Using the address Object

1: A PL/SQL block demonstrating the 2: use of the address object.

3: DECLARE 4: address_1 address;

5: address_2 address;

6: address_3 address;

7: BEGIN 8: Instantiate a new address object named address_1, 9: and assign a copy of it to address_2.

10: address_1 := address (‘2700 Peerless Road’,’Apt 1’, 11: ‘Cleveland’,’TN’,’37312’,’4235551212’);

12: address_2 := address_1;

13:

14: Change address #1 15: address_1.ChangeAddress (‘2800 Peermore Road’,’Apt 99’, 16: ‘Detroit’,’MI’,’48823’);

17:

18: Instantiate a second object.

19: address_3 := address (‘2700 Eaton Rapids Road’,’Lot 98’, 20: ‘Lansing’,’MI’,’48911’,’5173943551’);

INPUT

continues

Trang 18

22: Now print out the attributes from each object.

23: dbms_output.put_line(‘Attributes for address_1:’); 24: dbms_output.put_line(address_1.getStreet(1));

25: dbms_output.put_line(address_1.getStreet(2));

26: dbms_output.put_line(address_1.getCity 27: || ‘ ‘ || address_1.getStateAbbr 28: || ‘ ‘ || address_1.getPostalCode); 29: dbms_output.put_line(address_1.getPhone);

30:

31: dbms_output.put_line(‘ -’); 32: dbms_output.put_line(‘Attributes for address_2:’); 33: dbms_output.put_line(address_2.getStreet(1));

34: dbms_output.put_line(address_2.getStreet(2));

35: dbms_output.put_line(address_2.getCity 36: || ‘ ‘ || address_2.getStateAbbr 37: || ‘ ‘ || address_2.getPostalCode); 38: dbms_output.put_line(address_2.getPhone);

39:

40: dbms_output.put_line(‘ -’); 41: dbms_output.put_line(‘Attributes for address_3:’); 42: dbms_output.put_line(address_3.street_1);

43: dbms_output.put_line(address_3.street_2);

44: dbms_output.put_line(address_3.city 45: || ‘ ‘ || address_3.state_abbr 46: || ‘ ‘ || address_3.zip_code); 47: dbms_output.put_line(address_3.phone_number);

48: END;

49: /

Attributes for address_1:

2800 Peermore Road Apt 99

Detroit MI 48823 4235551212 - Attributes for address_2:

2700 Peerless Road Apt 1

Cleveland TN 37312 4235551212

Attributes for address_3:

-2700 Eaton Rapids Road Lot 98

Lansing MI 48911 5173943551

PL/SQL procedure successfully completed.

L ISTING 12.2 continued

OUTPUT

Trang 19

Notice that in lines 4–6, three object variables are defined They are of type

addressand are used to contain addressobjects When first created, theseobjects are considered to be null Any calls to their member methods result in errors andany reference to their attributes evaluates to null

The first addressobject is instantiated in line 10 This is done by calling the constructorfunction for the addressobject, and assigning the value returned to the object variable

address_1 In line 12 a copy of this object is assigned to address_2 Then the value of

address_1is changed This is done with a call to the ChangeAddressmethod (lines15–16), and is done in order to demonstrate that address_1andaddress_2are indeedseparate objects In line 19 a third addressobject is created

The values of these three addressobjects are displayed by the code in lines 22–47

Notice that although the accessor methods are used to retrieve the attribute values fromthe first two objects, the attributes of the third object are accessed directly

Storing and Retrieving Objects

There are two ways to store an object in an Oracle database One is to store the object as

a column within a table (This is the approach this chapter takes to storing the address

objects This way, each employee record has one address associated with it.) The otherapproach to storing objects involves the use of an object table, which as you learned ear-lier in the chapter is a relational table that has been defined to store a particular type ofobject Each row in the table represents one object, and each column represents oneattribute in the object

Storing Objects as Table Columns

Oracle’s object-relational model allows an object to be stored as a column in a databasetable In order to do this, a column of the appropriate object type must first be added tothe table in question To create an address column in the employee table, you must firstexecute the Data Definition Language (DDL) statement shown in Listing 12.3

L ISTING 12.3 Creating a Column for the address Object

1: ALTER TABLE employee 2: ADD (

3: home_address address 4: );

A NALYSIS

INPUT

Trang 20

This statement simply adds a column, which is named home_address, to theemployee table The column type is given as address, which is a reference to theobject type defined earlier in this chapter For any existing employee records, the object

is considered to be null

Now that an address column exists in the employee table, you can create some employeerecords and store each employee’s address, along with the other information Listing 12.4shows two different ways to do this

L ISTING 12.4 Saving address Objects with Employee Records

1: INSERT INTO employee 2: (emp_id, emp_name,pay_rate,pay_type,home_address) 3: VALUES (597,’Matthew Higgenbottom’,120000,’S’, 4: address(‘101 Maple’,’’,’Mio’,’MI’,’48640’,’5173943551’));

14: BEGIN 15: emp_home_address := address(‘911 Pearl’,’Apt 2’,’Lewiston’, 16: ‘MI’,’48645’,’5173363366’);

17: INSERT INTO employee 18: (emp_id, emp_name,pay_rate,pay_type,home_address) 19: VALUES (598, ‘Raymond Gennick’,55,’H’,emp_home_address);

597 Matthew Higgenbottom ADDRESS(‘101 Maple’, NULL, ‘Mio’, ‘MI’, ‘48640’, ‘5173943551’)

598 Raymond Gennick ADDRESS(‘911 Pearl’, ‘Apt 2’, ‘Lewiston’, ‘MI’, ‘48645’, ‘5173363366’)

A NALYSIS

I NPUT /

O UTPUT

Trang 21

Lines 1–4 show how a constructor method can be referenced from within a SQLstatement In fact, the statement in question was executed from within SQL*Plus,although it could have been inside a PL/SQL block Lines 12-22 show a PL/SQL blockthat first instantiates an addressobject, and then inserts that object into the employeetable as part of an employee record The emp_home_addressvariable is defined in line 13

as being of type address Then in line 15 of the third segment, the addressconstructor

is used to instantiate a new addressobject, which is assigned to the emp_home_address

variable Finally, in lines 17–19, an INSERTstatement is executed, saving the employeerecord The emp_home_addressvariable is included in the values list and is stored as apart of the record

TheSELECTstatement (lines 1–3 of the fourth segment) retrieves the addressobjects thatyou have just inserted into the database Notice how SQL*Plus uses the addresstypeconstructor in the resulting output to indicate that the addresses are from an embeddedobject

Retrieving and Updating Objects in a Table Column

As with inserting, you can retrieve and update an object that is stored in a column, just asyou would any other column value Listing 12.5 shows a PL/SQL block that retrieves theaddress for employee number 597, changes the phone number, and then updates the table

to contain the new value of the object

L ISTING 12.5 Retrieving and Updating the address Object

1: DECLARE 2: emp_addr address;

3: BEGIN 4: Retrieve the object from the table 5: SELECT home_address INTO emp_addr 6: FROM employee

15:

16: COMMIT;

17: END;

18: / 19:

20: PL/SQL procedure successfully completed.

A NALYSIS

I NPUT /

O UTPUT

continues

Trang 22

Lines 5–7 retrieve the addressobject into the emp_addrvariable for the

employ-ee whose phone number you want to change In line 10, the setPhonemethod isused to update the phone number At this point, only the object in memory has the updat-

ed phone number Lines 12–14 update the employee’s record, storing the new value oftheaddressobject

It is also possible to update an employee’s phone number by using only one update,rather than the three steps—retrieve, modify, and store—shown in Listing 12.5 This can

be accomplished by creating an entirely new addressobject and assigning it to theemployee’shome_addressfield Listing 12.6 shows the phone number for employeenumber 598 being modified, using this method

L ISTING 12.6 Updating an address Object

1: UPDATE employee e 2: SET e.home_address = address(e.home_address.street_1, 3: e.home_address.street_2, e.home_address.city, 4: e.home_address.state_abbr, e.home_address.zip_code, 5: ‘5173433333’)

correla-Note

Trang 23

TheSETclause of this UPDATEstatement uses the information from the existing

addressobject, plus a new phone number, to instantiate an entirely new address

object This is done in lines 2–5 by calling the object type’s constructor and passingattributes of the original address as arguments The home_addresscolumn is then set tothe value of this new object

Using Object Tables

As you learned earlier in the chapter, another way to store objects is in an objecttable in which each column of the table matches one of the attributes of theobject Consequently each row of the table is used to store one instance of an object Inaddition to the columns for the object’s attributes, an object table also has an additional

column that is used to contain an object identifier, which is an Oracle-generated value

that uniquely identifies each object in the database

Take a look at Listing 12.7 It defines a buildingtype for the sample database, and thencreates an object table that can store instances of that type

L ISTING 12.7 The building Object

1: CREATE OR REPLACE TYPE building AS OBJECT ( 2: BldgName VARCHAR2(40),

3: BldgAddress address, 4: BldgMgr INTEGER, 5: MEMBER PROCEDURE ChangeMgr (NewMgr IN INTEGER), 6: ORDER MEMBER FUNCTION Compare (OtherBuilding IN building) 7: RETURN INTEGER

8: );

9: / 10

11 Type created.

12 13: CREATE OR REPLACE TYPE BODY building AS 14: MEMBER PROCEDURE ChangeMgr(NewMgr IN INTEGER) IS 15: BEGIN

25: Make sure that we don’t get messed up by leading/trailing

Trang 24

38: END IF;

39: END;

40: END;

41: /

Type body created.

CREATE TABLE buildings OF building;

Table created.

Lines 1–9 contain the buildingobject’s type definition As you can see, the

buildingobject has three attributes containing the building’s name, the ing’s address, and the employee ID of the building manager The second attribute isinteresting because it is itself an object Objects can be nested in this manner to anylevel

build-TheORDERfunction, in line 6, enables you to compare two objects of type buildingfor

equality or to see which is greater You decide what equality means when you write the

function The keyword ORDERtells Oracle which member function to call when doingcomparisons Comparing objects by using order functions is described later in this les-son, in the section “Comparing Objects.”

Lines 13–40 define the object body, which contains the definitions for the two memberfunctionsChangeMgrandCompare

The last command in the listing, shown in the third segment, is very important This is anew form of the CREATE TABLEstatement, which creates an object table for objects oftypebuilding (You will be using this table later in this chapter.) You can look at thetable’s structure by typing this command:

describe buildings

L ISTING 12.7 continued

A NALYSIS

Trang 25

When you use an object table to store objects, they have visibility outside the table

Other objects can be linked to them, referencing them by their object identifiers Anotheradvantage of object tables is that they can be queried just like any other relational tables

This gives you some flexibility and enables you to mix and match relational and oriented methods in your software development projects

object-Storing Objects in an Object Table

You can insert information about buildings into the object table you just created by using

a SQL INSERTstatement Instead of a list containing separate values for each attribute,you can use the buildingobject’s constructor to create an object This one objectbecomes the only value in the values list

Type the statements shown in Listing 12.8 in order to insert a few buildingobjects

These will be used in later examples that show how to update object tables and how tolink objects in the database

L ISTING 12.8 Inserting Some building Objects

1: INSERT INTO buildings 2: values (building(‘Victor Building’, 3: address(‘203 Washington Square’,’ ‘,’Lansing’, 4: ‘MI’,’48823’,’ ‘),

5: 597));

1 row created.

1: INSERT INTO buildings 2: values (building(‘East Storage Shed’, 3: address(‘1400 Abbott Rd’,’’,’Lansing’,’MI’,’48823’,’’), 4: 598));

1 row created.

1: INSERT INTO buildings 2: values (building(‘Headquarters Building’, 3: address(‘150 West Jefferson’,’’,’Detroit’,’MI’,’48226’,’’), 4: 599));

1 row created.

SELECT * from buildings;

BLDGNAME - BLDGADDRESS(STREET_1, STREET_2, CITY, STATE_ABBR, ZIP_CODE, PHONE_NUMBER)

I NPUT /

O UTPUT

continues

Ngày đăng: 15/12/2013, 05:15

TỪ KHÓA LIÊN QUAN