[mybatis-spring]sqlSessionFactoryBean

在mybatis中,SqlSessionFactory由SqlSessionFactoryBuilder创建.

在mybatis-spring中,是由SqlSessionFactoryBean创建的.

1.创建

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

注意SqlSessionFactoryBean实现了Spring的FactoryBean接口 (see section 3.8 of the Spring documentation).

这意味着Spring最终创建的bean不是SqlSessionFactoryBean自身,

而是SqlSessionFactoryBean的getObject()方法的返回结果.(看Java等价代码第二行)

在这种情况下,Spring会在程序启动时为你创建一个SqlSessionFactory,并且将其以sqlSessionFactory 的名称存储.

等价的Java代码如下:

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
SqlSessionFactory sessionFactory = factoryBean.getObject();

通常在mybatis-spring的使用中,不需要直接使用SqlSessionFactoryBean或者对应的SqlSessionFactory.

Session factory会被注入到MapperFactoryBean或者其他继承SqlSessionDaoSupport的DAO.

2.属性.

唯一必须的一个属性:JDBC 数据源.

常用的属性有configLocation,用来指定Mybatis的配置XML文件.

只有当MyBatis配置需要更改时才需要使用.这时,通常还会选择<settings> or <typeAliases>

  注意:这个配置不需要是一个完整的mybatis配置. Specifically,任何environments,dataSourcec transactionManager都会被忽略.

SqlSessionFactoryBean 使用设置的值来创建它自己的定制化mybatis environment.

#另一个需要配置文件的原因是:#

mybatis mapper XML 文件不是和mapper类 在同一个classpath 位置下.

这样配置有两个可选的方法.

  第一个是手动指定XML文件的classpath,使用mybatis配置文件的<mappers> 选项.

  //之前的写法.

  第二个是使用factory bean的 mapperLocations 属性.

The mapperLocations property takes a list of resource locations. 

这个属性可以用来指定mybatis xml mapper 文件.

value可以办好Ant-style pattern来加载某个目录下的单所有文件,

or to recursively search all paths from a base location. 

(或者递归地搜索基位置下的所有路径)

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" />
</bean>

这回加载sample.config.mappers 包和其子包下的所有xml格式的mybatis mapper文件.

 

/*

One property that may be required in an environment with container managed transactions is transactionFactoryClass .

Please see the relevant section in the Transactions chapter.

In case you are using the multi-db feature you will need to set the databaseIdProvider property:

*/

mybatis-spring 1.3.0版本后,增加了configuration属性,
可以将mybatis的配置文件省略,而将其配置内容放入该bean下的一个属性中

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configuration">
    <bean class="org.apache.ibatis.session.Configuration">
      <property name="mapUnderscoreToCamelCase" value="true"/>
    </bean>
  </property>
</bean>

 

转载于:https://www.cnblogs.com/zienzir/p/9109773.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值