package com.db4o.samples;

import com.db4o.*;
import com.db4o.lib.Logger;

public class S15_Update_Per_Object
{
	public static void main(String[] args)
	{
		Logger.log("*** S15 Update Per Object");
		Individual templateAlice = new Individual();
		templateAlice.firstName = "Alice";
		templateAlice.addresses = new Address[0];
		ObjectContainer db = Db4o.openFile("samples.yap");
		Individual alice = (Individual)db.get(templateAlice).next();
		
		
		alice.addresses[0].street = "Rabbit Way 1";
		db.set(alice);
		// This call did NOT update the Address in the database.
		// Every Persistent object has to be updated with 
		// an explicit call to set() individually
		
		// Only new members are added automatically upon a call to set().

		
		db.close();
		Logger.log("Alice Adress unchanged:");
		logAlice();  // A small function to reopen the database and log the contents of 'Alice'.
		
		
		// Now the right way:
		db = Db4o.openFile("samples.yap");
		alice = (Individual)db.get(templateAlice).next();
		alice.addresses[0].street = "Rabbit Way 1";
		
		
		db.set(alice.addresses[0]);
		// set() is called for the object that really was updated.
		
		
		db.close();
		Logger.log("After the call to set() with alice.addresses[0]:");
		logAlice();  // A small function to reopen the database and log the contents of 'Alice'.
	}
	
	
	public static void logAlice(){
		Logger.log("Logging Alice and her Address.");
		ObjectContainer db = Db4o.openFile("samples.yap");
		Individual templateAlice = new Individual();
		templateAlice.firstName = "Alice";
		templateAlice.addresses = new Address[0];
		Logger.log(db, db.get(templateAlice).next());
		db.close();
	}
}
