Sunteți pe pagina 1din 8

Baze de date orientate obiect – lucrări de laborator

Laborator 12 – db4o

Stocarea obiectelor în db4o

Stocarea unui obiect nou în db4o se face prin apelul metodei store din database
container object. Dacă se dorește efectuarea unei actualizări a unui obiect deja
existent în baza de date, este apelată aceeași metodă deoarece db4o folosește
unique object identifiers din .NET sau Java pentru a determina dacă un obiect este
nou sau nu.
Următorul exemplu arată mecanismul stocării obiectelor în db4o:

class Person
{
private string name;
private Address address;
private string phoneNumber;

public Person(string name, Address address, string phoneNumber)


{
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}

public Person()
{
}

public Address CurrentAddress


{
get
{
return address;
}
}

public override string ToString()


{
return name + “ – “ + address.ToString() + “ – “ + phoneNumber;
}
}

45 din 52
Baze de date orientate obiect – lucrări de laborator

class Address
{
private string street;
private string city;

public Address(string street, string city)


{
this.street = street;
this.city = city;
}

public override string ToString()


{
return street + “ – “ + city;
}
}

Address address = new Address("Blvd. Mangeron", "Iasi");


Person person = new Person(“Mihaela Radulescu”, address, “111111”);

try
{
// Opens the database file and creates a new instance of the IObjectContainer interface.
IObjectContainer db = Db4oFactory.OpenFile("Persons.yap");

// Stores the new person.


db.Store(person);

// Commits the transaction.


db.Commit();
}

catch (Exception)
{
// Rolls the transaction back, in case of failures.
db.Rollback();
}

finally
{
// Closes the database.
db.Close();
}

Interogarea obiectelor în db4o

Sunt trei modele de interogari:


1. Query by Example - QBE,
2. Native Queries NQ și
3. SODA Query API (SODA).

46 din 52
Baze de date orientate obiect – lucrări de laborator

Query by Example

Pentru a folosi această metodologie, este obligatorie crearea unui template


object, (obiect șablon) care este o instanțiere a clasei căutate. Dacă unul sau mai
multe atribute din acest obiect șablon conțin date, atunci db4o caută obiecte în baza
de date cu atribute care se potrivesc datelor din șablon. Obiectele găsite sunt
returnate de interogare într–un set numit IObjectSet.
Atributele care nu au valori atribuite, şi au valorile implicite null sau zero (depinde
de tipul de atribut – primitiv sau neprimitiv) sunt găsite întotdeauna. Ca o consecință,
dacă un obiect nu are valori în atribute, atunci toate obiectele din clasa respectivă se
vor potrivi căutării, iar interogarea va returna toate obiectele clasei.
Interogarea de mai jos va returna toate persoanele din baza de date:

47 din 52
Baze de date orientate obiect – lucrări de laborator

Person person = new Person();

try
{
// Opens the database file and creates a new instance of the IObjectContainer interface.
IObjectContainer db = Db4oFactory.OpenFile("Persons.yap");

// Retrieves all the persons in the database.


IObjectSet personsSet = db.QueryByExample(person);

// Prints the results on the screen.


PrintResults(personsSet);
}

finally
{
// Closes the database.
db.Close();
}

private void PrintResult(IObjectSet results)


{
while (results.HasNext() == true)
Console.WriteLine(((Person)results.Next()).ToString());
}

Native Query

Native Query este metoda recomandată pentru interogarea obiectelor în db4o.


Aceasta, intern, se bazează pe SODA Query, de unde şi performanțele identice în
materie de consum al resurselor (procesor, timpi de citire, etc.)
Native Query utilizează principiile orientat–obiect type safe, compile-time checked
și refactorable.

class Customer
{
private string name;
private int age;
private int discount;

public Customer(string name, int age, int discount)


{
this.name = name;
this.age = age;
this.discount = discount;
}

48 din 52
Baze de date orientate obiect – lucrări de laborator

public Age CurrentAge


{
get
{
return age;
}
}

public override string ToString()


{
return name + “ – “ + age.ToString() + “ – “ + discount.ToString();
}
}

try
{
// Opens the database file and creates a new instance of the IObjectContainer interface.
IObjectContainer db = Db4oFactory.OpenFile("Customers.yap");

// Retrieves all the customers in the database, whose age attribute is between 35 and 50
IList<Customer> customersList = db.Query<Customer>(delegate(Customer customer)
{
return customer.CurrentAge >= 35 && customer.CurrentAge <= 50;
});

// Prints the results on the screen.


PrintResults(customersList);
}

finally
{
// Closes the database.
db.Close();
}

private void PrintResult(IList<Customer> results)


{
foreach (Customer customer in results)
Console.WriteLine(customer.ToString());
}

SODA Query

