筆記:MyBatis 使用 Java API配置


我們已經討論了各種MyBatis配置元素,如envronments、typeAlias和typeHandlers,以及如何使用XML配置它們。即使你想使用基於JavaAPI的MyBatis配置,MyBatis的SqlSessionFactory接口除了使用基於XML的配置創建外也可以通過Java API 編程式地被創建。每個在XML中配置的元素,都可以編程式的創建。使用Java API創建SqlSessionFactory,代碼如下:

   

    public static SqlSessionFactory getSqlSessionFactory()  

    {  

        SqlSessionFactory sqlSessionFactory = null;  

        try  

        {  

            DataSource dataSource = DataSourceFactory.getDataSource();  

            TransactionFactory transactionFactory = new  xJdbcTransactionFactory();  

            Environment environment = new Environment("development",  transactionFactory, dataSource);  

            Configuration configuration = new Configuration(environment);  

            configuration.getTypeAliasRegistry().registerAlias("student",  Student.class);  

            configuration.getTypeHandlerRegistry().register(PhoneNumber. class, PhoneTypeHandler.class);  

            configuration.addMapper(StudentMapper.class);  

            sqlSessionFactory = new SqlSessionFactoryBuilder().  build(configuration);  

        }  

        catch (Exception e)  

        {  

            throw new RuntimeException(e);  

        }  

          

  1. 環境配置 environment

    我們需要為想使用MaBatis連接的每一個數據庫創建一個 Enviroment對象。為了使用每一個環境,我們需要為每一個環境environment創建一個SqlSessionFactory對象。而創建Environment對象,我們需要java.sql.DataSource和TransactionFactory實例。下面讓我們看看如何創建DataSource 和 TransactionFactory 對象。

  2. 數據源DataSource

    MyBatis支持三種內建的DataSource類型: UNPOOLED, POOLED, 和JNDI.

  • UNPOOLED類型的數據源dataSource為每一個用戶請求創建一個數據庫連接。在多用戶並發應用中,不建議使用。
  • POOLED類型的數據源dataSource創建了一個數據庫連接池,對用戶的每一個請求,會使用緩沖池中的一個可用的Connection對象,這樣可以提高應用的性能。MyBatis提供了org.apache.ibatis.datasource.pooled.PooledDataSource 實現javax.sql.DataSource來創建連接池。
  • JNDI類型的數據源dataSource使用了應用服務器的數據庫連接池,並且使用JNDI查找來獲取數據庫連接。

讓我們看一下怎樣通過MyBatis的PooledDataSource獲得DataSource對象,如下:

        public class DataSourceFactory  

        {  

            public static DataSource getDataSource()  

            {  

                String driver = "com.mysql.jdbc.Driver";  

                String url = "jdbc:mysql://localhost:3306/mybatisdemo";  

                String username = "root";  

                String password = "admin";  

                PooledDataSource dataSource = new PooledDataSource(driver, url,  

                        username, password);  

                return dataSource;  

            }  

一般在生產環境中,DataSource會被應用服務器配置,並通過JNDI獲取DataSource對象,如下所示:

        public class DataSourceFactory  

        {  

            public static DataSource getDataSource()  

            {  

                String jndiName = "java:comp/env/jdbc/MyBatisDemoDS";  

                try  

                {  

                    InitialContext ctx = new InitialContext();  

                    DataSource dataSource = (DataSource) ctx.lookup(jndiName);  

                    return dataSource;  

                }  

                catch (NamingException e)  

                {  

                    throw new RuntimeException(e);  

                }  

            }

}

當前有一些流行的第三方類庫,如commons-dbcp和c3p0實現了java.sql.DataSource,你可以使用它們來創建dataSource。

  1. 事務工廠TransactionFactory

    MyBatis支持一下兩種TransactionFactory實現:

  • JdbcTransactionFactory
  • ManagedTransactionFactory

如果你的應用程序運行在未托管(non-managed)的環境中,你應該使用JdbcTransactionFactory。

        DataSource dataSource = DataSourceFactory.getDataSource();  

        TransactionFactory txnFactory = new JdbcTransactionFactory();  

        Environment environment = new Environment("development", txnFactory, dataSource);  

如果你的應用程序運行在未托管(non-managed)的環境中,並且使用容器支持的事務管理服務,你應該使用ManagedTransactionFactory。

        DataSource dataSource = DataSourceFactory.getDataSource();  

        TransactionFactory txnFactory = new ManagedTransactionFactory();  

Environment environment = new Environment("development", txnFactory, dataSource); 

  1. 類型別名typeAliases

    MyBatis 提供以下幾種通過Configuration對象注冊類型別名的方法:

  • 根據默認的別名規則,使用一個類的首字母小寫、非完全限定的類名作為別名注冊,可使用以下代碼:

    configuration.getTypeAliasRegistry().registerAlias(Student.class);  

  • 指定指定別名注冊,可使用以下代碼:

    configuration.getTypeAliasRegistry().registerAlias("Student",Student.class);  

  • 通過類的完全限定名注冊相應類別名,可使用一下代碼:

    configuration.getTypeAliasRegistry().registerAlias("Student", "com.mybatis3.domain.Student");

  • 為某一個包中的所有類注冊別名,可使用以下代碼:

    configuration.getTypeAliasRegistry().registerAliases("com. mybatis3.domain"); 

  • 為在com.mybatis3.domain package包中所有的繼承自Identifiable類型的類注冊別名,可使用以下代碼:

    configuration.getTypeAliasRegistry().registerAliases("com. mybatis3.domain", Identifiable.class);  

  1. 類型處理器typeHandlers

    MyBatis提供了一系列使用Configuration對象注冊類型處理器(type handler)的方法。我們可以通過以下方式注冊自定義的類處理器:

  • 為某個特定的類注冊類處理器:

    configuration.getTypeHandlerRegistry().register(PhoneNumber.class, PhoneTypeHandler.class);

  • 注冊一個類處理器:

    configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.class);

  • 注冊com.mybatis3.typehandlers包中的所有類型處理器:

    configuration.getTypeHandlerRegistry().register("com.mybatis3.typehandlers");

  1. 全局參數設置Settings

    MyBatis提供了一組默認的,能夠很好地適用大部分的應用的全局參數設置。然而,你可以稍微調整這些參數,讓它更好地滿足你應用的需要。你可以使用下列方法將全局參數設置成想要的值。

            configuration.setCacheEnabled(true);  

            configuration.setLazyLoadingEnabled(false);  

            configuration.setMultipleResultSetsEnabled(true);  

            configuration.setUseColumnLabel(true);  

            configuration.setUseGeneratedKeys(false);  

            configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);  

            configuration.setDefaultExecutorType(ExecutorType.SIMPLE);  

            configuration.setDefaultStatementTimeout(25);  

            configuration.setSafeRowBoundsEnabled(false);  

            configuration.setMapUnderscoreToCamelCase(false);  

            configuration.setLocalCacheScope(LocalCacheScope.SESSION);  

            configuration.setAggressiveLazyLoading(true);  

            configuration.setJdbcTypeForNull(JdbcType.OTHER);  

            Set<String> lazyLoadTriggerMethods = new HashSet<String>();  

            lazyLoadTriggerMethods.add("equals");  

            lazyLoadTriggerMethods.add("clone");  

            lazyLoadTriggerMethods.add("hashCode");  

            lazyLoadTriggerMethods.add("toString");  

            configuration.setLazyLoadTriggerMethods(lazyLoadTriggerMethods );

  2. Mappers

    MyBatis提供了一些使用Configuration對象注冊Mapper XML文件和Mappe接口的方法。

  • 添加一個Mapper接口,可使用以下代碼:

    configuration.addMapper(StudentMapper.class);  

  • 添加 com.mybatis3.mappers包中的所有Mapper XML文件或者Mapper接口,可使用以下代碼:

    configuration.addMappers("com.mybatis3.mappers");  

  • 添加所有com.mybatis3.mappers包中的拓展了特定Mapper接口的Maper接口,如 aseMapper,可使用如下代碼:

    configuration.addMappers("com.mybatis3.mappers", BaseMapper.class);  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM