MyBatis与Spring的整合
第一步:导入jar包
包含spring、mybatis、mybatis-spring的jar包,如有需要的朋友可以直接留言哦~
第二步:创建两个Source Folder文件夹( resources和test)
第三步:创建实体类
第四步:创建dao层接口、实现类、mapper映射文件
1、BillMapper接口
package cn.smbms.dao.bill; import java.util.List; import cn.smbms.pojo.Bill; import org.apache.ibatis.annotations.Param; public interface BillMapper { /** * 增加订单 * @param bill * @return * @throws Exception */ public int add(Bill bill)throws Exception; /** * 通过查询条件获取供应商列表-模糊查询-getBillList * @return * @throws Exception */ public List<Bill> getBillList(@Param(value = "providerId") String providerId, @Param(value = "productName") String productName, @Param(value = "isPayment") String isPayment)throws Exception; /** * 通过delId删除Bill * @param delId * @return * @throws Exception */ public int deleteBillById(String delId)throws Exception; /** * 通过billId获取Bill * @param id * @return * @throws Exception */ public Bill getBillById(String id)throws Exception; /** * 修改订单信息 * @param bill * @return * @throws Exception */ public int modify(Bill bill)throws Exception; /** * 根据供应商ID查询订单数量 * @param providerId * @return * @throws Exception */ public int getBillCountByProviderId(String providerId)throws Exception; }
2、BillMapperImpl实现类
package cn.smbms.dao.bill; import cn.smbms.pojo.Bill; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class BillMapperImpl implements BillMapper { ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml"); BillMapper mapper= (BillMapper) context.getBean("billMapper"); @Override public int add(Bill bill) throws Exception { return mapper.add(bill); } @Override public List<Bill> getBillList(String providerId, String productName, String isPayment) throws Exception { return mapper.getBillList(providerId, productName, isPayment); } @Override public int deleteBillById(String delId) throws Exception { return mapper.deleteBillById(delId); } @Override public Bill getBillById(String id) throws Exception { return mapper.getBillById(id); } @Override public int modify(Bill bill) throws Exception { return mapper.modify(bill); } @Override public int getBillCountByProviderId(String providerId) throws Exception { return mapper.getBillCountByProviderId(providerId); } }
3、BillMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.smbms.dao.bill.BillMapper"> <insert id="add" parameterType="cn.smbms.pojo.Bill"> insert into smbms_bill (billCode, productName, productDesc, productUnit, productCount, totalPrice, isPayment, createdBy, creationDate, modifyBy, modifyDate, providerId) values (#{billCode},#{productName},#{productDesc},#{productUnit},#{productCount}, #{totalPrice},#{isPayment},#{createdBy},#{creationDate},#{modifyBy}, #{modifyDate},#{providerId}) </insert> <select id="getBillList" resultType="cn.smbms.pojo.Bill"> select b.*,p.proName as providerName from smbms_bill b, smbms_provider p where b.providerId = p.id <if test="providerId!=null"> and providerId=#{providerId} </if> <if test="providerId!=null"> and productName like CONCAT('%',#{productName},'%') </if> <if test="providerId!=null"> and isPayment=#{isPayment} </if> </select> <delete id="deleteBillById" parameterType="int"> delete from smbms_bill where id=#{id} </delete> <select id="getBillById" resultType="cn.smbms.pojo.Bill"> select b.*,p.proName as providerName from smbms_bill b, smbms_provider p where b.providerId = p.id and b.id=#{id} </select> <update id="modify" parameterType="cn.smbms.pojo.Bill"> update smbms_bill set billCode=#{billCode}, productName=#{productName}, productDesc=#{productDesc}, productUnit=#{productUnit},productCount=#{productCount},totalPrice=#{totalPrice}, isPayment=#{isPayment},providerId=#{providerId},modifyBy=#{modifyBy},modifyDate=#{modifyDate} where id = #{id} </update> <select id="getBillCountByProviderId" resultType="int"> select count(1) as billCount from smbms_bill where providerId = #{providerId} </select> </mapper>
第五步:创建service层接口、实现类
1、BillService接口
package cn.smbms.service.bill; import java.util.List; import cn.smbms.pojo.Bill; public interface BillService { /** * 增加订单 * @param bill * @return */ public boolean add(Bill bill); /** * 通过条件获取订单列表-模糊查询-billList * @param bill * @return */ public List<Bill> getBillList(Bill bill); /** * 通过billId删除Bill * @param delId * @return */ public boolean deleteBillById(String delId); /** * 通过billId获取Bill * @param id * @return */ public Bill getBillById(String id); /** * 修改订单信息 * @param bill * @return */ public boolean modify(Bill bill); }
2、BillServiceImpl实现类
package cn.smbms.service.bill; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import cn.smbms.dao.BaseDao; import cn.smbms.dao.bill.BillMapper; import cn.smbms.dao.bill.BillMapperImpl1; import cn.smbms.pojo.Bill; public class BillServiceImpl implements BillService { private BillMapper billMapper; public BillServiceImpl(){ billMapper = new BillMapperImpl1(); } @Override public boolean add(Bill bill) { // TODO Auto-generated method stub boolean flag = false; Connection connection = null; try { connection = BaseDao.getConnection(); connection.setAutoCommit(false);//开启JDBC事务管理 if(billMapper.add(bill) > 0) flag = true; connection.commit(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); try { System.out.println("rollback=================="); connection.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }finally{ //在service层进行connection连接的关闭 BaseDao.closeResource(connection, null, null); } return flag; } @Override public List<Bill> getBillList(Bill bill) { // TODO Auto-generated method stub Connection connection = null; List<Bill> billList = null; System.out.println("query productName ---- > " + bill.getProductName()); System.out.println("query providerId ---- > " + bill.getProviderId()); System.out.println("query isPayment ---- > " + bill.getIsPayment()); try { connection = BaseDao.getConnection(); billList = billMapper.getBillList("","",""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return billList; } @Override public boolean deleteBillById(String delId) { // TODO Auto-generated method stub Connection connection = null; boolean flag = false; try { connection = BaseDao.getConnection(); if(billMapper.deleteBillById(delId) > 0) flag = true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return flag; } @Override public Bill getBillById(String id) { // TODO Auto-generated method stub Bill bill = null; Connection connection = null; try{ connection = BaseDao.getConnection(); bill = billMapper.getBillById(id); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); bill = null; }finally{ BaseDao.closeResource(connection, null, null); } return bill; } @Override public boolean modify(Bill bill) { // TODO Auto-generated method stub Connection connection = null; boolean flag = false; try { connection = BaseDao.getConnection(); if(billMapper.modify(bill) > 0) flag = true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ BaseDao.closeResource(connection, null, null); } return flag; } }
第六步:在resource文件夹中编写mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--这里可以加入类型别名,其他配置已经转到Spring中--> </configuration>
第七步:在resource文件夹中编写applicationContext.xml
因为测试了三种MyBatis与Spring整合的方法,所以配置文件显得很冗长,请注意注掉的部分代码!
最终采用的是org.mybatis.spring.mapper.MapperScannerConfigurer,这也是在实际工作情况中使用较多的一种整合方式。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--引入properties文件--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:database.properties</value> </property> </bean> <!--配置DataSource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${user}"/> <property name="password" value="${pwd}"/> </bean> <!--配置SqlSessionFactoryBean--> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--引用数据源组件--> <property name="dataSource" ref="dataSource"/> <!--引用MyBatis配置文件中的配置,必须有,里面的内容可以为空--> <!-- 有关mybatis的特性配置可以写在该文件中,比如插件,setting属性等 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 指定mapper文件位置,当不指定时mapper映射文件默认与接口在一个包下 --> <property name="mapperLocations" value="classpath*:cn/smbms/dao/**/*.xml"/> </bean> <!-- Mybatis-Spring为我们提供了一个实现了SqlSession接口的SqlSessionTemplate类,它是线程安全的, 可以被多个Dao同时使用。 同时它还跟Spring的事务进行了关联,确保当前被使用的SqlSession是一个已经和Spring的事务进行绑定了的。 而且它还可以自己管理Session的提交和关闭。当使用了Spring的事务管理机制后, SqlSession还可以跟着Spring的事务一起提交和回滚。 --> <!--配置SqlSessionTemplate--> <bean id="session" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="factory"></constructor-arg> </bean> <!--配置实现类--> <!--<bean id="userMapper" class="cn.smbms.dao.user.UserMapperImpl">--> <!--<property name="session" ref="session"/>--> <!--<property name="session" ref="session"></property>--> <!--</bean>--> <!--直接配置接口--> <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">--> <!--<property name="mapperInterface" value="cn.smbms.dao.user.UserMapper"/>--> <!--<property name="sqlSessionFactory" ref="factory"/>--> <!--</bean>--> <!--直接配置接口--> <!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">--> <!--<property name="basePackage" value="cn.smbms.dao"/>--> <!--<property name="sqlSessionFactoryBeanName" value="factory"/>--> <!--</bean>--> <!--配置扫描包--> <!-- 代理dao层接口实现类 --> <bean id="mapConf" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.smbms.dao"/> </bean> <!--配置扫描注解定义的业务Bean--> <context:component-scan base-package="cn.smbms.service"/> <!--<context:annotation-config></context:annotation-config>--> <!--配置事务管理bean--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置对应的方法和事务传播机制--> <!--<tx:advice id="txAdvice" transaction-manager="txManager">--> <!--<tx:attributes>--> <!--<tx:method name="updateTian*" timeout="-1"/>--> <!--<tx:method name="*" propagation="REQUIRED"/>--> <!--</tx:attributes>--> <!--</tx:advice>--> <!--配置定义切面--> <!--<aop:config>--> <!--<!–定义切入点–>--> <!--<aop:pointcut id="serviceMethod" expression="execution(public int updateTian())"/>--> <!--<!–将事务增强与切入点组合–>--> <!--<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>--> <!--</aop:config>--> <!--注解--> <tx:annotation-driven transaction-manager="txManager"/> </beans>
第八步:在test文件夹中编写测试方法
一个简单的快捷键:ctrl+shift+T ,我们创建BillMapperImpl类的测试方法,对功能模块进行测试。
package cn.smbms.dao.bill; import cn.smbms.pojo.Bill; import org.apache.log4j.Logger; import org.junit.Test; import java.math.BigDecimal; import java.util.Date; import static org.junit.Assert.*; public class BillMapperImplTest { Logger logger=Logger.getLogger(BillMapperImplTest.class); BillMapper mapper=new BillMapperImpl(); @Test public void add() { Bill bill=new Bill(); bill.setBillCode("BILL2016_020"); bill.setProductName("鞭炮"); bill.setProductDesc("烟花炮竹"); bill.setProductUnit("箱"); bill.setProductCount(BigDecimal.valueOf(500)); bill.setTotalPrice(BigDecimal.valueOf(1000)); bill.setIsPayment(1); bill.setCreatedBy(1); bill.setCreationDate(new Date()); bill.setProviderId(13); try { int row=mapper.add(bill); if (row>0){ logger.info("成功插入一条商品信息"); }else { logger.info("插入不成功"); } } catch (Exception e) { e.printStackTrace(); } } @Test public void getBillList() { try { logger.info(mapper.getBillList("6","油","2")); } catch (Exception e) { e.printStackTrace(); } } @Test public void deleteBillById() { try { int row=mapper.deleteBillById("26"); if (row>0){ logger.info("删除成功"); }else { logger.info("删除失败"); } } catch (Exception e) { e.printStackTrace(); } } @Test public void getBillById() { try { logger.info(mapper.getBillById("1")); } catch (Exception e) { e.printStackTrace(); } } @Test public void modify() { Bill bill=new Bill(); bill.setId(14); bill.setBillCode("151654"); bill.setProductName("西北香米"); try { int row=mapper.modify(bill); if (row>0){ logger.info("成功修改一条商品信息"); }else { logger.info("修改不成功"); } } catch (Exception e) { e.printStackTrace(); } } @Test public void getBillCountByProviderId() { try { logger.info("查询供应商数"+mapper.getBillCountByProviderId("1")); } catch (Exception e) { e.printStackTrace(); } } }
以上,便是采用MapperScannerConfigurer方式进行的MyBatis与Spring的整合!