SlideShare uma empresa Scribd logo
1 de 16
Baixar para ler offline
Powerful persistence layer
           with
Google Guice & MyBatis

     GuiceCon, March 19th, 2011
               Simone Tripodi
          simonetripodi@apache.org
  http://people.apache.org/~simonetripodi
MyBatis?!?
It reminds Apache iBATIS!


Indeed, MyBatis is the Apache iBATIS fork!
● Fork happened on 2010;

● The whole original team moved the project on

Google Code;
● Apache iBATIS moved to Attic and no more

maintained;
● New extensions after left ASF.
The Guice integration early days...


● Announced as independent project on Google
Code on December 2009 with iBaGuice name;
● Only 2 folks behind it: Simone Tripodi & Marco

Speranza;
● Focused on providing a smart iBATIS bootstrap and

related component injection.
... and the merge with MyBatis


● Donated to MyBatis after the iBATIS fork;
● Community supported;

● Same objectives, better APIs;

● More 3
           rd
              parties integration:
  ● Apache Commons DBCP;

  ● Bone CP;

  ● C3P0;

  ● Built-in MyBatis DataSource.
MyBatis Confguration & Bootstrap


createInjector(new MyBatisModule() {

             @Override
             protected void initialize() {
                 environmentId("test");
                 bindDataSourceProviderType(PooledDataSourceProvider.class);
                 bindTransactionFactoryType(JdbcTransactionFactory.class);
                 addMapperClass(ContactMapper.class);
                 handleType(CustomType.class).with(CustomLongTypeHandler.class);
                 handleType(Address.class).with(AddressTypeHandler.class);
                 addInterceptorClass(CountUpdateInterceptor.class);
             }

       });
MyBatis XML Confguration
                        & Bootstrap


createInjector(new XMLMyBatisModule() {

             @Override
             protected void initialize() {
                 setEnvironmentId("test");
                 setClassPathResource("org/acme/mybatis-config.xml");
             }

       });
Require Mappers injection
public interface ContactMapper {

    void brokenAdd(Contact contact);

    void add(Contact contact);

    void update(Contact contact);

    void delete(Integer id);

    Contact getById(Integer id);

    List<Contact> selectAll();

}




@javax.inject.Singleton
public class ContactMapperClient {

    @javax.inject.Inject
    private ContactMapper contactMapper;

    public void setContactMapper(ContactMapper contactMapper) {
        this.contactMapper = contactMapper;
    }

}
rd
                        3 parties DataSource

createInjector(new XMLMyBatisModule() {

             @Override
             protected void initialize() {
                 // MyBatis built-in
                 bindDataSourceProviderType(UnpooledDataSourceProvider.class);
                 bindDataSourceProviderType(PooledDataSourceProvider.class);
                 bindDataSourceProviderType(JndiDataSourceProvider.class);

                 // c3p0
                 bindDataSourceProviderType(C3p0DataSourceProvider.class);

                 // apache commons-dbcp
                 bindDataSourceProviderType(BasicDataSourceProvider.class);
                 bindDataSourceProviderType(SharedPoolDataSourceProvider.class);
                 bindDataSourceProviderType(PerUserPoolDataSourceProvider.class);

                 // BoneCP
                 bindDataSourceProviderType(BoneCPProvider.class);
             }

       });
Issue: boring transactions!
public class FooDao {

    @Inject
    private SqlSessionManager sessionManager;

    public void setSessionManager(SqlSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public void doFooBar() throws MyDaoException {
        this.sessionManager.startManagedSession(ExecutorType.BATCH,
TransactionIsolationLevel.READ_UNCOMMITTED);
        try {
            FooMapper fooMapper = this.sessionManager.getMapper(FooMapper.class);
            fooMapper.doFoo();
            BarMapper barMapper = this.sessionManager.getMapper(BarMapper.class);
            barMapper.doBar();
            this.sessionManager.commit();
        } catch (Throwable t) {
            this.sessionManager.rollback();
            throw new MyDaoException("Something went wrong", t);
        } finally {
            this.sessionManager.close();
    }

}
Solution: @Transactional

public class FooDao {

    @Inject
    private FooMapper fooMapper;

    @Inject
    private BarMapper barMapper;

    // let's assume setters here

    @Transactional(executorType = ExecutorType.BATCH,
        isolationLevel = TransactionIsolationLevel.READ_UNCOMMITTED,
        rethrowExceptionsAs = MyDaoException.class,
        exceptionMessage = "Something went wrong")
    public void doFooBar() {
        this.fooMapper.doFoo();
        this.barMapper.doBar();
    }

}
JDBC Helper



Small issue: remember JDBC URL patterns and driver
class names
● Create index/catalog? :(

● Create automatic index/catalog! :)
JDBCHelper in action

● Just a module that automatically injects JDBC.url and
JDBC.driver properties used by DataSource providers;
● JDBC.url is a template;

  ● Pattern contains variables in ${name|defaultValue} format;

  ● Patterns require other properties, i.e.:

     jdbc:mysql://${JDBC.host|localhost}:${JDBC.port|3306}/${JDBC.schema}

●   Sample?
createInjector(JdbcHelper.MySQL, ...);
References


MyBatis home page: http://mybatis.org/

Google-Guice integration module:
http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DGuice


Google-Guice integration SVN:
http://mybatis.googlecode.com/svn/sub-projects/mybatis-guice/trunk/
G R A Z I E :)

Mais conteúdo relacionado

Mais procurados

Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPASubin Sugunan
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Anna Shymchenko
 
Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contextsMatthew Morey
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
Jasig Cas High Availability - Yale University
Jasig Cas High Availability -  Yale UniversityJasig Cas High Availability -  Yale University
Jasig Cas High Availability - Yale UniversityJasig CAS
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...Dmytro Sokolov
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)Yurii Kotov
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization AttacksNSConclave
 
Modular javascript
Modular javascriptModular javascript
Modular javascriptZain Shaikh
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialRam132
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10minszmcartor
 

Mais procurados (20)

Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Data repositories
Data repositoriesData repositories
Data repositories
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
 
Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contexts
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
Jasig Cas High Availability - Yale University
Jasig Cas High Availability -  Yale UniversityJasig Cas High Availability -  Yale University
Jasig Cas High Availability - Yale University
 
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...[Java eeconf 2016] spring jta  principles of work with transactions. Dmytro S...
[Java eeconf 2016] spring jta principles of work with transactions. Dmytro S...
 
Dmytro Zaitsev Viper: make your mvp cleaner
Dmytro Zaitsev Viper: make your mvp cleanerDmytro Zaitsev Viper: make your mvp cleaner
Dmytro Zaitsev Viper: make your mvp cleaner
 
Data binding в массы! (1.2)
Data binding в массы! (1.2)Data binding в массы! (1.2)
Data binding в массы! (1.2)
 
Python Deserialization Attacks
Python Deserialization AttacksPython Deserialization Attacks
Python Deserialization Attacks
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
 

Semelhante a Powerful persistence layer with Google Guice & MyBatis

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0Matt Raible
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejugrobbiev
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfThchTrngGia
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... AgainPedro Vicente
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'sAntônio Roberto Silva
 

Semelhante a Powerful persistence layer with Google Guice & MyBatis (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
ExSchema
ExSchemaExSchema
ExSchema
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 

Último

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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
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 FresherRemote DBA Services
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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 Scriptwesley chun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
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
 
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 CVKhem
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
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...Drew Madelung
 
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 SavingEdi Saputra
 
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)wesley chun
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Último (20)

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...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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...
 
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
 
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)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Powerful persistence layer with Google Guice & MyBatis

  • 1. Powerful persistence layer with Google Guice & MyBatis GuiceCon, March 19th, 2011 Simone Tripodi simonetripodi@apache.org http://people.apache.org/~simonetripodi
  • 3. It reminds Apache iBATIS! Indeed, MyBatis is the Apache iBATIS fork! ● Fork happened on 2010; ● The whole original team moved the project on Google Code; ● Apache iBATIS moved to Attic and no more maintained; ● New extensions after left ASF.
  • 4.
  • 5. The Guice integration early days... ● Announced as independent project on Google Code on December 2009 with iBaGuice name; ● Only 2 folks behind it: Simone Tripodi & Marco Speranza; ● Focused on providing a smart iBATIS bootstrap and related component injection.
  • 6. ... and the merge with MyBatis ● Donated to MyBatis after the iBATIS fork; ● Community supported; ● Same objectives, better APIs; ● More 3 rd parties integration: ● Apache Commons DBCP; ● Bone CP; ● C3P0; ● Built-in MyBatis DataSource.
  • 7. MyBatis Confguration & Bootstrap createInjector(new MyBatisModule() { @Override protected void initialize() { environmentId("test"); bindDataSourceProviderType(PooledDataSourceProvider.class); bindTransactionFactoryType(JdbcTransactionFactory.class); addMapperClass(ContactMapper.class); handleType(CustomType.class).with(CustomLongTypeHandler.class); handleType(Address.class).with(AddressTypeHandler.class); addInterceptorClass(CountUpdateInterceptor.class); } });
  • 8. MyBatis XML Confguration & Bootstrap createInjector(new XMLMyBatisModule() { @Override protected void initialize() { setEnvironmentId("test"); setClassPathResource("org/acme/mybatis-config.xml"); } });
  • 9. Require Mappers injection public interface ContactMapper { void brokenAdd(Contact contact); void add(Contact contact); void update(Contact contact); void delete(Integer id); Contact getById(Integer id); List<Contact> selectAll(); } @javax.inject.Singleton public class ContactMapperClient { @javax.inject.Inject private ContactMapper contactMapper; public void setContactMapper(ContactMapper contactMapper) { this.contactMapper = contactMapper; } }
  • 10. rd 3 parties DataSource createInjector(new XMLMyBatisModule() { @Override protected void initialize() { // MyBatis built-in bindDataSourceProviderType(UnpooledDataSourceProvider.class); bindDataSourceProviderType(PooledDataSourceProvider.class); bindDataSourceProviderType(JndiDataSourceProvider.class); // c3p0 bindDataSourceProviderType(C3p0DataSourceProvider.class); // apache commons-dbcp bindDataSourceProviderType(BasicDataSourceProvider.class); bindDataSourceProviderType(SharedPoolDataSourceProvider.class); bindDataSourceProviderType(PerUserPoolDataSourceProvider.class); // BoneCP bindDataSourceProviderType(BoneCPProvider.class); } });
  • 11. Issue: boring transactions! public class FooDao { @Inject private SqlSessionManager sessionManager; public void setSessionManager(SqlSessionManager sessionManager) { this.sessionManager = sessionManager; } public void doFooBar() throws MyDaoException { this.sessionManager.startManagedSession(ExecutorType.BATCH, TransactionIsolationLevel.READ_UNCOMMITTED); try { FooMapper fooMapper = this.sessionManager.getMapper(FooMapper.class); fooMapper.doFoo(); BarMapper barMapper = this.sessionManager.getMapper(BarMapper.class); barMapper.doBar(); this.sessionManager.commit(); } catch (Throwable t) { this.sessionManager.rollback(); throw new MyDaoException("Something went wrong", t); } finally { this.sessionManager.close(); } }
  • 12. Solution: @Transactional public class FooDao { @Inject private FooMapper fooMapper; @Inject private BarMapper barMapper; // let's assume setters here @Transactional(executorType = ExecutorType.BATCH, isolationLevel = TransactionIsolationLevel.READ_UNCOMMITTED, rethrowExceptionsAs = MyDaoException.class, exceptionMessage = "Something went wrong") public void doFooBar() { this.fooMapper.doFoo(); this.barMapper.doBar(); } }
  • 13. JDBC Helper Small issue: remember JDBC URL patterns and driver class names ● Create index/catalog? :( ● Create automatic index/catalog! :)
  • 14. JDBCHelper in action ● Just a module that automatically injects JDBC.url and JDBC.driver properties used by DataSource providers; ● JDBC.url is a template; ● Pattern contains variables in ${name|defaultValue} format; ● Patterns require other properties, i.e.: jdbc:mysql://${JDBC.host|localhost}:${JDBC.port|3306}/${JDBC.schema} ● Sample? createInjector(JdbcHelper.MySQL, ...);
  • 15. References MyBatis home page: http://mybatis.org/ Google-Guice integration module: http://code.google.com/p/mybatis/downloads/list?can=3&q=Product%3DGuice Google-Guice integration SVN: http://mybatis.googlecode.com/svn/sub-projects/mybatis-guice/trunk/
  • 16. G R A Z I E :)