SlideShare ist ein Scribd-Unternehmen logo
1 von 29
RETHINKING
PERSISTENCE
JPA/Hibernate & myBatis Compared
5/17/2012                                   2




About 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
5/17/2012                                                                 3




About 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)
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
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…
  • http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis
  • MySQL makes an ok NoSQL (see SauceLabs post)
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…
Hibernate
                                                                  Heart of the
        Proxy   DataApplication
                                                                   difference
                                                                  w/myBatis

HibernateData
  Proxy    Session                Hibernate Session
(1st Level Cache)                 (1st Level Cache)



 Data
                   Hibernate                   •   LazyInitializationException
                2nd Level Cache                •   SessionException
                                               •   StaleSessionException
                                               •   TransientObjectException
                                               •   PersistentObjectException
Data                 RDBMS
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
ORM Cool/Scary Example
List 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 snippet
of code result in?
A: Impossible to tell from this snippet. Depends on many factors. Mapping
configuration for Event, Location objects and associations, as well as the cache
configuration. Fixing one code execution path, for example, eager fetching
Location, will cause potential problems elsewhere. So, this could result in
N*N, (N+1), 1, or even 0 requests.
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
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
MYBATIS EXAMINED
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.
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.)
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.
Basic Design

             Application




 Mapper
               Session
Interfaces




               RDBMS
Key Concepts
• Configuration
• Mappers
• Code
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
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);
}
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();
Available Annotations
• Cache (support for wide variety)
• Mappings (result set -> Java object[s])
• Identifier mapping
• Static statements
• Dynamic statements
• Parameters
Other Features
• Generator (demo)
• Migrations (discuss if time)
 • Maven plugin
• Integrations
 • Spring, Guice, Scala
 • OSCache, EhCache, Hazelcast
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
Comparison
Topic                JPA/Hibernate                 myBatis
Developer            Java, SQL, HQL, Criteria      Java, SQL
productivity
Caching strategies   Two level cache               One level cache
Debugging            Complex                       Simple (except for more
                                                   complex mappings, which are
                                                   localized)
Transaction          One transaction per session   Ironically, easier to use with
management           w/open-session-in-view only   Spring TX.
                     sane route: Spring TX =
                     insanity
Schema 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)
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
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
Job Trends
Job Trends (Detail on Smaller)
DEMO
Code for demo up on GitHub
https://github.com/dynacron-group/

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to CQRS - command and query responsibility segregation
Introduction to CQRS - command and query responsibility segregationIntroduction to CQRS - command and query responsibility segregation
Introduction to CQRS - command and query responsibility segregationAndrew Siemer
 
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]Malin Weiss
 
Scalable Machine Learning with Hadoop
Scalable Machine Learning with HadoopScalable Machine Learning with Hadoop
Scalable Machine Learning with HadoopGrant Ingersoll
 
Thousands of Threads and Blocking I/O
Thousands of Threads and Blocking I/OThousands of Threads and Blocking I/O
Thousands of Threads and Blocking I/OGeorge Cao
 
Enterprise Virtualization with Xen
Enterprise Virtualization with XenEnterprise Virtualization with Xen
Enterprise Virtualization with XenFrank Martin
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns Alex Theedom
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormOrtus Solutions, Corp
 
Stig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at ScaleStig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at ScaleDATAVERSITY
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
What Drove Wordnik Non-Relational?
What Drove Wordnik Non-Relational?What Drove Wordnik Non-Relational?
What Drove Wordnik Non-Relational?DATAVERSITY
 
The Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceThe Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceAbdelmonaim Remani
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMOrtus Solutions, Corp
 
LinkedIn - A Professional Network built with Java Technologies and Agile Prac...
LinkedIn - A Professional Network built with Java Technologies and Agile Prac...LinkedIn - A Professional Network built with Java Technologies and Agile Prac...
LinkedIn - A Professional Network built with Java Technologies and Agile Prac...LinkedIn
 
What is persistence in java
What is persistence in javaWhat is persistence in java
What is persistence in javaBenjamin Kim
 
My sql 5.6_replwebinar_may12
My sql 5.6_replwebinar_may12My sql 5.6_replwebinar_may12
My sql 5.6_replwebinar_may12Mat Keep
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=HibernateJay Shah
 

Was ist angesagt? (20)

Introduction to CQRS - command and query responsibility segregation
Introduction to CQRS - command and query responsibility segregationIntroduction to CQRS - command and query responsibility segregation
Introduction to CQRS - command and query responsibility segregation
 
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
JavaOne2016 - Microservices: Terabytes in Microseconds [CON4516]
 
Scalable Machine Learning with Hadoop
Scalable Machine Learning with HadoopScalable Machine Learning with Hadoop
Scalable Machine Learning with Hadoop
 
Thousands of Threads and Blocking I/O
Thousands of Threads and Blocking I/OThousands of Threads and Blocking I/O
Thousands of Threads and Blocking I/O
 
Enterprise Virtualization with Xen
Enterprise Virtualization with XenEnterprise Virtualization with Xen
Enterprise Virtualization with Xen
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cborm
 
Stig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at ScaleStig: Social Graphs & Discovery at Scale
Stig: Social Graphs & Discovery at Scale
 
Hpts 2011 flexible_oltp
Hpts 2011 flexible_oltpHpts 2011 flexible_oltp
Hpts 2011 flexible_oltp
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
What Drove Wordnik Non-Relational?
What Drove Wordnik Non-Relational?What Drove Wordnik Non-Relational?
What Drove Wordnik Non-Relational?
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
The Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot PersistenceThe Rise of NoSQL and Polyglot Persistence
The Rise of NoSQL and Polyglot Persistence
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORM
 
J2EE Online Training
J2EE Online TrainingJ2EE Online Training
J2EE Online Training
 
LinkedIn - A Professional Network built with Java Technologies and Agile Prac...
LinkedIn - A Professional Network built with Java Technologies and Agile Prac...LinkedIn - A Professional Network built with Java Technologies and Agile Prac...
LinkedIn - A Professional Network built with Java Technologies and Agile Prac...
 
Hibernate
HibernateHibernate
Hibernate
 
What is persistence in java
What is persistence in javaWhat is persistence in java
What is persistence in java
 
My sql 5.6_replwebinar_may12
My sql 5.6_replwebinar_may12My sql 5.6_replwebinar_may12
My sql 5.6_replwebinar_may12
 
Struts2-Spring=Hibernate
Struts2-Spring=HibernateStruts2-Spring=Hibernate
Struts2-Spring=Hibernate
 

Andere mochten auch

How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...Altoros
 
Secure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScriptSecure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScriptJonathan LeBlanc
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyManageIQ
 
OpenERP 6.1 Framework Changes
OpenERP 6.1 Framework ChangesOpenERP 6.1 Framework Changes
OpenERP 6.1 Framework ChangesOdoo
 
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...Vladimir Bacvanski, PhD
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»e-Legion
 
MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제정완 전
 
RESTful API Automation with JavaScript
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScriptJonathan LeBlanc
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSunghyouk Bae
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
A brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinA brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinLeonardo YongUk Kim
 
Frisby: Rest API Automation Framework
Frisby: Rest API Automation FrameworkFrisby: Rest API Automation Framework
Frisby: Rest API Automation FrameworkQuovantis
 
Web API Test Automation using Frisby & Node.js
Web API Test Automation using Frisby  & Node.jsWeb API Test Automation using Frisby  & Node.js
Web API Test Automation using Frisby & Node.jsChi Lang Le Vu Tran
 
API Management Platform Technical Evaluation Framework
API Management Platform Technical Evaluation FrameworkAPI Management Platform Technical Evaluation Framework
API Management Platform Technical Evaluation FrameworkWSO2
 
How to Design a Successful Test Automation Strategy
How to Design a Successful Test Automation Strategy How to Design a Successful Test Automation Strategy
How to Design a Successful Test Automation Strategy Impetus Technologies
 
Test Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comTest Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comIdexcel Technologies
 
通往測試最高殿堂的旅程 - GTAC 2016
通往測試最高殿堂的旅程 - GTAC 2016通往測試最高殿堂的旅程 - GTAC 2016
通往測試最高殿堂的旅程 - GTAC 2016Chloe Chen
 
Introduction to Test Automation - Technology and Tools
Introduction to Test Automation - Technology and ToolsIntroduction to Test Automation - Technology and Tools
Introduction to Test Automation - Technology and ToolsKMS Technology
 

Andere mochten auch (20)

How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
 
Secure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScriptSecure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScript
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John Hardy
 
OpenERP 6.1 Framework Changes
OpenERP 6.1 Framework ChangesOpenERP 6.1 Framework Changes
OpenERP 6.1 Framework Changes
 
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제
 
RESTful API Automation with JavaScript
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScript
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
MyBatis
MyBatisMyBatis
MyBatis
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
A brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinA brief introduction to Realm with Kotlin
A brief introduction to Realm with Kotlin
 
Frisby: Rest API Automation Framework
Frisby: Rest API Automation FrameworkFrisby: Rest API Automation Framework
Frisby: Rest API Automation Framework
 
