SeaJUG May 2012 mybatis


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

SeaJUG May 2012 mybatis

  1. 1. RETHINKINGPERSISTENCEJPA/Hibernate & myBatis Compared
  2. 2. 5/17/2012 2About Will• Will Iverson • CTO, Dynacron Group• Personal Background • Professional software dev/architect/consulting since 1995 • Roles: Apple, Symantec, SolutionsIQ • Clients: Sun, BEA, Canal+, T- Mobile, at&t, Microsoft, State of WA • ORM Patent Case • 4 books, many articles
  3. 3. 5/17/2012 3About Dynacron Group• Established mid-2010• Technology Consulting (Java, .NET, BI)• ~25 consultants (& growing, see site for info)• Key differentiation: Continuous Delivery • People • Deep roots in Seattle region • TPM/ScrumMaster, Sr Dev, Sr SDET, DevOps • Process • Blend of Agile (Scrum/Kanban/XP), heavy use of TDD, automation • Tools • Leverage cloud in client friendly-way (e.g. start with testing) • Manage source & binaries (CI, automated release)
  4. 4. Problem• Need to save data • Preferably ACID! • No need to reinvent wheel• Hand-crafted JDBC is annoying & error-prone • Code generation is… sort of ok… • But runtimes are better• Relational databases are pretty darn popular • Tools, extensive knowledge • Not going away any time soon
  5. 5. Possible Solutions• JPA • Really, Hibernate• myBatis• Spring JDBC • Hybrid of myBatis approach + native JDBC…• All others = essentially no adoption • Measured by # of downloads, search volume, job postings, etc…• What about NoSQL…? • Cassandra, MongoDB, CouchDB… • • MySQL makes an ok NoSQL (see SauceLabs post)
  6. 6. Really Different Approaches• ORM (JPA/Hibernate) • Generates SQL from object graph • Proxy objects • DOA if you can’t talk to the DB directly • Most popular choice (Hibernate)• Mapping (MyBatis) • Make it easy to write and map result sets to Java• All other (relational) frameworks are essentially noise in terms of market adoptions • As measured by # of downloads, search volume, job postings, etc…
  7. 7. Hibernate Heart of the Proxy DataApplication difference w/myBatisHibernateData Proxy Session Hibernate Session(1st Level Cache) (1st Level Cache) Data Hibernate • LazyInitializationException 2nd Level Cache • SessionException • StaleSessionException • TransientObjectException • PersistentObjectExceptionData RDBMS
  8. 8. Comparisons• Hibernate • Manual is 391 pages (and you will need a book) • Many dependencies • Based on JPA • Study the code for years and still be learning• MyBatis • Manual is 73 pages (in a bigger font) • One tiny library • No standard • Code review in a day
  9. 9. ORM Cool/Scary ExampleList result = session.createQuery( "from Event" ).list();for (Event event : (List<Event>) result ) { println(event.getDate() + “:" + event.getLocation() );}Question: How much data, in how many queries, will this snippetof code result in?A: Impossible to tell from this snippet. Depends on many factors. Mappingconfiguration for Event, Location objects and associations, as well as the cacheconfiguration. Fixing one code execution path, for example, eager fetchingLocation, will cause potential problems elsewhere. So, this could result inN*N, (N+1), 1, or even 0 requests.
  10. 10. JPA• Graphs of objects in memory• Linked to corresponding data structures in RDBMS• Non-trivial examples require careful understanding of entire structure• Promise: Learn JPA, never worry about SQL• Reality: Must have a VERY solid understanding of SQL, Java, and JPA • In particular, the query and criteria APIs • Need to understand sessions and object scope as relates to sessions
  11. 11. Hibernate Session Complexity• What happens if object Open Session accessed outside of session? Create Transaction• Outside transaction? Flush• Cache status? SQL Statement Transaction Session• Objects have LOTS of SQL Statement hidden state associated SQL Statement • Proxy-based access Flush• Really, really complex if SQL Statement SQL Statement those objects are intended for presentation Commit Transaction • Web services • User interfaces Close Session• Very complex serialization scenarios
  13. 13. Personal Interest• Finished project that ran from 2008-2010 • Numerous challenges (blend of team + Hibernate)• Starting new project in 2010 • Just needed to wrap a few sprocs • Hibernate seemed like overkill• Really liked the annotation-only approach • iBatis based on XML… XML is fine for config, but dev? Bleah.
  14. 14. Brief History• Started as part of a JPetStore demo in 2002• iBatis 2.0 named & released in 2004 • Donated to ASF• Moved from ASF, renamed myBatis 3.0 in 2010 • Released via Google Code • Complete redesign (based on TDD, simplicity, etc.)
  15. 15. MyBatis Approach• Write queries in SQL • Map result sets to data objects via annotations • Get objects back • (Optional) use generator • (Optional) cache result sets•…• That’s basically it.
  16. 16. Basic Design Application Mapper SessionInterfaces RDBMS
  17. 17. Key Concepts• Configuration• Mappers• Code
  18. 18. Configuration (Conceptual)• Session Factory • Static, thread-safe factory • Attach mappers at bootstrap • With annotations, mappers are just interfaces with annotations • With Spring, easy drop mapper interface into context
  19. 19. Mappers• XML or Annotations• Annotations = simple interfaces w/annotations (no implementation!)public interface UserMapper { @Insert({ "insert into user (nickname, email) values (#{nickname}, #{email})" }) @Options(useGeneratedKeys = true, keyProperty = "id") int insert(User user); @Select("select count(*) from user") long count(); @Delete({ "delete from user where id = #{id}" }) void deleteById(User user);}
  20. 20. Usage• Simply ask the session for mapper instance• Call method & get data• Begin transaction, commit, and rollback handled once via standard utility wrapper • (e.g. Spring or custom) user = session.getMapper(UserMapper.class); return user.count();
  21. 21. Available Annotations• Cache (support for wide variety)• Mappings (result set -> Java object[s])• Identifier mapping• Static statements• Dynamic statements• Parameters
  22. 22. Other Features• Generator (demo)• Migrations (discuss if time) • Maven plugin• Integrations • Spring, Guice, Scala • OSCache, EhCache, Hazelcast
  23. 23. Things You Don’t Do With MyBatis• Don’t Do • Object proxies • Complex object lifecycles• Could Do (But Don’t) • Build highly complex mapping graphs
  24. 24. ComparisonTopic JPA/Hibernate myBatisDeveloper Java, SQL, HQL, Criteria Java, SQLproductivityCaching strategies Two level cache One level cacheDebugging Complex Simple (except for more complex mappings, which are localized)Transaction One transaction per session Ironically, easier to use withmanagement w/open-session-in-view only Spring TX. sane route: Spring TX = insanitySchema management Built-in validation. Upgrade Real migrations (but requires but not real migrations hand-rolling)Session Management Open-session-in-view only Open-session-in-view, or not sane route (simplified object lifecycle)
  25. 25. Thoughts: Hibernate/JPA vs. MyBatis• MyBatis is much, much simplier • People don’t use most of Hibernate• Hibernate/JPA require learning HQL • Don’t understand complex • Criteria queries are better for simple mappings things • Miss a lot of the benefit • In practice, this means you have • Sessions & Object attachment in three data APIs, SQL, Criteria & HQL Hibernate/JPA is very complex • HQL only for hard stuff • Two different cache levels, objects • Find it much faster to just knock out may or may not be attached to query in SQL, pop in annotation and session – at runtime often feels non- call it good deterministic • Most missed from Hibernate • Bootstrap validation of expected schema
  26. 26. MyBatis Negatives?• Over apx 1 year project, asked several people on team for thoughts • Only cited issue was compatibility with legacy stored procedure • Team was unable to diagnose why sproc wouldn’t load into mapping • Worked around by updating sproc • Everyone agreed MyBatis was much simpler & easier to use • Really liked the Spring integration • 1 person cited Spring JDBC as pretty darn easy too
  27. 27. Job Trends
  28. 28. Job Trends (Detail on Smaller)
  29. 29. DEMOCode for demo up on GitHub