= XML Database, XPath/XQuery 3.0 Processor

  • Open Source (BSD-licensed), platform independent
  • supp. W3C Update
  • supp. Full Text
  • supp. logging


  1. BaseX XQuery Processor
  2. BaseX Server
  3. BaseX GUI

BaseX XQuery Processor

XQuery 3.0

map operator !
group by, switch
try/catch - handle errors at runtime
function items ~ lambda functions
string Concatenations - 'Hello' || ' ' || 'Universe'
context items
functions - eg. math:pi(), fn:analyze-string(), fn:format-dateTime(), count


Full Text

W3C XQuery Full Text 1.0 - for information retrieval systems
wildcards, stemming, diactritics


XML <-> JSON conversion


XQuery Update Facility 1.0 - inserting, deleting, renaming and replacing nodes.


file system operations, such as reading, or writing files and directories.

Java Bindings

Direct access to Java procedures and object manipulation


implementation of maps in XQuery

Execution Plan

Each evaluation procedure can be visualized with individual steps and index accesses


Via Saxon


BaseX Client/Server Architecture

Server: Port 1984, starting: basexserver, stoping: basexserver stop
Client: starting: basexclient, username: admin, password: admin
HTTP Server: default on Jetty Web Server at 8984, starting: basexhttp

Clients in several programming languages.
Transaction Management
User Management - secure auth
Transaction Logging
WebDAV Server
REST Server


  • Server Administration
  • realtime XQuery editor
  • interactive visualizations


addressed by their unique database path
Collection - database with more than one documents


basex - standalone (embedded)
basexclient, basexserver

Getting started


  • GUI APP (Mac/Windows version)
  • ZIP Archive - move to your location (eg. /Users/strajk/bin/basex) and add /Users/strajk/bin/basex/bin to system PATH
  • try which basex on terminal


| Java Virtual Machine with Java 1.6

Starting GUI

  • From downloaded installer
  • From downloaded zip
    The GUI can be started as follows (get more information on all Startup Options):
    • Double click on the BaseX.jar file.
    • Run one of the basexgui or basexgui.bat scripts.
    • Execute the following command: java -cp BaseX.jar org.basex.BaseXGUI
    • On Windows: Double click on the BaseX GUI icon.
    • For Maven users: type in mvn exec:java in the main directory of the basex project.

world Find tags and texts containing world
=world Find exact matching text nodes
~world Find text nodes similar to world
@world Find attributes and attribute values
@=world Find exact attribute values
"united world" Find tags and texts containing the phrase "united world"

Creating DB

CREATE DB »name-of-db« »full-path-to-resource-xml-file«       OPEN »name-of-db«
XQUERY //people/person/name
XQUERY doc("»name-of-db«")//country
SHOW DATABASES --> show currently opened databases
INFO --> about currently opened db
LIST --> show databases with info
CREATE BACKUP »name-of-db«, RESTORE »name-of-db« --> ~/BaseXData/»name-of-db«

Parsing data into BaseX

Can parse xml, html, json, csv, text

  • Internal - fault-tollerant
  • Java SAXParser
SET DTD true

Java Templating Engines

separation between the actual view logic and the rendered view

General purpose


What to do with teplates?

template = report design = master page
merge data (dynamic) into template (static) -> final document
data are usually in a form of Container or Collection (eg. HashMap)
data are accessible in teplate through special classes (eg. context or model)


  • Template Engine
  • Content Resource
  • Template Resource


  1. Instantiate an template engine
  2. feed it with data
  3. call a parse()


  • general purpose (HTML, XML, RTF, …)
  • good for MVC (replaces JSP)
  • support JSP taglibs
  • internationalization - charset, number formating, date formating, language variation of templates
  • replacement of Velocity
  • replacement of XLST

${...} interpolations
FTL tags - starts with #, refers to directives (as HTML tag

refers t o HTML element

  • predefined # bezobsahove se neuzaviraji
  • user @ bezobsahove se uzaviraji
    Comments <#-- -->
    Anything else static text

doesn't tolerate the referring to missing variables unless you tell them explicitly what to do if the variable is missing.
Scalars: String, Number, Boolean, Date. Containers: Hash, Sequence

${user!"Anonymous"} - default value
${cargo.weight!(item.weight * itemCount + 10)}
<#if user??> ${user} is defined </#if>
${user.weight / 2 + 100}


<#include "/footer.ftml">