Web API Test Automation using Frisby & Node.js
Web API Test Automation using Frisby  & Node.jsWeb API Test Automation using Frisby  & Node.js
Web API Test Automation using Frisby & Node.js
 
API Management Platform Technical Evaluation Framework
API Management Platform Technical Evaluation FrameworkAPI Management Platform Technical Evaluation Framework
API Management Platform Technical Evaluation Framework
 
How to Design a Successful Test Automation Strategy
How to Design a Successful Test Automation Strategy How to Design a Successful Test Automation Strategy
How to Design a Successful Test Automation Strategy
 
Test Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.comTest Automation Framework Design | www.idexcel.com
Test Automation Framework Design | www.idexcel.com
 
通往測試最高殿堂的旅程 - GTAC 2016
通往測試最高殿堂的旅程 - GTAC 2016通往測試最高殿堂的旅程 - GTAC 2016
通往測試最高殿堂的旅程 - GTAC 2016
 
Introduction to Test Automation - Technology and Tools
Introduction to Test Automation - Technology and ToolsIntroduction to Test Automation - Technology and Tools
Introduction to Test Automation - Technology and Tools
 
Concourse and Database
Concourse and DatabaseConcourse and Database
Concourse and Database
 

Ähnlich wie SeaJUG May 2012 mybatis

Fixing twitter
Fixing twitterFixing twitter
Fixing twitterRoger Xia
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...smallerror
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...xlight
 
High-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and JavaHigh-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and Javasunnygleason
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?DATAVERSITY
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...OpenBlend society
 
Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347
Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347
Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347Manik Surtani
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMPT.JUG
 
Chirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterChirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterJohn Adams
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudyJohn Adams
 
Data Modeling for NoSQL
Data Modeling for NoSQLData Modeling for NoSQL
Data Modeling for NoSQLTony Tam
 
Bigdata antipatterns
Bigdata antipatternsBigdata antipatterns
Bigdata antipatternsAnurag S
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects OptimizationWO Community
 
Inside Wordnik's Architecture
Inside Wordnik's ArchitectureInside Wordnik's Architecture
Inside Wordnik's ArchitectureTony Tam
 
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...Thibaud Desodt
 
Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)Don Demcsak
 
Five Years of EC2 Distilled
Five Years of EC2 DistilledFive Years of EC2 Distilled
Five Years of EC2 DistilledGrig Gheorghiu
 

Ähnlich wie SeaJUG May 2012 mybatis (20)

Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 
Fixing_Twitter
Fixing_TwitterFixing_Twitter
Fixing_Twitter
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
High-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and JavaHigh-Performance Storage Services with HailDB and Java
High-Performance Storage Services with HailDB and Java
 
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
A Case Study of NoSQL Adoption: What Drove Wordnik Non-Relational?
 
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
Introducing Hibernate OGM: porting JPA applications to NoSQL, Sanne Grinovero...
 
Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347
Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347
Infinispan, Data Grids, NoSQL, Cloud Storage and JSR 347
 
JavaOne_2010
JavaOne_2010JavaOne_2010
JavaOne_2010
 
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGMUsing JPA applications in the era of NoSQL: Introducing Hibernate OGM
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
 
Chirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterChirp 2010: Scaling Twitter
Chirp 2010: Scaling Twitter
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudy
 
Data Modeling for NoSQL
Data Modeling for NoSQLData Modeling for NoSQL
Data Modeling for NoSQL
 
Bigdata antipatterns
Bigdata antipatternsBigdata antipatterns
Bigdata antipatterns
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects Optimization
 
Inside Wordnik's Architecture
Inside Wordnik's ArchitectureInside Wordnik's Architecture
Inside Wordnik's Architecture
 
RavenDB in the wild
RavenDB in the wildRavenDB in the wild
RavenDB in the wild
 
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...From ddd to DDD : My journey from data-driven development to Domain-Driven De...
From ddd to DDD : My journey from data-driven development to Domain-Driven De...
 
Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)
 
Five Years of EC2 Distilled
Five Years of EC2 DistilledFive Years of EC2 Distilled
Five Years of EC2 Distilled
 

Mehr von Will Iverson

Decisions, Decisions: Native to Mobile Web
Decisions, Decisions: Native to Mobile WebDecisions, Decisions: Native to Mobile Web
Decisions, Decisions: Native to Mobile WebWill Iverson
 
Greenfield Java 2013
Greenfield Java 2013Greenfield Java 2013
Greenfield Java 2013Will Iverson
 
QA Lab in the Cloud
QA Lab in the CloudQA Lab in the Cloud
QA Lab in the CloudWill Iverson
 
Continuous Delivery Overview
Continuous Delivery OverviewContinuous Delivery Overview
Continuous Delivery OverviewWill Iverson
 
Introduction to Kanban
Introduction to KanbanIntroduction to Kanban
Introduction to KanbanWill Iverson
 
Practical maven-slides 2
Practical maven-slides 2Practical maven-slides 2
Practical maven-slides 2Will Iverson
 
Software Internationalization Crash Course
Software Internationalization Crash CourseSoftware Internationalization Crash Course
Software Internationalization Crash CourseWill Iverson
 
Choosing a Java Web Framework
Choosing a Java Web FrameworkChoosing a Java Web Framework
Choosing a Java Web FrameworkWill Iverson
 
Design For Testability
Design For TestabilityDesign For Testability
Design For TestabilityWill Iverson
 
Java Tools and Techniques for Solving Tricky Problem
Java Tools and Techniques for Solving Tricky ProblemJava Tools and Techniques for Solving Tricky Problem
Java Tools and Techniques for Solving Tricky ProblemWill Iverson
 

Mehr von Will Iverson (12)

SeaJUG 5 15-2018
SeaJUG 5 15-2018SeaJUG 5 15-2018
SeaJUG 5 15-2018
 
Java CMS 2015
Java CMS 2015Java CMS 2015
Java CMS 2015
 
Decisions, Decisions: Native to Mobile Web
Decisions, Decisions: Native to Mobile WebDecisions, Decisions: Native to Mobile Web
Decisions, Decisions: Native to Mobile Web
 
Greenfield Java 2013
Greenfield Java 2013Greenfield Java 2013
Greenfield Java 2013
 
QA Lab in the Cloud
QA Lab in the CloudQA Lab in the Cloud
QA Lab in the Cloud
 
Continuous Delivery Overview
Continuous Delivery OverviewContinuous Delivery Overview
Continuous Delivery Overview
 
Introduction to Kanban
Introduction to KanbanIntroduction to Kanban
Introduction to Kanban
 
Practical maven-slides 2
Practical maven-slides 2Practical maven-slides 2
Practical maven-slides 2
 
Software Internationalization Crash Course
Software Internationalization Crash CourseSoftware Internationalization Crash Course
Software Internationalization Crash Course
 
Choosing a Java Web Framework
Choosing a Java Web FrameworkChoosing a Java Web Framework
Choosing a Java Web Framework
 
Design For Testability
Design For TestabilityDesign For Testability
Design For Testability
 
Java Tools and Techniques for Solving Tricky Problem
Java Tools and Techniques for Solving Tricky ProblemJava Tools and Techniques for Solving Tricky Problem
Java Tools and Techniques for Solving Tricky Problem
 

Kürzlich hochgeladen

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 WorkerThousandEyes
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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 Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Kürzlich hochgeladen (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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

SeaJUG May 2012 mybatis

  • 2. 5/17/2012 2 About 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. 5/17/2012 3 About 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. 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. 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… • http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis • MySQL makes an ok NoSQL (see SauceLabs post)
  • 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. Hibernate Heart of the Proxy DataApplication difference w/myBatis HibernateData Proxy Session Hibernate Session (1st Level Cache) (1st Level Cache) Data Hibernate • LazyInitializationException 2nd Level Cache • SessionException • StaleSessionException • TransientObjectException • PersistentObjectException Data RDBMS
  • 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. ORM Cool/Scary Example List 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 snippet of code result in? A: Impossible to tell from this snippet. Depends on many factors. Mapping configuration for Event, Location objects and associations, as well as the cache configuration. Fixing one code execution path, for example, eager fetching Location, will cause potential problems elsewhere. So, this could result in N*N, (N+1), 1, or even 0 requests.
  • 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. 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. 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. 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. 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. Basic Design Application Mapper Session Interfaces RDBMS
  • 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. 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. 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. Available Annotations • Cache (support for wide variety) • Mappings (result set -> Java object[s]) • Identifier mapping • Static statements • Dynamic statements • Parameters
  • 22. Other Features • Generator (demo) • Migrations (discuss if time) • Maven plugin • Integrations • Spring, Guice, Scala • OSCache, EhCache, Hazelcast
  • 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. Comparison Topic JPA/Hibernate myBatis Developer Java, SQL, HQL, Criteria Java, SQL productivity Caching strategies Two level cache One level cache Debugging Complex Simple (except for more complex mappings, which are localized) Transaction One transaction per session Ironically, easier to use with management w/open-session-in-view only Spring TX. sane route: Spring TX = insanity Schema 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. 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. 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
  • 28. Job Trends (Detail on Smaller)
  • 29. DEMO Code for demo up on GitHub https://github.com/dynacron-group/