MyBatis与Spring的结合

来源:互联网 发布:安庆市网络广播电视 编辑:程序博客网 时间:2024/05/17 04:27

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>

这里写图片描述

原创粉丝点击