Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Database and LINQ Presented by : Yasser Deeb Fayez Salma Supervised by : Dr. Mohammed Al-Haji Dr. Mohammed Al-Haji.

Similar presentations


Presentation on theme: "Object Oriented Database and LINQ Presented by : Yasser Deeb Fayez Salma Supervised by : Dr. Mohammed Al-Haji Dr. Mohammed Al-Haji."— Presentation transcript:

1 Object Oriented Database and LINQ Presented by : Yasser Deeb Fayez Salma Supervised by : Dr. Mohammed Al-Haji Dr. Mohammed Al-Haji

2 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

3 Introduction Traditional Data Models : Hierarchical, Network (since mid-60’s), Relational (since 1970 and commercially since 1982) Traditional Data Models : Hierarchical, Network (since mid-60’s), Relational (since 1970 and commercially since 1982) Object Oriented (OO) Data Models since mid-90’s Object Oriented (OO) Data Models since mid-90’s Reasons for creation of Object Oriented Databases Reasons for creation of Object Oriented Databases Need for more complex applications Need for more complex applications Need for additional data modeling features Need for additional data modeling features Increased use of object-oriented programming languages Increased use of object-oriented programming languages Commercial OO Database products – several in the 1990’s, but did not make much impact on mainstream data management Commercial OO Database products – several in the 1990’s, but did not make much impact on mainstream data management Chapter 20-3

4 Overview of Object Oriented Database Management Systems An OODBMS is the result of combining object oriented programming principles with database management principles. An OODBMS is the result of combining object oriented programming principles with database management principles. Object oriented programming concepts such as encapsulation, polymorphism and inheritance. Object oriented programming concepts such as encapsulation, polymorphism and inheritance.

5 Relational Database Example StockItem abstract class and creating subclasses to represent the specific item types

6 Relational Database Example There is no single optimum strategy for mapping inheritance hierarchies to tables – the options include: There is no single optimum strategy for mapping inheritance hierarchies to tables – the options include:  one table per class  one table per concrete class All of these have drawbacks in one or more of performance, storage efficiency and maintenance, and the drawbacks become more significant as the model becomes more complex.

7 Bridging the Gap If you use a relational database and an object- oriented domain model, the impedance mismatch means that work has to be done someplace in your application to handle the mapping If you use a relational database and an object- oriented domain model, the impedance mismatch means that work has to be done someplace in your application to handle the mapping O/R mapping tools ( NHibernate and Microsoft’s own forthcoming LINQ/LINQ to SQL ) O/R mapping tools ( NHibernate and Microsoft’s own forthcoming LINQ/LINQ to SQL ) Object-oriented databases Object-oriented databases

8 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

9 ODL ODL is used to define persistent classes, those whose objects may be stored permanently in the database. ODL is used to define persistent classes, those whose objects may be stored permanently in the database. ODL classes look like Entity sets with binary relationships, plus methods. ODL classes look like Entity sets with binary relationships, plus methods. ODL class definitions are part of the extended, OO host language. ODL class definitions are part of the extended, OO host language.

10 ODL Overview A class declaration includes: A class declaration includes: 1. A name for the class. 2. Optional key declaration(s). 3. Extent declaration = name for the set of currently existing objects of the class. 4. Element declarations. An element is either an attribute, a relationship, or a method.

11 Class Definitions class { <list of element declarations, separated by semicolons> }

12 Attribute and Relationship Declarations Attributes are (usually) elements with a type that does not involve classes. Attributes are (usually) elements with a type that does not involve classes. attribute ; Relationships connect an object to one or more other objects of one class. Relationships connect an object to one or more other objects of one class. relationship relationship inverse ;

13 Inverse Relationships Suppose class C has a relationship R to class D. Suppose class C has a relationship R to class D. Then class D must have some relationship S to class C. Then class D must have some relationship S to class C. R and S must be true inverses. R and S must be true inverses. If object d is related to object c by R, then c must be related to d by S. If object d is related to object c by R, then c must be related to d by S. 13

14 Example: Attributes and Relationships class Bar { attribute string name; attribute string addr; relationship Set serves inverse Beer::servedAt; } class Beer { attribute string name; attribute string manf; relationship Set servedAt inverse Bar::serves; } The type of relationship serves is a set of Beer objects. The :: operator connects a name on the right to the context containing that name, on the left.

15 Types of Relationships The type of a relationship is either The type of a relationship is either 1. A class, like Bar. If so, an object with this relationship can be connected to only one Bar object. 2. Set : the object is connected to a set of Bar objects.

16 Multiplicity of Relationships All ODL relationships are binary. All ODL relationships are binary. Many-many relationships have Set for the type of the relationship and its inverse. Many-many relationships have Set for the type of the relationship and its inverse. Many-one relationships have Set in the relationship of the “one” and just the class for the relationship of the “many.” Many-one relationships have Set in the relationship of the “one” and just the class for the relationship of the “many.” One-one relationships have classes as the type in both directions. One-one relationships have classes as the type in both directions.

17 Example: Multiplicity class Drinker { … relationship Set likes inverse Beer::fans; relationship Beer favBeer inverse Beer::superfans; } class Beer { … relationship Set fans inverse Drinker::likes; relationship Set superfans inverse Drinker::favBeer; } Many-many uses Set in both directions. Many-one uses Set only with the “one.”

18 Method Declarations A class definition may include declarations of methods for the class. A class definition may include declarations of methods for the class. Information consists of: Information consists of: 1. Return type, if any. 2. Method name. 3. Argument modes and types (no names). w Modes are in, out, and inout. 4. Any exceptions the method may raise.

19 Example: Methods real gpa(in string)raises(noGrades); 1. The method gpa returns a real number (presumably a student’s GPA). 2. gpa takes one argument, a string (presumably the name of the student) and does not modify its argument. 3. gpa may raise the exception noGrades.

20 ODL Subclasses Usual object-oriented subclasses. Usual object-oriented subclasses. Indicate superclass with a colon and its name. Indicate superclass with a colon and its name. Subclass lists only the properties unique to it. Subclass lists only the properties unique to it. Also inherits its superclass’ properties. Also inherits its superclass’ properties.

21 Example: Subclasses Ales are a subclass of beers: Ales are a subclass of beers: class Car:Vehicle { attribute string color; }

22 ODL Keys You can declare any number of keys for a class. You can declare any number of keys for a class. After the class name, add: After the class name, add: (key ) A key consisting of more than one attribute needs additional parentheses around those attributes. A key consisting of more than one attribute needs additional parentheses around those attributes.

