SlideShare une entreprise Scribd logo
1  sur  29
Parancoe usare i DAO senza implementarli a cura di Lucio Benfante Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License Roma 2007
What is Parancoe? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Convention over Configuration DRY (Don't repeat yourself) Don't re-invent the wheel Guidelines
Fun for the developer Main Guideline
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Starting a new application
...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 ?
NOIA!
Hibernate <class name=&quot;events.Person&quot; table=&quot;PERSON&quot;> <id name=&quot;id&quot; column=&quot;PERSON_ID&quot;> <generator class=&quot;native&quot;/> </id> <property name=&quot;age&quot;/> <property name=&quot;firstname&quot;/> <property name=&quot;lastname&quot;/> <set name=&quot;events&quot; table=&quot;PERSON_EVENT&quot;> <key column=&quot;PERSON_ID&quot;/> <many-to-many column=&quot;EVENT_ID&quot; class=&quot;events.Event&quot;/> </set> </class> ,[object Object],[object Object]
NOIA!
Hibernate (JPA) ,[object Object],[object Object],[object Object]
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? ,[object Object],<hibernate-configuration>  <session-factory> <mapping class=&quot;it.jugpadova.demoapp.po.Person&quot;/>  </session-factory> </hibernate-configuration> ,[object Object]
NOIA!
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 ,[object Object],[object Object]
The classic DAO ,[object Object],[object Object],[object Object]
NOIA!
Do we need the factory? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Common implementation public List<Person>  findByLastName (String lastName) { Session session = sessionFactory.openSession(); Transaction tx = null; List<Person> result = null; try { tx = session.beginTransaction(); Query q = session.createQuery( &quot;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? ,[object Object],[object Object],[object Object]
Parancoe DAO @Dao(entity=Person.class) public  interface  PersonDao extends GenericDao<Person, Long>  { List<Person> findByLastName(String lastName); } Auto-discovered Automatically available  in the Spring context people = dao().getPersonDao().findByLastName(“Benfante”);
Some finder examples ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Complex queries @Dao(entity=Person.class) public interface PersonDao extends GenericDao<Person, Long> { ... List<Person> searchByPartialUncasedLastName( String partialLastName); ... } @Entity() @NamedQueries({ @NamedQuery( name=&quot;Person.searchByPartialUncasedLastName&quot; , query=&quot;from Person p”+ ”  where lower(p.lastName) like lower(?)”+ ”  order by p.lastName&quot;) })  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<T> findAll(); List<T> searchByCriteria(Criterion... criterion); List<T> searchByCriteria(DetachedCriteria criteria); List<T> searchByCriteria(   DetachedCriteria criteria,   int firstResult, int maxResults); int deleteAll(); long count();
Informazioni sul JUG Padova ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Contenu connexe

Tendances

Tendances (20)

The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Going reactive in java
Going reactive in javaGoing reactive in java
Going reactive in java
 
What I Love About Ruby
What I Love About RubyWhat I Love About Ruby
What I Love About Ruby
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More Approachable
 
Object Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHPObject Oriented Design Patterns for PHP
Object Oriented Design Patterns for PHP
 
php string-part 2
php string-part 2php string-part 2
php string-part 2
 
Regex-Fu - Juliette Reinders Folmer - Codemotion Rome 2017
Regex-Fu -  Juliette Reinders Folmer - Codemotion Rome 2017Regex-Fu -  Juliette Reinders Folmer - Codemotion Rome 2017
Regex-Fu - Juliette Reinders Folmer - Codemotion Rome 2017
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
 
Textual Modeling Framework Xtext
Textual Modeling Framework XtextTextual Modeling Framework Xtext
Textual Modeling Framework Xtext
 
Design attern in php
Design attern in phpDesign attern in php
Design attern in php
 
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua LawrenceEmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
 
Round PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing FunctionallyRound PEG, Round Hole - Parsing Functionally
Round PEG, Round Hole - Parsing Functionally
 
Static Analysis and AST Transformations
Static Analysis and AST TransformationsStatic Analysis and AST Transformations
Static Analysis and AST Transformations
 
Session Server - Maintaing State between several Servers
Session Server - Maintaing State between several ServersSession Server - Maintaing State between several Servers
Session Server - Maintaing State between several Servers
 
Static Analysis in IDEA
Static Analysis in IDEAStatic Analysis in IDEA
Static Analysis in IDEA
 
Erlang/OTP for Rubyists
Erlang/OTP for RubyistsErlang/OTP for Rubyists
Erlang/OTP for Rubyists
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Using spl tools in your code
Using spl tools in your codeUsing spl tools in your code
Using spl tools in your code
 
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching PatternDeadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 

En vedette

En vedette (7)

Apigee Console & eZ Publish REST
Apigee Console & eZ Publish RESTApigee Console & eZ Publish REST
Apigee Console & eZ Publish REST
 
Java e i database: da JDBC a JPA
Java e i database: da JDBC a JPAJava e i database: da JDBC a JPA
Java e i database: da JDBC a JPA
 
Java Persistence 2.0
Java Persistence 2.0Java Persistence 2.0
Java Persistence 2.0
 
WP REST API
WP REST APIWP REST API
WP REST API
 
Applicazione JavaFX – CORSA DI AUTO SU TRACCIATI REALI
Applicazione JavaFX – CORSA DI AUTO SU TRACCIATI REALIApplicazione JavaFX – CORSA DI AUTO SU TRACCIATI REALI
Applicazione JavaFX – CORSA DI AUTO SU TRACCIATI REALI
 
Rest Console
Rest ConsoleRest Console
Rest Console
 
API Design - 3rd Edition
API Design - 3rd EditionAPI Design - 3rd Edition
API Design - 3rd Edition
 

Similaire à Using DAOs without implementing them

Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
Jevgeni Kabanov
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 

Similaire à Using DAOs without implementing them (20)

Apache Persistence Layers
Apache Persistence LayersApache Persistence Layers
Apache Persistence Layers
 
Parancoe and Lambico
Parancoe and LambicoParancoe and Lambico
Parancoe and Lambico
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Os Leonard
Os LeonardOs Leonard
Os Leonard
 
Struts2
Struts2Struts2
Struts2
 
The Basics Of Page Creation
The Basics Of Page CreationThe Basics Of Page Creation
The Basics Of Page Creation
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
JavaScript Needn't Hurt!
JavaScript Needn't Hurt!JavaScript Needn't Hurt!
JavaScript Needn't Hurt!
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
 
I Feel Pretty
I Feel PrettyI Feel Pretty
I Feel Pretty
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Jsp And Jdbc
Jsp And JdbcJsp And Jdbc
Jsp And Jdbc
 
Jsp
JspJsp
Jsp
 
Php
PhpPhp
Php
 
Cena-DTA PHP Conference 2011 Slides
Cena-DTA PHP Conference 2011 SlidesCena-DTA PHP Conference 2011 Slides
Cena-DTA PHP Conference 2011 Slides
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Using DAOs without implementing them

  • 1. Parancoe usare i DAO senza implementarli a cura di Lucio Benfante Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License Roma 2007
  • 2.
  • 3. Convention over Configuration DRY (Don't repeat yourself) Don't re-invent the wheel Guidelines
  • 4. Fun for the developer Main Guideline
  • 5.
  • 6. ...easier with a good IDE
  • 8. What I'm able to use? (JUNIOR Programmer)
  • 9. What I like to use? (SENIOR Developer)
  • 10. What for the persistent layer? Class.forName( &quot;com.mioDbms.mioDriver&quot; ); Connection con=null; try { con = DriverManager.getConnection ( “ jdbc:...”, “user”, “pass”); ResultSet rs; PreparedStatement ps = conn.prepareStatement( &quot; SELECT * FROM Person WHERE name=? ”); ps. setString (1, &quot;Lucio Benfante&quot;); 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 ?
  • 11. NOIA!
  • 12.
  • 13. NOIA!
  • 14.
  • 15. 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() { ... } }
  • 16.
  • 17. NOIA!
  • 18. 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!
  • 19.
  • 20.
  • 21. NOIA!
  • 22.
  • 23. Common implementation public List<Person> findByLastName (String lastName) { Session session = sessionFactory.openSession(); Transaction tx = null; List<Person> result = null; try { tx = session.beginTransaction(); Query q = session.createQuery( &quot;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; }
  • 24.
  • 25. Parancoe DAO @Dao(entity=Person.class) public interface PersonDao extends GenericDao<Person, Long> { List<Person> findByLastName(String lastName); } Auto-discovered Automatically available in the Spring context people = dao().getPersonDao().findByLastName(“Benfante”);
  • 26.
  • 27. Complex queries @Dao(entity=Person.class) public interface PersonDao extends GenericDao<Person, Long> { ... List<Person> searchByPartialUncasedLastName( String partialLastName); ... } @Entity() @NamedQueries({ @NamedQuery( name=&quot;Person.searchByPartialUncasedLastName&quot; , query=&quot;from Person p”+ ” where lower(p.lastName) like lower(?)”+ ” order by p.lastName&quot;) }) public class Person extends EntityBase { ... }
  • 28. 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<T> findAll(); List<T> searchByCriteria(Criterion... criterion); List<T> searchByCriteria(DetachedCriteria criteria); List<T> searchByCriteria( DetachedCriteria criteria, int firstResult, int maxResults); int deleteAll(); long count();
  • 29.