MyBatis与Spring的结合

MyBatis与Spring的结合

首先,先导入Spring和MyBatis的核心包,C3P0连接池包,数据库连接包,log4j包;
这里写图片描述

在Spring的配置文件applicationContext.xml中:

<!-- 配置Spring本身 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver">
        </property>
        <property name="jdbcUrl" value="jdbc:mysql:///abc?characterEncoding=UTF-8"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>

    <bean id="txM"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务 -->
    <tx:advice id="txAdvice" transaction-manager="txM">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut expression="execution( * cn..*Service.*(..))"
            id="cut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="cut" />
    </aop:config>

    <!-- 配置mybatis的SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--版本1 加载mybatis-config.xml,通过该文件进一步加载其中配置的 -->
        <property name="configLocation">
            <value>classpath:mybatis-config.xml</value>
        </property>
        <!--版本2 直接加载映射文件,不要配置文件mybatis-config.xml -->
        <!-- <property name="mapperLocations"> <list> <value>classpath:cn/hncu/domain/*.xml</value> 
            </list> </property> -->
    </bean>
    <!-- 包装类,构造出sessionFactoy -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"></constructor-arg>
    </bean>

演示代码不做过多解释,也是MVC架构,然后注入DAO,service,

applicationContext.xml中:

<!-- 注入sqlSession,dao -->
    <bean id="userDao" class="cn.hncu.user.dao.UserDaoImpl">
        <property name="sqlSession" ref="sqlSession"></property>
    </bean>
    <bean id="userService" class="cn.hncu.user.service.UserServiceImpl">
        <property name="dao" ref="userDao"></property>
    </bean>
    <!-- impl2,注入到父类 -->
    <bean id="userDao2" class="cn.hncu.user.dao.UserDaoImpl2">
        <property name="sqlSessionTemplate" ref="sqlSession"></property>
    </bean>

MyBatis配置文件就不用写连接数据库,直接从Spring中拿:

<configuration>

    <!-- 配置别名 -->
    <typeAliases>
        <typeAlias alias="User" type="cn.hncu.domain.User"/>
    </typeAliases>

    <mappers>
        <mapper resource="cn/hncu/domain/User.xml"/>
    </mappers>
</configuration>

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值