0
点赞
收藏
分享

微信扫一扫

使用Java配置MyBatis

天使魔鬼 2023-09-21 阅读 37


我们已经讨论了各种 MyBatis 配置元素,如 envronments,typeAlias,和 typeHandlers,以及如何使用

XML 配置它们。即使你想使用基于 Java API 的 MyBatis 配置,经历前面的学习是大有好处的,它可以帮你对这些配置元素有更好的理解。

配置SqlSessionFactory

MyBatis 的 SqlSessionFactory 接口除了使用基于 XML 的配置创建外也可以通过 Java API 编程式地被创建。每个在 XML 中配置的元素,都可以编程式的创建。

使用 Java API 创建 SqlSessionFactory,代码如下:

public static SqlSessionFactory getSqlSessionFactoryUsingJavaAPI() {
    if (javaSqlSessionFactory == null) {
        try {
            DataSource dataSource = DataSourceFactory.getDataSource();
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);
            Configuration configuration = new Configuration(environment);
            configuration.getTypeAliasRegistry().registerAlias("student", Student.class);
            configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.class);
            configuration.addMapper(StudentMapper.class);
            javaSqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return javaSqlSessionFactory;
}

这个配置里,加载了一个映射类。映射类是包含了 SQL 映射注解的 Java类,可以用来取代 XML。然而 ,由于 Java 注解的一些限制和 MyBatis 映射的复杂性,一些高级的映射还是要用 XML 来配置,比如嵌套映射等。由于这个原因,MyBatis 会自动查找和加载已经存在的 XML。

环境配置 Environment

我们需要为想使用 MaBatis 连接的每一个数据库创建一个 Enviroment 对象。为了使用每一个环境,我们需要为每一个环境 environment 创建一个 SqlSessionFactory 对象。 而创建 Environment 对象, 我们需要 java.sql.DataSource和 TransactionFactory 实例。下面让我们看看如何创建 DataSource 和 TransactionFactory 对象

数据源 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 {
    private static final Properties PROPERTIES = new Properties();
    static {
        try {
            InputStream is = DataSourceFactory.class.getResourceAsStream("/mysql.properties");
            PROPERTIES.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource() {
        String driver = PROPERTIES.getProperty("jdbc.driverClassName");
        String url = PROPERTIES.getProperty("jdbc.url");
        String username = PROPERTIES.getProperty("jdbc.username");
        String password = PROPERTIES.getProperty("jdbc.password");
        PooledDataSource dataSource = new PooledDataSource(driver, url, username, password);
        return dataSource;
    }
}

一般在生产环境中,DataSource 会被应用服务器配置,并通过 JNDI 获取 DataSource 对象,如下所示:

public static DataSource getJNDIDataSource() {
    String dataSourceJNDIName = "java:comp/env/jdbc/MyBatisDemoDS";
    try {
        InitialContext ctx = new InitialContext();
        DataSource dataSource = (DataSource) ctx.lookup(dataSourceJNDIName);
        return dataSource;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

当前有一些流行的第三方类库,如 commons-dbcp 和 c3p0实现了 java.sql.DataSource,你可以使用它们来创建dataSource。

事务工厂 TransactionFactory

MyBatis 支持一下两种 TransactionFactory 实现:

  • JdbcTransactionFactory
  • ManagedTransactionFactory

如果你的应用程序运行在未托管(non-managed)的环境中,你应该使用 JdbcTransactionFactory:

DataSource dataSource = DataSourceFactory.getDataSource(); 
TransactionFactory txnFactory = new JdbcTransactionFactory(); 
Environment environment = new Environment("development", txnFactory, dataSource);

如果你的应用程序运行在托管(managed)的环境中,并且使用容器支持的事务管理服务,你应该使用ManagedTransactionFactory:

DataSource dataSource = DataSourceFactory.getDataSource();

TransactionFactory txnFactory = new ManagedTransactionFactory();

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

类型别名 typeAliases

MyBatis 提供以下几种通过 Configuration 对象注册类型别名的方法:

1. 根据默认的别名规则,使用一个类的首字母小写、非完全限定的类名作为别名注册,可使用以下代码:

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

2. 指定别名注册,可使用以下代码:

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

3. 通过类的完全限定名注册相应类别名,可使用一下代码:

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

4. 为某一个包中的所有类注册别名,可使用以下代码:

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

5. 为在 com.mybatis3.domain package 包中所有的继承自 Identifiable 类型的类注册别名,可使用以下代码:

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

类型处理器 typeHandlers

MyBatis 提供了一系列使用 Configuration 对象注册类型处理器(type handler)的方法。我们可以通过以下方式注册自定义的类处理器:

1. 为某个特定的类注册类处理器:

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

2. 注册一个类处理器:

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

3. 注册 com.mybatis3.typehandlers 包中的所有类型处理器:

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

全局参数设置 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 );

Mappers

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

1. 添加一个 Mapper 接口,可使用以下代码:

configuration.addMapper(StudentMapper.class);

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

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

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

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

举报

相关推荐

0 条评论