SODA Query este primul tip de interogare introdus de db4o şi încă este folosit intern în
implementarea Native Query. Ideea de bază la SODA este construirea unui graf al
interogării. Rezultatul este rapid deoarece graful este o structură care poate fi traversată
rapid. Metoda este mai complicată de folosit deoarece trebuie definit explicit graful. Din acest
motiv este de preferat Native Query deoarece acesta folosește construcții proprii limbajelor
de programare care sunt apoi translate automat de db4o în graf.

49 din 52
Baze de date orientate obiect – lucrări de laborator

Exemplul de mai jos returnează toate obiectele Customer cu atributul vârsta cuprins între
35 şi 50.

try
{
// Opens the database file and creates a new instance of the IObjectContainer interface.
IObjectContainer db = Db4oFactory.OpenFile("Customers.yap");

// Creates a new IQuery object


IQuery initialQuery = db.Query();

// Constrains the returned object to instances of the Customer class


query.Constrain(typeof(Customer));

// Reaches the age attribute of a Person


IQuery ageQuery = query.Descend("age");

// Constrains the age attribute to be between 35 and 50


ageQuery. Constrain(34).Greater();
ageQuery. Constrain(51).Smaller();

// Executes the query


IObjectSet results = query.Execute();

// Prints the results on the screen


PrintResults(results);
}

finally
{
// Closes the database.
db.Close();
}

private void PrintResult(IObjectSet results)


{
while (results.HasNext() == true)
Console.WriteLine(((Customer)results.Next()).ToString());
}

50 din 52
Baze de date orientate obiect – lucrări de laborator

Exemplu complet din tutorialul Formula1 în java:


package com.db4odoc.f1.chapter1;

import java.io.*;
import com.db4o.*;
import com.db4odoc.f1.*;

public class FirstStepsExample extends Util {


final static String DB4OFILENAME = System.getProperty("user.home")
+ "/formula1.db4o";

public static void main(String[] args) {


new File(DB4OFILENAME).delete();
accessDb4o();
new File(DB4OFILENAME).delete();
ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
.newConfiguration(), DB4OFILENAME);
try {
storeFirstPilot(db);
storeSecondPilot(db);
retrieveAllPilots(db);
retrievePilotByName(db);
retrievePilotByExactPoints(db);
updatePilot(db);
deleteFirstPilotByName(db);
deleteSecondPilotByName(db);
} finally {
db.close();
}
}

public static void accessDb4o() {


ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
.newConfiguration(), DB4OFILENAME);
try {
// do something with db4o
} finally {
db.close();
}
}
public static void storeFirstPilot(ObjectContainer db) {
Pilot pilot1 = new Pilot("Michael Schumacher", 100);
db.store(pilot1);
System.out.println("Stored " + pilot1);
}
public static void storeSecondPilot(ObjectContainer db) {
Pilot pilot2 = new Pilot("Rubens Barrichello", 99);
db.store(pilot2);
System.out.println("Stored " + pilot2);
}
public static void retrieveAllPilotQBE(ObjectContainer db) {
Pilot proto = new Pilot(null, 0);
ObjectSet result = db.queryByExample(proto);
listResult(result);
}

51 din 52
Baze de date orientate obiect – lucrări de laborator

public static void retrieveAllPilots(ObjectContainer db) {


ObjectSet result = db.queryByExample(Pilot.class);
listResult(result);
}

public static void retrievePilotByName(ObjectContainer db) {


Pilot proto = new Pilot("Michael Schumacher", 0);
ObjectSet result = db.queryByExample(proto);
listResult(result);
}

public static void retrievePilotByExactPoints(ObjectContainer db)


{
Pilot proto = new Pilot(null, 100);
ObjectSet result = db.queryByExample(proto);
listResult(result);
}

public static void updatePilot(ObjectContainer db) {


ObjectSet result = db
.queryByExample(new Pilot("Michael Schumacher", 0));
Pilot found = (Pilot) result.next();
found.addPoints(11);
db.store(found);
System.out.println("Added 11 points for " + found);
retrieveAllPilots(db);
}
public static void deleteFirstPilotByName(ObjectContainer db) {
ObjectSet result = db
.queryByExample(new Pilot("Michael Schumacher", 0));
Pilot found = (Pilot) result.next();
db.delete(found);
System.out.println("Deleted " + found);
retrieveAllPilots(db);
}
public static void deleteSecondPilotByName(ObjectContainer db) {
ObjectSet result = db
.queryByExample(new Pilot("Rubens Barrichello", 0));
Pilot found = (Pilot) result.next();
db.delete(found);
System.out.println("Deleted " + found);
retrieveAllPilots(db);
}

Laborator 13 – testare colocviu

52 din 52

S-ar putea să vă placă și