Using DAOs without implementing them

download Using DAOs without implementing them

If you can't read please download the document

Transcript of Using DAOs without implementing them

Parancoe: usare i DAO senza implementarli

Parancoe
usare i DAO senza implementarli

a cura di Lucio Benfante

Roma 2007

Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License

What is Parancoe?

A framework (YAFF?)

Yet Another Fucking Framework

A framework aggregation

A tool for developers

Hibernate/JPA + Spring 2 + Spring MVC

Maven 2

+ ...

(write what you are using)

Convention over Configuration

DRY (Don't repeat yourself)

Don't re-invent the wheel

Guidelines

Funforthedeveloper

Main Guideline

mvn archetype:create \

-DarchetypeGroupId=org.parancoe \

-DarchetypeArtifactId=parancoe-webarchetype \

-DarchetypeVersion=0.3.2 \

-DgroupId=it.jugpadova \

-DartifactId=demoapp \

-DpackageName=it.jugpadova.demoapp

...at work in seconds!

Starting a new application

Utilizziamo netbeans perch ci piace risulta comodo per demo, non vincolante per l'uso di parancoe

...easier with a good IDE

The new application

What I'm able to use? (JUNIOR Programmer)

What I like to use? (SENIOR Developer)

What for the persistent layer?

Class.forName( "com.mioDbms.mioDriver" );Connection con=null; try { con = DriverManager.getConnection ( jdbc:..., user, pass); ResultSet rs; PreparedStatement ps = conn.prepareStatement( "SELECT * FROM Person WHERE name=?); ps.setString(1, "Lucio Benfante"); rs = ps.executeQuery(); while ( rs.next() ) { rs.getString...ecc..ecc.... } rs.close(); ps.close(); stmt.close(); } catch(Exception e){ ... } finally { try { con.close(); } catch( Exception ignoreMe ) {} }

JDBC ?

Lancio di netbeans visualizzazione della applicazione di esempioit's all freetitleheaderfootermenu i18n

NOIA!

Now we specialize for the class event starting from the example person

oppure scriverla da zero

fino ad adesso abbiamo scritto 2 classi, un file di configurazione e una interfaccia

there is no dumb question

Hibernate

Hibernate?

Mapping in XML?

Addesso vogliamo gestire eventi e registrazioni

Scrivere la classi persistenti per eventi e registrazione

NOIA!

Now we specialize for the class event starting from the example person

oppure scriverla da zero

fino ad adesso abbiamo scritto 2 classi, un file di configurazione e una interfaccia

there is no dumb question

Hibernate (JPA)

Hibernate (JPA)

Mapping with

annotations!

2 concetti 1)le classi persistenti sono annotate da entity e 2)Queste classi estendono una classe EntityBase che fornisce automaticamente id e version per il locking

e una funzionalita facilmente resa disponibile e non un vincolo

partiamo dalla classe pi semplicepatecipantimport, setter e getter con ide

A simple persistent class

@Entity()public class Person {

private Long id; private String firstName; private String lastName; private Integer version; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { ... } public void setId(Long id) { ... } public String getFirstName() { ... } public void setFirstName(String firstName) { ... } public String getLastName() { ... } public void setLastName(String lastName) { ... } @version public Integer getVersion() { ... } public void setVersion() { ... }}

@Entity()public class Person {

private Long id; private String firstName; private String lastName; private Integer version; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { ... } public void setId(Long id) { ... } public String getFirstName() { ... } public void setFirstName(String firstName) { ... } public String getLastName() { ... } public void setLastName(String lastName) { ... } @version public Integer getVersion() { ... } public void setVersion() { ... }}

What I don't like?

Declaration
of persistent classes

Required fields

Paracoe is extreme able to autodiscover the persistent classes so there is NO xml for the persistence mapping and persistent class registration only annotations on classes

usually with with hibernate you have to register your persitent classes or mapping ...parancoe is able to autodiscover

NOIA!

Now we specialize for the class event starting from the example person

oppure scriverla da zero

fino ad adesso abbiamo scritto 2 classi, un file di configurazione e una interfaccia

there is no dumb question

The Parancoe Way

@Entity()public class Person extends EntityBase { private String firstName; private String lastName; public String getFirstName() { ... } public void setFirstName(String firstName) { ... } public String getLastName() { ... } public void setLastName(String lastName) { ... }}

...auto-discovered!

DAO

DAO

(Data Access Object)

Ne facciamo una con una relazione con participants e qualche annotazione in piclasse Eventin piu abbiamo le annotazioni per la date e annotazione per la relazione

eventualmente evidenziare sul canale visivo il concetto di annotazione

The classic DAO

Interface

Implementation(s)

Factory

Lanciare l'applicazione

NOIA!

Now we specialize for the class event starting from the example person

oppure scriverla da zero

fino ad adesso abbiamo scritto 2 classi, un file di configurazione e una interfaccia

there is no dumb question

Do we need the factory?

Interface

Implementation(s)

Factory

Interface

Implementation(s)

Factory

Common implementation

public List findByLastName(String lastName) { Session session = sessionFactory.openSession(); Transaction tx = null; List result = null; try { tx = session.beginTransaction(); Query q = session.createQuery( "from Person p where p.lastName = ?+ order by p.lastName); q.setString(0, lastName); result = q.list(); tx.commit(); } catch (HibernateException he) { if (tx!=null) tx.rollback(); throw he; } finally { try {session.close();} catch(Exception ignore) {} } return result;}

A minimal DAO

Is it possible?

Interface

Implementation(s)

Factory

Parancoe DAO

@Dao(entity=Person.class)public interface PersonDao extends GenericDao {

List findByLastName(String lastName);

}

Auto-discovered

Automatically available
in the Spring context

people = dao().getPersonDao().findByLastName(Benfante);

Some finder examples

List findByFirstNameAndLastNameAndBirthDate(
String firstName, String lastName, Date birthDate);

List findByBirthDateOrderByLastNameAndFirstName(
Date birthDate);

List findByOrderByLastNameAndFirstName();

Person findByFirstNameAndLastName(
String firstName, String lastName);

List findByLastName(
@Compare(CompareType.ILIKE) String lastName);

List findByLastName(String lastName,
@FirstResult int offset, @MaxResults int limit);

Opzioni sul dbriavviare tomcat quando si cambia la configurazione del datasource

le classi persistenti sono state scoperte automaticamente

abbiamo already the dao usable but very basic function, non specialized on the specific class of our application for example the dato returns an object instead of a instance of class event

Complex queries

@Dao(entity=Person.class)public interface PersonDao extends GenericDao { ... List searchByPartialUncasedLastName( String partialLastName); ...}

@Entity()@NamedQueries({ @NamedQuery( name="Person.searchByPartialUncasedLastName", query="from Person p+ where lower(p.lastName) like lower(?)+ order by p.lastName")}) public class Person extends EntityBase { ... }

Methods of the base DAO

PK create(T newInstance);void createOrUpdate(T o);T read(PK id);void update(T transientObject);void delete(T persistentObject);List findAll();List searchByCriteria(Criterion... criterion);List searchByCriteria(DetachedCriteria criteria);List searchByCriteria(
DetachedCriteria criteria,
int firstResult, int maxResults);int deleteAll();long count();

Informazioni sul JUG Padova

Sito Web

www.jugpadova.it

Mailing List

!Attenzione nuova mailing list su googlegroups

http://groups.google.com/group/jugpadova

Sito Parancoe

www.parancoe.org

Contattami

Lucio Benfante ([email protected])

ML Parancoe ([email protected])

Cliccate per modificare il formato del testo del titolo

Click to edit the outline text format

Second Outline Level

Third Outline Level

Fourth Outline Level

Fifth Outline Level

Sixth Outline Level

Seventh Outline Level

Eighth Outline Level

Ninth Outline Level

javadayRoma 2007