首页 > 代码库 > springMVC+MyBatis+Spring 整合(3)
springMVC+MyBatis+Spring 整合(3)
spring mvc 与mybatis 的整合.
加入配置文件:
spring-mybaits.xml
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- myBatis文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> <property name="mapperLocations" value="classpath:com/**/mapping/*Mapper.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com..*.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 拦截器方式配置事物 --> <!-- PROPAGATION_SUPPORTS: 如果已经存在事务,则加入事务;如果没有事务,则以非事务的方式执行; PROPAGATION_MANDATORY: 使用当前事务, 如果没有, 则抛出异常; PROPAGATION_REQUIRED: 新建事务,如果当前有事务, 则挂起; P ROPAGATION_NOT_SUPPORTED:以非事务的方式执行, 如果当前有事务, 则挂起; PROPAGATION_NEVER:以非事务的方式执行, 如果当前有事务,则抛出异常; +/-Exception</prop> + 表示异常出现时事物提交 - 表示异常出现时事务回滚 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <!----> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com..service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> <aop:config> <aop:pointcut id="transactionPointcut2" expression="execution(* com..service.*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut2" advice-ref="transactionAdvice" /> </aop:config> </beans>
配置数据源监听器:
spring-druid.xml
<?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:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!-- 配置druid监控spring jdbc --> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> </bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>com..service.*</value> </list> </property> </bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> </beans>
配置数据源spring-dataSource.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- JNDI方式配置数据源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="http://www.mamicode.com/${jndiName}"></property> </bean> --> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="http://www.mamicode.com/true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="http://www.mamicode.com/33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="http://www.mamicode.com/stat" /> --> <property name="filters" value="mergeStat" /> </bean> </beans>
配置连接属性
#hibernate.dialect=org.hibernate.dialect.OracleDialect #driverClassName=oracle.jdbc.driver.OracleDriver #validationQuery=SELECT 1 FROM DUAL #jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl #jdbc_username=sypro #jdbc_password=sypro hibernate.dialect=org.hibernate.dialect.MySQLDialect driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/c_sai?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc_username=root jdbc_password= #hibernate.dialect=org.hibernate.dialect.SQLServerDialect #driverClassName=net.sourceforge.jtds.jdbc.Driver #validationQuery=SELECT 1 #jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy #jdbc_username=sa #jdbc_password=123456 #hibernate.dialect=org.hibernate.dialect.DerbyDialect #driverClassName=org.apache.derby.jdbc.EmbeddedDriver #validationQuery=SELECT 1 #jdbc_url=jdbc:derby:sy;create=true #jdbc_username=sypro #jdbc_password=sypro #jndiName=java:comp/env/dataSourceName hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=true sessionInfoName=sessionInfo uploadFieldName=filedata uploadFileMaxSize=20971520 uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid uploadDirectory=attached
修改serviceImpl
package com.sd.test.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.sd.test.dao.TTestMapper; import com.sd.test.model.TTest; import com.sd.test.service.TestService; @Service public class TestServiceImpl implements TestService { @Resource private TTestMapper mapper; @Override public void save(Object obj) { int i = this.mapper.insert((TTest) obj); System.out.println("save = " + i); System.out.println("save"); } @Override public Object selectOne(Object obj) { System.out.println("selectOne"); TTest tt = null; tt = this.mapper.selectByPrimaryKey(Integer.parseInt(obj.toString())); return tt; } @Override public Object put(Object obj) { System.out.println("put"); return this.mapper.insert((TTest) obj); } }
controller 代码如下:
package com.sd.test.controller; import java.io.IOException; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.sd.test.model.TTest; import com.sd.test.service.TestService; @Controller @RequestMapping("/test") public class TestController { @Resource private TestService testService; @RequestMapping("selectOne") public void findById(HttpServletRequest request, HttpServletResponse response) throws IOException { String id = request.getParameter("id"); Object obj = this.testService.selectOne(Integer.parseInt(id)); response.getWriter().print(obj); } @RequestMapping("save") public void save(HttpServletRequest request, HttpServletResponse response) { String name = request.getParameter("name"); TTest t = new TTest(); t.setUsername(name); this.testService.save(t); } @RequestMapping("tsave") public void tsave(HttpServletRequest request, HttpServletResponse response) { String name = request.getParameter("name"); TTest t = new TTest(); t.setUsername(name); int i = (Integer) this.testService.put(t); System.out.println(i); }
启动测试.
http://localhost:8080/prot/test/selectOne.do?id=1
页面上输出:
com.sd.test.model.TTest@9db6ecb
http://localhost:8080/prot/test/save.do?name=userNo1
控制台输出:
save = 1
save
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。