<#if someBoolean>It was right</#if>
<#if user == "Strajk">Welcome back, admin!</#if>
<#if offer.icecream.price == 0>Free ice-cream!</#if>


<#list animals as being>${} ${being.type}</#list>


boolean arithmetic
${"green " + "mouse"?upper_case}   <#-- green MOUSE -->


<#assign mouse = "Jerry">
${} - computer audience, disable locale formating
${married?string("yes", "no")}.

macros (+params)

<#macro greet person="Anonymous" where>
  <h1>Hello ${person}, welcome to ${where}!</h1>
<@greet person="Fred"/>
<#macro wrapper>
  <div class="wrapper">
<@border>Gift to be wrapped</@border>


output transformation (eg. escaping HTML)

public class FreemarkerExample extends TemplateExample{

    Configuration config = new Configuration();
    Template freemarkerTemplate;
    OutputStreamWriter output = new OutputStreamWriter(System.out);

    Map<String,String> dataModel = new HashMap<String,String>();

    public FreemarkerExample(String user){
        this.user = user;
        dataModel.put("user", this.user);

    public void print() {
        try {
            freemarkerTemplate = new Template("Template", new StringReader("Hello Freemarker, I'm ${user}\n"), config);
            freemarkerTemplate.process(this.dataModel, this.output);
        } catch (TemplateException e) {
        } catch (IOException e) {


    public void printFromFile() {
        try {
            freemarkerTemplate = config.getTemplate("templates/freemarker.xml");
            freemarkerTemplate.process(this.dataModel, this.output);
        } catch (TemplateException e) {
        } catch (IOException e) {


public class VelocityExample extends TemplateExample {

    VelocityEngine engine = new VelocityEngine();
    VelocityContext context = new VelocityContext();

    public VelocityExample(String user) {
        this.user = user;
        context.put("user", this.user);

    public void print() {
        StringWriter writer = new StringWriter();
        StringReader reader = new StringReader("\nHello Velocity, I'm $user\n");
        try {
            Velocity.evaluate(context, writer, this.user, reader);
            System.out.println( writer.toString() );
        } catch (Exception e) {

    public void printFromFile() {
        StringWriter writer = new StringWriter();
        try {
            Template template = engine.getTemplate("templates/velocity.vm");
            template.merge( context, writer );
            System.out.println( writer.toString() );
        } catch (Exception e) {
Hello, ${name}!

#foreach($engineName in $engineNames)
  Hello, ${engineName} world!

#if ($engineName = "Velocity")
  Hello, $engineName world!
  Hello, other world!

Hello $engineName world!


public class StringTemplateExample extends TemplateExample{

    StringTemplate template = new StringTemplate("Hello StringTemplate, I'm $user$");

    public StringTemplateExample(String user) {
        this.user = user;
        template.setAttribute("user", this.user);

    public void print(){

    public void printFromFile(){
        StringTemplateGroup templateGroup = new StringTemplateGroup("xml group", "templates");
        StringTemplate xmlTemplate = templateGroup.getInstanceOf("xml");
        xmlTemplate.setAttribute("user", this.user);

import org.antlr.stringtemplate.*;
import org.antlr.stringtemplate.language.*;

StringTemplateGroup group =  new StringTemplateGroup("»our name«", "»path to teplates foled«]]", DefaultTemplateLexer.class);
StringTemplate homepage = group.getInstanceOf("homepage");
helloAgain.setAttribute("title", "Welcome To StringTemplate");
Hello, $name$!
Hello, $$!
Hello, $user.(expression_to_get_property)$
Hello, $users; separator=", "$

$name:bold()$ // Apply template
$users:{s|<li>$s$</li>}; // Anonymous teplate


public class MVELExample extends TemplateExample{

    Map<String,String> map = new HashMap<String,String>();

    public MVELExample(String user) {
        this.user = user;
        map.put("user", user);

    public void print() {
        System.out.println((String)TemplateRuntime.eval("Hello MVEL, I'm @{user}\n", map));

    public void printFromFile() {
        try {
            System.out.println(TemplateRuntime.eval(new FileInputStream(new File("templates/mvel.xml")), map));
        } catch (FileNotFoundException e) {

Spring libraries

defines NormalViewResolver, this uses JSP and JSTL views

View resolver
Declared in WebApplicationContext

  • InternalResourceViewResolver
  • ResourceBundleViewResolver

When using JSTL, we need to use JstlView first

<%@ taglib prefix="form" uri="" %>



<%@taglib prefix="c" uri="" %>

JSP Import

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page pageEncoding="UTF-8"%>
<%@ page session="false" %>
<%@ taglib uri="" prefix="c" %>
<%@ taglib uri="" prefix="fmt" %>
<%@ taglib uri="" prefix="form" %>

Load XML to DOM

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

// Document doc = db.parse(url.toString());
// Document doc = db.parse("path.xml");

Element rootElem = doc.getDocumentElement();
Node: getNodeName(), getNodeValue(), getNodeType(), getParentNode(), getChildNodes(),
Element: .getAttribute(), setAttribute, removeAttribute()
Element: .getElementsByTagName

// NodeList nodeList = rootElem.getChildNodes();
// NodeList nodeList = rootElem.getElementsByTagName("tag");

for (int i = 0; i < nodeList.getLength(); i++) {
Element elem = (Element) nodeList.item(i);
String id = elem.getAttribute("id");
// ...

serializacetoXML(URI output)

public void serializetoXML(URI output) throws IOException, TransformerConfigurationException, TransformerException {
// Vytvorime instanci tovarni tridy
TransformerFactory factory = TransformerFactory.newInstance();
// Pomoci tovarni tridy ziskame instanci tzv. kopirovaciho transformeru
Transformer transformer = factory.newTransformer();
// Vstupem transformace bude dokument v pameti
DOMSource source = new DOMSource(doc);
// Vystupem transformace bude vystupni soubor
StreamResult result = new StreamResult(output.toString());
// Provedeme transformaci
transformer.transform(source, result);


Relational DB.

JDBC - via SQL to any relational db.
Persistentni objekty - existence pretrva beh aplikace.

Ukladat objekty, ne relace:

  • objekty maji vlastni identitu -> neresime primarni klic (jinak generovan umele)
  • pri zmene db nemusime revidovat vsechny SQL

Nejlepsi reseni -> objektova db (eg. Cache)

Nastroje na persistenci objektu pomoci relacni databaze:

  • J2EE a Entity Beans.
  • Hibernate, TopLink - maji vlastni api, zmena neni jednoduse mozna.
  • JDO - standartni rozhrani persistence

By Sun. Umoznuje ruzne implementace (slouzi jako rozhrani objektove db, provadi maping na relace, uklada data do relacni db)
API je nezavisle na implementaci persistence - muzeme jednoduse meni implementace a typ DB.

--- all in javax.jdo ---
PersistenceManagerFacorty - konfig persistence
PersistenceManager - implementace metod pro persistenci
Transaction - sprava transakci
1 PersistenceManager = 1 Transaction (get via currentTransaction())


Posloupnost operaci, probehne bud cela, nebo nic.
-- vsechno v JDO je v transakcich
-> app vzdy v konzistetnim stavu

// Properties properties = new Properties(); // setting db access
PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(properties);
PersistenceManager pm = pm = pmflgetPersistenceManager();
Transation tx - pm.currentTransaction();
    // Write
    Person joe = new Person("Joe", "Doe");

    // or Read
    Extent extent = pm.getExtent(Person.class, false);
    for (Iterator i = extent.iterator(); i.hasNext();) {
        Person somebody = (Person);

} finally {
    if (tx.isActive()) {
        tx.rollback(); // zruseni cele transakce


Meni se v ramci transakce


Vytvoreny objekt za behu app, nebyl ulozen jako persistent
JDO se o nej vubec nestara

  • kazdy novy objekt
  • persistentni pomoci pm.makeTransient(obj); // zruseni vazby
  • persistentni pomoci pm.deletePersistent(obj) // zruseni + smazani z uloziste


Ve sprave JDO.

  • Persistent New (po makePersistent()), zatim neni ulozen, ulozi se po commitu transakce
  • Persistent Clean - ulozen i nacten do objektu v pameti… Odpovidaji si. Tady bude po stavu hollow kdyz ho nacteme.
  • Persistent Dirty - neodpovidaji si. Zmenili jsme ho v pameti. Po commintu transakce se ulozi.
  • Persistent Deleted - je ulozen, bylo provedeno persistentDelete(). Pri commitu bude smazan.
  • Persistent New Deleted - [RARE], makePersistent() -> Persistence New -> deletePersistent() before commit


Data v ulozisti. Nejsou nacteny v pameti. // Ale je nejakym zpusobem nactena informace o tom ze tam jsou.

  • Persisteni objekt se Hollow stane po commitu
  • Kazdy objekt nove nacetny z uoziste… jakmile ho zacteme cist tak je z nej Persistent.

Kazdy objekt ma indentitu nezavislou na obsahu dat. V relacni db je to vestinou nejaky primarni klic.
V JDO ziskava identitu v okamziku, kdy je ucinen persistentnim. (JDO o nem vi).
Schemata pridelovani identity:

  • Datastore identity - sprava id je na JDO <-- implicitni
  • Application identity - sprava id je na aplikaci (=programatorovi). Pouziti jen vyjimecne. (napr chceme aby iden. osoby bylo RC)
    --- mozno kombinovat

Datastore identity

Implementace JDO musi mit tridu objektu, ktere budou slouzit jako ID
ziskame ho pm.getObjectId();

<class name="Osoba" identity-type="datastore">

Application identity

Nase trida musi obsahovat primarni klic (jednoznacna identifikace) - jednoduchy (1 polozka)/slozeny (kombinace vice polozek).
Nelze pouzit String/Long
Musiem definovat atribut primarniho klice (ident) a take jeho tridu (idOsoby)

<class name="Osoba" identity-type="application" objectid-class="IdOsoby">
    <field name="ident" primary-key="true">
    <field name="vek"/>

Pozadavky na tridu identifikatoru

  • nestaticke verejne vlastnosti stejneho jmena a typu, jake jsou polozky primarniho klice
  • equals, hashCode() - zavisi na vsechn vlastnostech primarniho klice
  • implicitni konstruktor
  • musi mit konstruktor s argumentem String (on demand identifikator)
  • toString() - kombatibilni s konstruktorem s arg String
  • trida je public, implements Seriazible
  • vsechny nestaticke vlastnosti tridy musi byt Serializable (recomm. String, Date, Number)
  • vsechny nestaticke vlastnosti jsou public

Access to objects in DB

Access via ID

We already know object id, eg. from pm.getObjectId() or from predchozi knowledge (generujeme si idcka sami, eg rodne cislo)
Person somebody = (Person) pm.getObjectById(id, true); // true - kontroluje se pritomnost v ulozisti

Access via extent

Extent = mnozina vsech instanci dane tridy ulozenych v objekotve databazi a muze zahrnovat i tridy odvozene.

Extent people = pm.getExtent(Person.class, true); // true - i odvozene tridy
Iterator itr = osoby.iterator();
try {
    while(itr.hasNext()) {
        somebody = (Person);
} finally {

Pokud data modifikujeme, musime zacit a ukoncit transakci.

Access data via JDOQL

Query via javax.jdo.Query


Query query = pm.newQUery(Person.class, "age" < 50);
Collection collection = (Collection) query.execute();

Data types

Problem: Java and Relation Db Data types are not compatible, need for mapping

First-Class Object - persistentni object, has own odentity, lze na nej odkazovat… typicky vsechny objekty ulozene v aplikaci.
Second-Class Object - nema vlastni identitu, existuje jako atribut First-class objectu.

Datatypes supported by JDO implementation:

boolean, byte, short, int, long, char, float, double
Boolean, Character, Byte, Short, Integer, Long, Float, Double, String, Locale, BigDecimal, BigInteger
Collection, Set, HashSet
optional [Map, List, ArrayList, HashMap, Hashtable, LinkedList, TreeMap, TreeSet, Vector]

Every class implements PersisetnceCapable (done by extending translated classes)
Every interface


Dve tridy objektu

  1. Vlastnost typu kolekce (=vlastnik kolekce)
  2. Tridy prvky kolekce (v Jave je mozne pouzit pro kolekci obecny typ Object, pro ulozeni ho ale musime presneji specifikovat)
  3. [MAP] tridy prvku pouzite jako klice (pouziti v meteadatech <map key-type="java.lang.String" value-type="Adresa"/>)

Set neobsahuje duplikaty (nikdy p1.equals(p2)), poradi nehraje roli
List muze obsahovat duplikaty, poradi hraje roli

Pokud je atribut peristentni tridy kolekce ≤ Card > collection of tags ≥, stava se trida vlastnikem kolekce a v jejich metadatech je treba zadat tridu prvku

<class name="Card" identity-type="datastore">
    <field name="name">
        <extension vendor-name="jpox" key="length" value="max 100"/>
    <field name="image">
        <extension vendor-name="jpox" key="length" value="max 100"/>
    <field name="tags">
        <collection element-type="Tag" embedded-element="true"/> // element-type has to be also persistent // embedded-element - jsou prvky ulozeny jako FCO (true), nebo jako SCO (false)

Object relations

1:N possibilites
Normal mapping - trida A obsahuje atribut kolekci objektu B (skryte vytvari treti tabulku - JOIN TABLE)
Jednostranne inverzni mapovani - kazdy z objektu tridy B obsahuje atribut A, se kterym je v relaci
Oboustranne inverzni mapovani = kombinace prechchozich


<class name="Person">
    <field name="name" persistence-modifier="persistent">
        <extension vendor-name="jpox" key="length" value="max 50"/>
<class name="Employee" persistence-capable-superclass="Osoba">
    <field name="salary" persistence-modifier="persistent"/>


  1. Import classes used in query
  2. Params declaration - data from outside (from user)
  3. Vars declaration - local variables to handle query
  4. Candidate set - set of object query works with (eg. extent)
    • Class of objects (extent of this and extended classes) query.setClass()
    • precreated extent query.setCandidates(Extent)
    • collection and class of objects query.setCandidates(Collection)
  5. Result set class declaration - one query can return just one type of class
  6. Filter settings - is object part of result or should be ignored?
  7. Order sertings
import java.util.*;
PersistenceManager pm; /* vytvoren drive */
public Collection aktivniAkce()
    /* Vytvoříme dotaz, zadáme třídu objektů a filtr */
    Query q = pm.newQuery(Akce.class,
                          "datefrom <= now && dateto >= now");
    /* Import třídy Date */
    q.declareImports("import java.util.Date");
    /* Deklarujeme parametr 'now' */
    q.declareParameters("Date now");
    /* Zjistíme dnešní datum */
    Date dnes = new Date();
    /* Spustíme dotaz */
    Collection result = (Collection) q.execute(dnes);
    return result;

Storing data at Gogle App Engine

AppEngineDatastore - NoSQL, schemaless, object, query engine, atomic transactions (no interfering between ops, within entity groups). Implementations of JDO and JPA
Google Cloud SQL - relational SQL, based on MySQL
Google Cloud Storage - for big files


Entity - properties (named value): string, integer, reference, …
Identified by key: kind, identifier (string/numeric), [ancestor path]. Can be assigned by us or automatically.
Multiple operations in one transactions. (every op. has to suceed, otherwise rollback)

DataStore vs Relational DB

Query performance depends on Result Set (not Date Set) -> load 10 entities from 100 == load 10 entities from 1 000 000. (but because of that, just some ops are supported)
NO join, aggregate, inequality filtering on multiple props, filtering data based on subquery
Hierarchy (~filesystem). Entity can have parent. - permanent. Entity + its descendats = entity group.
Person:GreatGrandpa / Person:Grandpa / Person:Dad / Person:Me


Get by key
Quert by values
Return: keys, entities, projected entities


Commit phase - entity data is recorded to log
Apply phase - entity data is written & index rows for a entity is written

Google App Engine JDO 2.3

Standard interface for storing objects containing data into a database

  • annotate java objects
  • retrieve objects with queries
  • interacting with a db suing transactions


  • JDO and DataNucleus App Engine JARs in war/WEB-INF/lib/
  • jdoconfig.xml in war/WEB-INF/classes/META-INF // tells JDO to use AppEngine
  • build process must perfomr a post-compilation enhancement - associate with JDO impl

@PersistenceCapable - To declare a Java class as capable of being stored and retrieved from the datastore with JDO
@Persistent - fields of class to be stored
@Persistent(serialized = "true") - stored as BLOB (files)
@NotPersistent - fields of class NOT to be stored
(because some default are used - some data types are persistent by default, some are not)
@PrimaryKey, @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) - keys

import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
public class Employee {
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    private String firstName;
    private String lastName;
    private Date hireDate;
    public Employee(String firstName, String lastName, Date hireDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hireDate = hireDate;
    // Accessors for the fields. JDO doesn't use these, but your application does.
    public Key getKey() {
        return key;
    public String getFirstName() {
        return firstName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    public String getLastName() {
        return lastName;
    public void setLastName(String lastName) {
        this.lastName = lastName;
    public Date getHireDate() {
        return hireDate;
    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;

Helps create dynamic webpages based on standart markup languages (HTML, XML, …) – any type of data through OutputStream
1999, Sun Microsystems
Require web server with servlet container (Apache Tomcat, Jetty)
Similar to PHP or ASP.NET Web Forms
Alternative Apache Velocity

High-level abstraction of Java servlets.
JSP translated to executable servlets at runtime, by compiler (embedded in server).
Cached until modified.
Can be used:
• independently
• as view in MVC ( usually M = JavaBeans, V = JSP, C = Java Servlets/framework (Struts, Spring) )

Mix of Java and other languages


evaluated inside java servlet class, without semicolon

inner variables, classes, methods definitions

same as expression, but puts all in _jspService() method

to control how the Web container translates and executes the JSP page.
include – directly pasted
taglib – tag library is used, params: prefix and URI" prefix="c" %>
• import – translate into import in servlet
• contentType – optional, if HTML is not used -> text/html
• errorPage -> false (if true object (of type javax.servlet.jsp.JspException) is available // We can define error page to whole WAR
• isErrorPage
• isThreadSafe
• autoFlush – buffer flushed when full (false -> throw exception)
• session
• buffer – buffer size
• language – only possible is Java right now
• extends – DO NOT USE
• info – text for getServletInfo()
• pageEncoding = default ISO-8859-1, change to UTF-8

Implicit objects
out – [JspWriter]
page – servlet itself
pageContext – [PageContext] … usually one HTML page passes multiple JSP
request – [HttpServletRequest]
response – [HttpServletResponse]
session – [HttpSession]
application – shared data for all servlets
exception – exceptions not caught by app code

jsp:include – subroutine, temporalily hands control to other JSP, then return to self

jsp:forward – some as include, but control will NOT be returned back

jsp:param – used in jsp:include, jsp:forward, jsp:params
jsp:getProperty – property of JavaBean

"myerror.jsp" %>
="" %>

=1; %>

Counting to three:

This number is .

Expression Language
Added in ver. 2.0 (in 2.1 Unified Expression Language, same as in JSF)
Access data and functions in Java objects

Additional tags
Tag libraires, create your own using JSP Tag Extension API
Standart is JSTL (interations, condititons) and Struts Tag LIbrary

JSP 2.0

Displaying parameter values
Hello, ${param.visitor}
Same as: Hello, request.getParameter("visitor")%>

Nested beans

deferred expressions - evaluated az when needed

Compiler-JVM set (called an SDK or JDK)

the lone JVM (called a JRE, Java Runtime Environment)

JSP Life Cycle

Request to JSP Page

Handled by special servlet – checks if JSP was modified since last time


Object data mode <-> Relational Data Model

Entita (clovek, faktura, objednavka, …)
Trida, ktera nam reprezentuje domenovy objekt
(- odpovida jednomu radku v db)

Data Transfer Object
Zapozdreni dat a jejich prenos
Pokud potrebujeme neco nekam poslat
Velice podobna jako entita, klidne uplne stejna

  • entita je vzdycky stejne

Plain Old Java Object
Tridy na ktere nejsou kladeny zadne slozite pozadavky - zadne rozhrani, zadne extendy, zadne konvence
pouze napr muze mit pozadavky na nejake get/set, bezparam konstruktor, …

Customer (name, address, notes)
Contracts (customer_id, description, …)
U vypisu Customeru nas muzou zajimat jen info o Custoemrech a souhrne infomrace o Contractech (ale ne cele entity)
Vytvorim si CustomerDAO - ktere nektere atributy mit nebude a bude mit nejake navic z Contractu

Pouziva se vice pristupu

  1. Entity EJB
    Entita je objekt, ktery se nachazi v EJB kontejneru a pristup se resil (vzdalene)

  2. JDO
    Java Data Object
    Univerzalni standart pro persistenci, neni omezen na relacni databazi
    Obecnejsi nez JPA
    Ale odstinuje nas od db jeste vic nez ty ostatni

  3. JPA
    Vyuziva koncet POJO Entit
    Inspirovane nastorem Hibernate
    Je ot pouze API, muze byt implementovano ruznymi ORM nastroji TopLink, OpenJPA, Hibernate, …
    Je hodne obecne, muze se menit implementace… Nastroje pak maji nejake veci navic, ale jen extra featury
    JPA je standard

Entity reprezentuji jednotlive domenove objekty (klasicke POJO objekty - attrs, musi mit bezparam constructor, doporucuje se aby byla serializovatelna)

Definice mapovani

  1. Anotace
    Prehlednejsi, je to na jednom miste
    Anotace ma Java od v 5

  2. XML

  1. JavaDoc
    Predtim nez mela Java anotace

XML ma vetsi prioritu nez anotace
Convention over configuration (nemusime nikde rikat do ktere tabulky se bude ukladat, jak se buodu sloupecky jmenovat, …)

Konfigurace v persistence.xml, muze obsahovat vice persistence unit

Persistence unit
Seznam trid, ktere Persistence Unit spravuje
Konfigurace pripojeni (JDNI DataSource, JDBC url, name, pass)
Zpusob rizeni transakci

Konfiguracni parametry
<?xml version="1.0" encoding="UTF-8"?>


CRUD operace s entitami, nejdulezitejnsi entita z JPA
Instanci ziskame pomoc EntityManagerFactory (bud primo pres new nebo od containeru pres DI)
Relativne levna operace, ale ne thread-safe.

Nacita conf z persistence.xml
Ziskame pomoci Persistence.createEntityManagerFactory(--- retezec s nazvem Persistence Unit ---) nebo pomoc DI
Je relativne draha (nacita conf), je thread-safe
Init ORM nastroje

KOnfigurace v persistence.xml, sklada se z persistence unit (vetsinou jedna, ale napr. dalsi pri testovani, pri vice db,
Kazda entita je asociovana s jednou persistence unit.

Persistence Context se stara instance entity
Persistence Unit se stara o tridy entit
--> pro jednu unit muzeme mit vic contextu, dochazi k tomu pri soubeznych transakcich.
V tabulce mam jednoho Petra, v pameti muzu mit vic instanci Petru ( v jinych kontextech ) -> davat na to pozor

Transakce je spravovana PersistenceContextem, maximalne jedna. Zmeny jsou ulozeny pri commitu.

Na zacatku neexisutje
Vytvorime ppomoci konstruktoru
Obycejna instance v pameti, ORM o ni nevi
em.persist(e) - dostane se do managovaneho stavu, je asoc. s persistence contextem, zmeny jsou automaticky ukladany do db pri provedeni commitu transakce commitu.

Vazby mezi entitami
V ORM ma cenu se bavit o vazbach mezi entitami, v SQL to nejde
Vazba jedostrana, oboustrana (ze zaazniku se dostanu na objednavky, z objednavek na zakazniky)
(Lazy fetching - mame zakaznika, chceme vytahnout jeho enitity, vytahnou se i vsechny jeho objednavky… pres lazy fetching muzeme nastavit ze objednavky se nastavi az je budeme potrebovat ––– funguje jen po dobu trvani transakce)
Vazby nam vytvari zavislost - muzeem se do nich zamotat
(Produkty obsahuji zavislost na kategoriich, kategorie obsahuji vazby na prodkty)
( -> reseni je lazy fetching - nejde obcas pouzit)
( -> reseni je jednosmerna vazba)

Selecty (narozdil od SQL, mame vztahy mezi netitama, nemusime provadet JOIN)
umi ruzne vystupy (entity, atributy, seznam atribitu)

Napr pri dotazovani na db pri vyplnenni formulare od uzivatele

javax.persistence.Query --- createQuery
muzeme si dotazy pripojit rovnou k entitam, potom createNamedQuery
muzou byt parametrizovany (parametry jsou pojmenovane, ne cislovane jako JDBC)

EJB je bitevni tank
Spring je odlehcena varianta, je velmi oblibena, not invasive. Relative simple, do not create other dependencies.
Spring is not formal standard. Big Companies could be afraid.

  • deklarativni rizeni transakci
  • autorizace (via annotations)
  • distribuovane transakce
  • resime ceho chceme dosahnout

Spring JDBC
Apache Commons DB
--- implementace TemplateMethod Patternu
zjednodusuje kod, ale porad nas nechrani v typove kontrole a chybach v SQL


DB ------------- Data Access ----------- Service --------------------------- View
sql, jdbc objects data transfer object

Tomcat a Jetty jsou webovy server kontejnery
Jsou pouzity v glassfishu


INSERT INTO people (id, name) VALUES (1, "Pepa");
Person p = new Person(1, "Pepa"); em.persist(p); em.getTransaction().commit();
UPDATE people SET name = "Honza" WHERE id = 2;
Person p = em.find(Person.class,2); p.setName("Honza"); em.getTransaction().commit();


Usnadneni vyvoje enterprise applikaci.

  • DI
  • transakcni zpracovani, remoting business
  • centralizovany config
  • usnadneni unit testu

= alternativa k EJB
EJB je zastarale (nebo alespon vychazi ze zastaralych korenu)
EJB je prilis komplexni - 1 komponenta = 4 tridy (component interface, business interface, implenetation, deployment descriptor)
EJB je invazivni -> problemy s unit testy.
EJB pouziva proprietalni technologie.

Dalsi sluzby nad ramec EJB od Springu

  • MVC + intergrace jinych technologii (JSP+JSTL+Tiles, Velocity, FreeMarker, XSLT, JasperReports)
  • integrace jinych MVC (Struts, Tapestry, JSD, WebWork)
  • AOP Aspect Oriented Programing


Spring provide abstract class for JUnit tests.

Inversion of Control - odpovednost za vytvareni, init a provazadni objektu ven z kodu (do IoC kontejneru)
Dependency Injection je specialni pripad Inversion of Control.

  • Setter injection
  • Construction injection
  • Interface injection

Can be used also as only a libary inside other frameworks (Struts/WebWork) - start Spring via ContextLoaderListener and access it via ServletContext attr

Spring Framework


  • Source-level metadata
  • AOP infrastructure


  • Hibernate
  • JDO
    org.springframework.web - Spring Web MVC

Spring Web MVC

Designed around DispatcherServlet.

  • dispatches requests to handlers
    • hanlder mapping (via annotations @Controller, @RequestMapping)
    • view resoulution (customizable - url, request type, params, Accept header, ...)
    • locale and theme resolution
    • uploading files


Front Controller design pattern
Central Servlet (inherits from HttpServlet, declared in web.xml)
Has associated parent WebApplicationContext (bound in ServletContext, access via RequestContextUtils) (extension of ApplicationContext) - inherits all beans from it. Integrated with the Spring IoC container (all features of Spring are accessible for us)

  • Dispatches requests to controllers
  • offers other functionality
    For both uses Special beans (can be set, or we can use default - set in

Special bean types

  • HandlerMapping - maps request to handlers, pre and post-processors. eg. via annotations in controllers.
  • HandlerAdapter - for invoking handlers, to shield DispatcherServlet from impl detail (previosly mapped by HandlerMappig)
  • HandlerExceptionResolver - maps exceptions to views
  • ViewResolver - string based view names -> actual View types. (default InternalResourceViewResolver)
  • LocaleResolver
  • ThemeResolver
  • MultipartResolver - processing uploads
  • FlashMapManager - pass attrs between request, eg for flash messages


  1. Locale resolving
  2. Theme resolving
  3. Multipart resolving, if true -> wrapped in a MultipartHttpServletRequest
  4. Handler searching and executing
  5. If model returned -> render view

Looks for [servlet-name]-servlet.xml in WEB_INF directory, eg. /WEB-INF/golfing-servlet.xml
Create beans from it


        <!-- customize DispatcherServlet instances via init-param elems -->
        <init-param name="contextClass" value="" /> // default: XmlWebApplicationContext
        <init-param name="contextConfigLocation" value="" />
        <init-param name="namespace" value="" /> // default: [servlet-name]-servlet.


@Controller - used to handler mapping
@RequestMapping - used to handler mapping, to class or class's method

  • value: strings, {pathVariables}, {symbolicName:[a-z-]+}
  • method: RequestMethod.POST, RequestMethod.GET
  • consumes (Content-Type header): application/json (also negations)
  • produces (Accept request header): application/json
  • params: presence "param", absence "!param", value "param=value"
    @PathVariable - useful for REST

Prior to Spring 3.1
Controlled was selected by DefaultAnnotationHandlerMapping
Actual method was narrowed by AnnotationMethodHandlerAdapter

Since Spring 3.1
Controller and method is selected by RequestMappingHandlerMapping (coop with RequestMappingHandlerAdapter)
Not working anymore:

  • select a controller first with SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping and then select method by @RequestMapping
  • rely on method names as a fall-back with disambiguate methods (with same @RequestMapping)
  • have single "default" method in controller without @RequestMapping, when no other mapping was matches (now 404)