23 Example: Keys class Beer (key name) { … name is the key for beers. name is the key for beers. class Course (key (dept,number)){

24 Extents For each class there is an extent, the set of existing objects of that class. For each class there is an extent, the set of existing objects of that class. Think of the extent as the one relation with that class as its schema. Think of the extent as the one relation with that class as its schema. Indicate the extent after the class name, along with keys, as: Indicate the extent after the class name, along with keys, as: (extent … )

25 Example: Extents class Beer (extent Beers key name) { … } Conventionally, we’ll use singular for class names, plural for the corresponding extent. Conventionally, we’ll use singular for class names, plural for the corresponding extent.

26 OID OID Unique to object Unique to object Not a primary key Not a primary key

27 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

28 OQL OQL is the object-oriented query standard. OQL is the object-oriented query standard. It uses ODL as its schema definition language. It uses ODL as its schema definition language. Types in OQL are like ODL’s. Types in OQL are like ODL’s. Set(Struct) and Bag(Struct) play the role of relations. Set(Struct) and Bag(Struct) play the role of relations.

29 Path Expressions Let x be an object of class C. Let x be an object of class C. 1. If a is an attribute of C, then x.a is the value of that attribute. 2. If r is a relationship of C, then x.r is the value to which x is connected by r. w Could be an object or a set of objects, depending on the type of r. 3. If m is a method of C, then x.m (…) is the result of applying m to x.

30 Example: Path Expressions Let s be a variable of type Sell, i.e., a bar- beer-price object. Let s be a variable of type Sell, i.e., a bar- beer-price object. 1. s.price = the price in object s. 2. s.bar.addr = the address of the bar we reach by following the bar relationship in s. w Note the cascade of dots is OK here, because s.bar is an object, not a collection of objects.

31 Example: Illegal Use of Dot We cannot apply the dot with a collection on the left --- only with a single object. We cannot apply the dot with a collection on the left --- only with a single object. Example (illegal), with b a Bar object: Example (illegal), with b a Bar object:b.beersSold.price This expression is a set of Sell objects. It does not have a price.

32 OQL Select-From-Where We may compute relation-like collections by an OQL statement: We may compute relation-like collections by an OQL statement: SELECT SELECT FROM <list of collections and names for typical members> WHERE WHERE

33 FROM Clauses Each term of the FROM clause is: Each term of the FROM clause is: A collection can be: A collection can be: 1. The extent of some class. 2. An expression that evaluates to a collection, e.g., certain path expressions like b.beersSold.

34 Example Get the menu at Joe’s Bar. Get the menu at Joe’s Bar. SELECT s.beer.name, s.price FROM Sells s WHERE s.bar.name = “Joe’s Bar” Sells is the extent representing all Sell objects; s represents each Sell object, in turn. Legal expressions. s.beer is a beer object and s.bar is a Bar object. Notice OQL uses double-quotes.

35 Trick For Using Path Expressions If a path expression denotes an object, you can extend it with another dot and a property of that object. If a path expression denotes an object, you can extend it with another dot and a property of that object. Example: s, s.bar, s.bar.name. Example: s, s.bar, s.bar.name. If a path expression denotes a collection of objects, you cannot extend it, but you can use it in the FROM clause. If a path expression denotes a collection of objects, you cannot extend it, but you can use it in the FROM clause. Example: b.beersSold. Example: b.beersSold.

36 Subqueries A select-from-where expression can be surrounded by parentheses and used as a subquery in several ways, such as: A select-from-where expression can be surrounded by parentheses and used as a subquery in several ways, such as: 1. In a FROM clause, as a collection. 2. In EXISTS and FOR ALL expressions.

37 Example: Subquery in FROM Find the manufacturers of beers sold at Joe’s: Find the manufacturers of beers sold at Joe’s: SELECT DISTINCT b.manf FROM ( SELECT s.beer FROM Sells s WHERE s.bar.name = “Joe’s Bar” ) b Bag of Beer objects for the beers sold by Joe Technically a one-field struct containing a Beer object, but identified with that object itself.

38 Quantifiers Two boolean-valued expressions for use in WHERE clauses: Two boolean-valued expressions for use in WHERE clauses: FOR ALL x IN : FOR ALL x IN : EXISTS x IN : EXISTS x IN : True if and only if all members (resp. at least one member) of the collection satisfy the condition. True if and only if all members (resp. at least one member) of the collection satisfy the condition.

39 Example: EXISTS Find all names of bars that sell at least one beer for more than $5. Find all names of bars that sell at least one beer for more than $5. SELECT b.name FROM Bars b WHERE EXISTS s IN b.beersSold : s.price > 5.00 At least one Sell object for bar b has a price above $5.

40 Another Quantifier Example Find the names of all bars such that the only beers they sell for more than $5 are manufactured by Pete’s. Find the names of all bars such that the only beers they sell for more than $5 are manufactured by Pete’s. SELECT b.name FROM Bars b WHERE FOR ALL be IN ( SELECT s.beer FROM b.beersSold s WHERE s.price > 5.00 ) : be.manf = “Pete’s” Bag of Beer objects (inside structs) for all beers sold by bar b for more than $5. One-field structs are unwrapped automatically, so be may be thought of as a Beer object.

41 Simple Coercions As we saw, a one-field struct is automatically converted to the value of the one field. As we saw, a one-field struct is automatically converted to the value of the one field. Struct(f : x) coerces to x. Struct(f : x) coerces to x. A collection of one element can be coerced to that element, but we need the operator ELEMENT. A collection of one element can be coerced to that element, but we need the operator ELEMENT. E.g., ELEMENT(Bag(x )) = x. E.g., ELEMENT(Bag(x )) = x.

42 Aggregations AVG, SUM, MIN, MAX, and COUNT apply to any collection where they make sense. AVG, SUM, MIN, MAX, and COUNT apply to any collection where they make sense. Example: Find and assign to x the average price of beer at Joe’s: Example: Find and assign to x the average price of beer at Joe’s: x = AVG( SELECT s.price FROM Sells s WHERE s.bar.name = “Joe’s Bar” ); Bag of structs with the prices for the beers Joe sells.

43 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

44 DB4O db4o is the native Java,.NET and Mono open source object database. db4o is the native Java,.NET and Mono open source object database. Simple Simple Easy-to-use Easy-to-use Fast Fast

45 Opening the database // accessDb4o ObjectContainer db=Db4o.openFile(Util.YAPFILENAME); try { // do something with db4o } finally { db.close();}

46 Example in DB4O //create a class to hold our data package com.db4o.f1.chapter1; public class Pilot { private String name; private int points; public Pilot(String name,int points) { this.name=name;this.points=points;} public int getPoints() { return points; } public void addPoints(int points) { this.points+=points;} public String getName() { return name; } public String toString() { return name+"/"+points; }}

47 Storing objects // storeFirstPilot Pilot pilot1=new Pilot("Michael Schumacher",100); db.set(pilot1); System.out.println("Stored "+pilot1); OUTPUT: Stored Michael Schumacher/100

48 Updating objects // updatePilot ObjectSet result=db.get(new Pilot("Michael Schumacher",0)); Pilot found=(Pilot)result.next(); found.addPoints(11);db.set(found); System.out.println("Added 11 points for "+found); retrieveAllPilots(db);OUTPUT: Added 11 points for Michael Schumacher/111 2 Rubens Barrichello/99 Michael Schumacher/111

49 Deleting objects // deleteFirstPilotByName ObjectSet result=db.get(new Pilot("Michael Schumacher",0)); Pilot found=(Pilot)result.next(); PDF by iText, generated by Doctor, courtesy of db4objects Inc. db.delete(found); System.out.println("Deleted "+found); retrieveAllPilots(db);OUTPUT: Deleted Michael Schumacher/111 1 Rubens Barrichello/99

50 Quering Two querying systems: Two querying systems: Query-By-Example (QBE) Query-By-Example (QBE) Native Queries (NQ) Native Queries (NQ)

51 Query-By-Example (QBE) To retrieve all pilots from our database, we provide an 'empty' prototype: // retrieveAllPilotQBE Pilot proto=new Pilot(null,0); ObjectSet result=db.get(proto); listResult(result);OUTPUT:2 Rubens Barrichello/99 Michael Schumacher/100

52 // storePilots db.set(new Pilot("Michael Schumacher",100)); db.set(new Pilot("Rubens Barrichello",99)); Let's finds all pilots with a given name or a score within a given range Let's finds all pilots with a given name or a score within a given range

53 Native Queries (NQ) Query query=db.query(); query.constrain(Pilot.class); Query pointQuery=query.descend("points"); query.descend("name").constrain("Rubens Barrichello").or(pointQuery.constrain(new Integer(99)).greater().and(pointQuery.constrain(new Integer(199)).smaller())); ObjectSet result=query.execute(); listResult(result); OUTPUT: 2 PDF by iText, generated by Doctor, courtesy of db4objects Inc. Michael Schumacher/100 Rubens Barrichello/99

54 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

55 Transform UML class diagrams to ODL schemas

56 Class diagram Class diagram shows the static structure of an object-oriented model: object classes, internal structure, relationships. UML class and object diagram Class diagram showing two classes

57 Object diagram Object diagram shows instances that are compatible with a given class diagram. UML class and object diagram (cont.) Object diagram with two instances

58 Associations Association: Association: Named relationship among object classes Named relationship among object classes Association Role: Association Role: Role of an object in an association Role of an object in an association The end of an association where it connects to a class The end of an association where it connects to a class Multiplicity: Multiplicity: How many objects participate in an association. Lower-bound..Upper bound (cardinality) How many objects participate in an association. Lower-bound..Upper bound (cardinality)

59 Examples of association relationships of different degrees Lower-bound – upper-bound Represented as: 0..1, 0..*, 1..1, 1..* Similar to minimum/maximum cardinality rules in EER Unary Binary Ternary

60 Generalization/Specialization Subclass, superclass Subclass, superclass similar to subtype/supertype in EER similar to subtype/supertype in EER Common attributes, relationships, and operations Common attributes, relationships, and operations Disjoint vs. Overlapping Disjoint vs. Overlapping Complete (total specialization) vs. incomplete (partial specialization) Complete (total specialization) vs. incomplete (partial specialization) Abstract Class: no direct instances possible, but subclasses may have direct instances Abstract Class: no direct instances possible, but subclasses may have direct instances Concrete Class: direct instances possible Concrete Class: direct instances possible

61 Examples of generalization, inheritance, and constraints - Employee superclass with three subclasses Shared attributes and operations An employee can only be one of these subclasses An employee may be none of them. Specialized attributes and operations

62 Aggregation Aggregation: A part-of relationship between a component object and an aggregate object Aggregation: A part-of relationship between a component object and an aggregate object Composition: A stronger form of aggregation in which a part object belongs to only one whole object and exists only as part of the whole object Composition: A stronger form of aggregation in which a part object belongs to only one whole object and exists only as part of the whole object Recursive Aggregation: Composition where component object is an instance of the same class as the aggregate object Recursive Aggregation: Composition where component object is an instance of the same class as the aggregate object

63 63 Example of aggregation A Personal Computer includes CPU, Hard Disk, Monitor, and Keyboard as parts. But, these parts can exist without being installed into a computer. The open diamond indicates aggregation, but not composition

64 Object-Relational Data Models Extend the relational data model by including object orientation and constructs to deal with added data types. Extend the relational data model by including object orientation and constructs to deal with added data types. Allow attributes of tuples to have complex types, including non- atomic values such as nested relations. Allow attributes of tuples to have complex types, including non- atomic values such as nested relations. Preserve relational foundations, in particular the declarative access to data, while extending modeling power. Preserve relational foundations, in particular the declarative access to data, while extending modeling power. Upward compatibility with existing relational languages. Upward compatibility with existing relational languages.

65 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

66 Example of a Nested Relation Example: library information system Example: library information system Each book has Each book has title, title, a set of authors, a set of authors, Publisher, and Publisher, and a set of keywords a set of keywords Non-1NF relation books Non-1NF relation books

67 Structured Types and Inheritance in SQL Structured types can be declared and used in SQL Structured types can be declared and used in SQL create type Name as (firstname varchar(20), lastname varchar(20)) final create type Name as (firstname varchar(20), lastname varchar(20)) final create type Address as (street varchar(20), city varchar(20), zipcode varchar(20)) not final Note: final and not final indicate whether subtypes can be created Note: final and not final indicate whether subtypes can be created Structured types can be used to create tables with composite attributes Structured types can be used to create tables with composite attributes create table customer ( create table customer ( nameName, addressAddress, dateOfBirth date) Dot notation used to reference components: name.firstname Dot notation used to reference components: name.firstname

68 Structured Types (cont.) User-defined row types User-defined row types create type CustomerType as ( name Name, address Address, dateOfBirth date) not final Can then create a table whose rows are a user-defined type Can then create a table whose rows are a user-defined type create table customer of CustomerType

69 Methods Can add a method declaration with a structured type. Can add a method declaration with a structured type. method ageOnDate (onDate date) returns interval year Method body is given separately. Method body is given separately. create instance method ageOnDate (onDate date) returns interval year for CustomerType begin return onDate - self.dateOfBirth; end We can now find the age of each customer: We can now find the age of each customer: select name.lastname, ageOnDate (current_date) from customer

70 Inheritance Suppose that we have the following type definition for people: Suppose that we have the following type definition for people: create type Person (name varchar(20), address varchar(20)) Using inheritance to define the student and teacher types create type Student under Person (degree varchar(20), department varchar(20)) create type Teacher under Person (salary integer, department varchar(20)) Using inheritance to define the student and teacher types create type Student under Person (degree varchar(20), department varchar(20)) create type Teacher under Person (salary integer, department varchar(20)) Subtypes can redefine methods by using overriding method in place of method in the method declaration Subtypes can redefine methods by using overriding method in place of method in the method declaration

71 Multiple Inheritance SQL:1999 and SQL:2003 do not support multiple inheritance SQL:1999 and SQL:2003 do not support multiple inheritance If our type system supports multiple inheritance, we can define a type for teaching assistant as follows: create type Teaching Assistant under Student, Teacher If our type system supports multiple inheritance, we can define a type for teaching assistant as follows: create type Teaching Assistant under Student, Teacher To avoid a conflict between the two occurrences of department we can rename them To avoid a conflict between the two occurrences of department we can rename them create type Teaching Assistant under Student with (department as student_dept ), Teacher with (department as teacher_dept ) create type Teaching Assistant under Student with (department as student_dept ), Teacher with (department as teacher_dept )

72 Array and Multiset Types in SQL Example of array and multiset declaration: Example of array and multiset declaration: create type Publisher as (name varchar(20), branch varchar(20)) create type Book as (title varchar(20), author-array varchar(20) array [10], pub-date date, publisher Publisher, keyword-set varchar(20) multiset ) create type Publisher as (name varchar(20), branch varchar(20)) create type Book as (title varchar(20), author-array varchar(20) array [10], pub-date date, publisher Publisher, keyword-set varchar(20) multiset ) create table books of Book create table books of Book Similar to the nested relation books, but with array of authors instead of set Similar to the nested relation books, but with array of authors instead of set

73 Creation of Collection Values Array construction Array construction array [‘Silberschatz’,`Korth’,`Sudarshan’] array [‘Silberschatz’,`Korth’,`Sudarshan’] Multisets Multisets multisetset [‘computer’, ‘database’, ‘SQL’] multisetset [‘computer’, ‘database’, ‘SQL’] To create a tuple of the type defined by the books relation: (‘Compilers’, array[`Smith’,`Jones’], Publisher (`McGraw-Hill’,`New York’), multiset [`parsing’,`analysis’ ]) To create a tuple of the type defined by the books relation: (‘Compilers’, array[`Smith’,`Jones’], Publisher (`McGraw-Hill’,`New York’), multiset [`parsing’,`analysis’ ]) To insert the preceding tuple into the relation books To insert the preceding tuple into the relation books insert into books values (‘Compilers’, array[`Smith’,`Jones’], Publisher (`McGraw-Hill’,`New York’), multiset [`parsing’,`analysis’ ]) insert into books values (‘Compilers’, array[`Smith’,`Jones’], Publisher (`McGraw-Hill’,`New York’), multiset [`parsing’,`analysis’ ])

74 Querying Collection-Valued Attributes To find all books that have the word “database” as a keyword, To find all books that have the word “database” as a keyword, select title from books where ‘database’ in (unnest(keyword-set )) We can access individual elements of an array by using indices We can access individual elements of an array by using indices E.g.: If we know that a particular book has three authors, we could write: E.g.: If we know that a particular book has three authors, we could write: select author-array[1], author-array[2], author-array[3] from books where title = `Database System Concepts’ To get a relation containing pairs of the form “title, author-name” for each book and each author of the book To get a relation containing pairs of the form “title, author-name” for each book and each author of the book select B.title, A.author select B.title, A.author from books as B, unnest (B.author-array) as A (author ) To retain ordering information we add a with ordinality clause To retain ordering information we add a with ordinality clause select B.title, A.author, A.position select B.title, A.author, A.position from books as B, unnest (B.author-array) with ordinality as A (author, position )

75 Unnesting The transformation of a nested relation into a form with fewer (or no) relation-valued attributes is called unnesting. The transformation of a nested relation into a form with fewer (or no) relation-valued attributes is called unnesting. E.g. E.g. select title, A.author, publisher.name as pub_name, publisher.branch as pub_branch, K.keyword select title, A.author, publisher.name as pub_name, publisher.branch as pub_branch, K.keyword from books as B, unnest(B.author_array ) as A (author ), from books as B, unnest(B.author_array ) as A (author ), unnest (B.keyword_set ) as K (keyword )

76 User Generated Identifiers The type of the object-identifier must be specified as part of the type definition of the referenced table, and The type of the object-identifier must be specified as part of the type definition of the referenced table, and The table definition must specify that the reference is user generated The table definition must specify that the reference is user generated create type Person (name varchar(20) address varchar(20)) ref using varchar(20) create table people of Person ref is person_id user generated create type Person (name varchar(20) address varchar(20)) ref using varchar(20) create table people of Person ref is person_id user generated When creating a tuple, we must provide a unique value for the identifier: When creating a tuple, we must provide a unique value for the identifier: insert into people (person_id, name, address ) values (‘01284567’, ‘John’, `23 Coyote Run’) insert into people (person_id, name, address ) values (‘01284567’, ‘John’, `23 Coyote Run’) We can then use the identifier value when inserting a tuple into departments We can then use the identifier value when inserting a tuple into departments Avoids need for a separate query to retrieve the identifier: Avoids need for a separate query to retrieve the identifier: insert into departments values(`CS’, `02184567’) insert into departments values(`CS’, `02184567’)

77 User Generated Identifiers (Cont.) Can use an existing primary key value as the identifier: Can use an existing primary key value as the identifier: create type Person (name varchar (20) primary key, address varchar(20)) ref from (name) create table people of Person ref is person_id derived When inserting a tuple for departments, we can then use When inserting a tuple for departments, we can then use insert into departments values(`CS’,`John’)

78 Path Expressions Find the names and addresses of the heads of all departments: Find the names and addresses of the heads of all departments: select head –> name, head –> address from departments An expression such as “head –> name” is called a path expression An expression such as “head –> name” is called a path expression Path expressions help avoid explicit joins Path expressions help avoid explicit joins If department head were not a reference, a join of departments with people would be required to get at the address If department head were not a reference, a join of departments with people would be required to get at the address Makes expressing the query much easier for the user Makes expressing the query much easier for the user

79 Implementing O-R Features Similar to how E-R features are mapped onto relation schemas Similar to how E-R features are mapped onto relation schemas Subtable implementation Subtable implementation Each table stores primary key and those attributes defined in that table Each table stores primary key and those attributes defined in that tableor, Each table stores both locally defined and inherited attributes Each table stores both locally defined and inherited attributes

80 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

81 OODBMS Arguments More semantic information More semantic information Support for complex objects Support for complex objects Extensibility of data types Extensibility of data types May improve performance? May improve performance? with efficient caching with efficient caching Reusability Reusability Potential to integrate DBMSs into single environment Potential to integrate DBMSs into single environment

82 OODBMS Arguments Low market presence Low market presence Strong opposition from the established RDBMSs Strong opposition from the established RDBMSs Lack of theoretical foundation Lack of theoretical foundation Standard query language? Standard query language? Lack of business data design and management tools, administration, recovery, olap ….. Lack of business data design and management tools, administration, recovery, olap ….. Steep learning curve? Steep learning curve? Lack of compatibility between different OODBMSs Lack of compatibility between different OODBMSs

83 Current Applications of ODBMSs The Chicago Stock Exchange manages stock trades via a Versant ODBMS. The Chicago Stock Exchange manages stock trades via a Versant ODBMS. Ajou University Medical Center in South Korea uses InterSystems' Cachè ODBMS to support all hospital functions including mission-critical departments such as pathology, laboratory, blood bank, pharmacy, and X-ray. Ajou University Medical Center in South Korea uses InterSystems' Cachè ODBMS to support all hospital functions including mission-critical departments such as pathology, laboratory, blood bank, pharmacy, and X-ray.

84 Current Applications of ODBMSs The Large Hadron Collider at CERN in Switzerland uses an Objectivity DB. The database is currently being tested in the hundreds of terabytes at data rates up to 35 MB/second. The Large Hadron Collider at CERN in Switzerland uses an Objectivity DB. The database is currently being tested in the hundreds of terabytes at data rates up to 35 MB/second. As of November, 2000, the Stanford Linear Accelerator Center (SLAC) stored 169 terabytes of production data using Objectivity/DB. The production data is distributed across several hundred processing nodes and over 30 on-line servers. As of November, 2000, the Stanford Linear Accelerator Center (SLAC) stored 169 terabytes of production data using Objectivity/DB. The production data is distributed across several hundred processing nodes and over 30 on-line servers.

85 Plan Introduction Introduction ODL ODL OQL OQL OODBMS Example: DB4O OODBMS Example: DB4O Transform UML class diagrams to ODL schemas Transform UML class diagrams to ODL schemas ORDBMS ORDBMS OODBMS Arguments OODBMS Arguments Microsoft LINQ Overview Microsoft LINQ Overview

86 Introduction Language Integrated Query Language Integrated Query New in.NET Framework 3.0 New in.NET Framework 3.0 Accessing multiple data sources Accessing multiple data sources

87 Types of Data Sources Relational Relational MS SQL, MySQL, IBM DB2, Oracle 10i MS SQL, MySQL, IBM DB2, Oracle 10i Tables, Indexes, Relationships Tables, Indexes, Relationships ADO.NET, Ole, ODBC ADO.NET, Ole, ODBC XML XML Hierarchical Text File Hierarchical Text File XPath, XmlReader (forward only), XmlDocument XPath, XmlReader (forward only), XmlDocument Object Object Array, List, LinkedList, Dictionary, Graph Array, List, LinkedList, Dictionary, Graph Object graph Object graph IEnumerable (for each) IEnumerable (for each)

88 Query without LINQ Objects using loops and conditions foreach(Customer c in customers) if (c.Region == "UK")... Objects using loops and conditions foreach(Customer c in customers) if (c.Region == "UK")... Databases using SQL SELECT * FROM Customers WHERE Region='UK' Databases using SQL SELECT * FROM Customers WHERE Region='UK' XML using XPath/XQuery //Customers/Customer[@Region='UK'] XML using XPath/XQuery //Customers/Customer[@Region='UK']

89 ADO without LINQ SqlConnection con = new SqlConnection(...); con.Open(); SqlCommand cmd = new SqlCommand( @"SELECT * FROM Customers @"SELECT * FROM Customers WHERE c.Region = @Region", con WHERE c.Region = @Region", con); cmd.Parameters.AddWithValue("@Region", "UK"); DataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string name = dr.GetString(dr.GetOrdinal("Name")); string name = dr.GetString(dr.GetOrdinal("Name")); string phone = dr.GetString(dr.GetOrdinal("Phone")); string phone = dr.GetString(dr.GetOrdinal("Phone")); DateTime date = dr.GetDateTime(3); DateTime date = dr.GetDateTime(3);}dr.Close();con.Close();

90 Query with LINQ C# var myCustomers = from c in customers where c.Region == "UK" select c; C# var myCustomers = from c in customers where c.Region == "UK" select c; VB.NET Dim myCustomers = From c In customers _ Where c.Region = "UK" _ Select c VB.NET Dim myCustomers = From c In customers _ Where c.Region = "UK" _ Select c

91 More LINQ queries C# var goodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY") orderby c.Sales descending select c).Skip(10).Take(10); C# var goodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY") orderby c.Sales descending select c).Skip(10).Take(10); VB.NET Dim goodCusts = (From c In db.Customers _ Where c.PostCode.StartsWith("GY") _ Order By c.Sales Descending _ Select c).Skip(1).Take(10) VB.NET Dim goodCusts = (From c In db.Customers _ Where c.PostCode.StartsWith("GY") _ Order By c.Sales Descending _ Select c).Skip(1).Take(10)

92 LINQ operators AggregateConversionOrderingPartitioningSets Aggregate Average Count Max Min Sum Cast OfType ToArray ToDictionary ToList ToLookup ToSequence OrderBy ThenBy Descending Reverse Skip SkipWhile Take TakeWhile Concat Distinct Except Intersect Union

93 LINQ to Objects Query any IEnumerable source Includes arrays, List, Dictionary... Query any IEnumerable source Includes arrays, List, Dictionary... C# int[] nums = new int[] {0,4,2,6,3,8,3,1}; double average = nums.Take(6).Average(); var above = from n in nums where n > average select n; C# int[] nums = new int[] {0,4,2,6,3,8,3,1}; double average = nums.Take(6).Average(); var above = from n in nums where n > average select n; VB.NET Dim nums() As Integer = {0,4,2,6,3,8,3,1} Double average = nums.Take(6).Average() Dim above = From n In nums _ Where n > average _ Select n VB.NET Dim nums() As Integer = {0,4,2,6,3,8,3,1} Double average = nums.Take(6).Average() Dim above = From n In nums _ Where n > average _ Select n

94 LINQ to XML Power of Linq brought to data in XML format Power of Linq brought to data in XML format Perform queries over XML data Perform queries over XML data New API to manipulate XML New API to manipulate XML Alternative to XML DOM API Alternative to XML DOM API Create XML data with query expressions Create XML data with query expressions

95 LINQ to XML static class HelloLinqToXml { static void Main() { Book[] books = new Book[] { new Book("Ajax in Action", "Manning", 2005), new Book("Windows Forms in Action", "Manning", 2006), new Book("RSS and Atom in Action", "Manning", 2006) }; XElement xml = new XElement("books", from book in books where book.Year == 2006 select new XElement("book", new XAttribute("title", book.Title), new XElement("publisher", book.Publisher) ) ); Console.WriteLine(xml); } }

96 LINQ to SQL Object-relational mapping Records become strongly-typed objects Object-relational mapping Records become strongly-typed objects Data context is the controller mechanism Data context is the controller mechanism Facilitates update, delete & insert Facilitates update, delete & insert Translates LINQ queries behind the scenes Translates LINQ queries behind the scenes Type, parameter and injection safe Type, parameter and injection safe

97 Database mapping VS 2008 designer or SQLMetal command VS 2008 designer or SQLMetal command Map tables & fields to classes & properties Map tables & fields to classes & properties Generates partial classes with attributes Generates partial classes with attributes Each record becomes an object Each record becomes an object Data context represents the database Data context represents the database Utilise tables, views or stored procedures Utilise tables, views or stored procedures

98 Database mapping

99 LINQ to SQL Update Set object properties Update Set object properties Delete context.Table.DeleteOnSubmit(object) Delete context.Table.DeleteOnSubmit(object) Insert context.Table.InsertOnSubmit(object) Insert context.Table.InsertOnSubmit(object) Commit changes back context.SubmitChanges() Transactional - all or nothing Commit changes back context.SubmitChanges() Transactional - all or nothing

100 Update example

101 Insert,delete example

102 Linq under Cover How linq works

103 Language enhancements: Extension methods Project instance methods onto existing classes Project instance methods onto existing classes Declared in static class with static methods Declared in static class with static methods Introducing another this keyword Introducing another this keyword Type of first argument defines class to extend Type of first argument defines class to extend Compiler emits [ExtensionAttribute] to class and extension methods Compiler emits [ExtensionAttribute] to class and extension methods Import namespace to bring extension methods into scope Import namespace to bring extension methods into scope Instance methods take precedence over static Instance methods take precedence over static

104 Extension methods example public static class Helper { public static void sayHello(this string source{ Console.writeln(“Hello ”+source); }} //now to call it String s = “world”; s.sayHello();//equivalent to Helper.sayHello(s);

105 Language enhancements: Object initializers New way to initialize an object on creation New way to initialize an object on creation No need to provide or use complex constructors No need to provide or use complex constructors No need to set individual properties or fields No need to set individual properties or fields Object initializer takes any number of accessible fields or properties Object initializer takes any number of accessible fields or properties Blog b = new Blog { Name = “Alex Thissen”, SubTitle = “Disassembling my brain” }; Name of field/property must be specified Name of field/property must be specified

106 Language enhancements: Collection initializers Compact initialization of collections Compact initialization of collections Collection must implement ICollection Collection must implement ICollection List names = new List List names = new List { “Nicole”, “Lieke”, “Alex” };

107 Language enhancements: Anonymous types Static type is inferred at compile time Static type is inferred at compile time Intellisense infers type to allow auto-completion Intellisense infers type to allow auto-completion Keyword var specifies an inferred type Keyword var specifies an inferred type Introduced in C# 2.0 with anonymous delegates Introduced in C# 2.0 with anonymous delegates Extended in C# 3.0 Extended in C# 3.0 var name = "Ian"; var age = 24; var person = new { Name = "Ian", Age = 24 }; var names = new [] { "Ian", "Jacko", "Smale" }; foreach (var item in names)

108 Language enhancements: lambda Expressions C# 1.0 gave us delegates C# 1.0 gave us delegates Type safe function pointers Type safe function pointers C# 2.0 gave us anonymous delegates C# 2.0 gave us anonymous delegates Type safe anonymous function pointers Type safe anonymous function pointers C# 3.0 gives us lambda expressions C# 3.0 gives us lambda expressions We can think of these as shortcuts to specifying anonymous functions We can think of these as shortcuts to specifying anonymous functions But, lambda expressions evaluate to expression trees, not function pointers (important) But, lambda expressions evaluate to expression trees, not function pointers (important)

109 Lambda Expression Example Function Function int StringLength(String s) { return s.Length(); } Anonymous Delegate Anonymous Delegate delegate (String s) { return s.Length(); } Lambda Expression Lambda Expression s => s.Length();

110 LINQ

111 Advantages LINQ abstracts the data source LINQ abstracts the data source Unified data access Single syntax: Declarative approach makes queries easier to understand and more compact Unified data access Single syntax: Declarative approach makes queries easier to understand and more compact Strongly typed Catch errors during compilation Strongly typed Catch errors during compilation IntelliSense Prompt for syntax and attributes IntelliSense Prompt for syntax and attributes Expandable to new data sources (maybe) Expandable to new data sources (maybe)

112 Limitations LINQ Only defines query, not update Only defines query, not update Need to learn a new Query Language Need to learn a new Query Language LINQ To SQL Type-safety for object data sources only Type-safety for object data sources only Still need casting and ORM mapper (SQLMetal) Still need casting and ORM mapper (SQLMetal) Inevitable inconsistencies between provider - impedance mismatch is still present Inevitable inconsistencies between provider - impedance mismatch is still present There will always be some things you can do in SQL but not in LINQ There will always be some things you can do in SQL but not in LINQ Performance of Linq to SQL is comparitively low compared to hardcoded DAL as it is going to generate SQL on the runtime which would definitely be slowr compared to hard coded SQL statements written to best fit for a specific database like sql server, oracle etc. Performance of Linq to SQL is comparitively low compared to hardcoded DAL as it is going to generate SQL on the runtime which would definitely be slowr compared to hard coded SQL statements written to best fit for a specific database like sql server, oracle etc. Microsoft SQL Server 2000, 2005 only Microsoft SQL Server 2000, 2005 only

113 Limitations Cont’d LINQ To SQL Not all CLR functions can be translated to a database equivalent. Consider the following query: Not all CLR functions can be translated to a database equivalent. Consider the following query: var query = from book in books where book.PubDate >= DateTime.Parse("1/1/2007"); //works select book.PubDate.Value.ToString("MM/dd/yyyy"); //fails And Identifying all of the supported and unsupported expressions that are translated is impossible

114 Questions


Download ppt "Object Oriented Database and LINQ Presented by : Yasser Deeb Fayez Salma Supervised by : Dr. Mohammed Al-Haji Dr. Mohammed Al-Haji."

Similar presentations


Ads by Google