mybatis+spring+springmvc
由于是个小白,所以此下写的一切内容可能有错,请多多指教了。
---------------------------------------------------
在下面我将写:
1.mybatis整合spring
1)需要实现类
2)不需要实现类
3)接口扫描
2.mybatis整合spring 加入spring事务管理
3.mybatis整合spring整合springmvc
1.mybatis+spring
1)方法1:需要实现类
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>web</groupId> <artifactId>web</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>web Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- 设置项目编码编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本号 --> <spring.version>4.3.5.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.1</mybatis.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- java ee --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 实现slf4j接口并整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.2</version> </dependency> <!-- JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.7</version> </dependency> <!-- 数据库 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> <scope>runtime</scope> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>testweb</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <!-- 设置JDK版本 --> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
一开始写的mysql-connector-java的版本过低,所以一直出现了如下错误,改成8.0.11的版本就好了
java.sql.SQLException: Unknown system variable 'query_cache_size'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:545)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115)
at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1983)
at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1936)
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1422)
at com.mysql.cj.jdbc.ConnectionImpl.loadServerVariables(ConnectionImpl.java:2831)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:2381)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1739)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>runtime</scope>
</dependency>
empdao.java
package com.wxy.dao; import com.wxy.domain.Emp; public interface empdao { public void saveEmp(Emp e); }
empimpl.java
package com.wxy.domain; import com.wxy.dao.empdao; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.support.SqlSessionDaoSupport; public class empimpl extends SqlSessionDaoSupport implements empdao{ public void saveEmp(Emp e){ SqlSession sqlSession=this.getSqlSession(); sqlSession.insert("saveEmp",e); //去EmpMapper.xml里配置 } }
EmpMapper.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用于绑定dao接口的,即面向接口编程,需要是唯一的,我这里写的是全限定类名--> <mapper namespace="com.wxy.dao.empdao"> <!--savaEmp对应接口的方法 这里我实现的是一个插入功能 parameterType插入数据的类型--> <insert id="saveEmp" parameterType="com.wxy.domain.Emp"> INSERT into emp (empid, first_name, salary ) values ( #{empid}, #{first_name}, #{salary} ); </insert> </mapper>
Emp.java
package com.wxy.domain; public class Emp { private Integer empid; private String first_name; private Integer salary; public void setEmpid(Integer empid) { this.empid = empid; } public void setFirst_name(String first_name) { this.first_name = first_name; } public void setSalary(Integer salary) { this.salary = salary; } public Integer getEmpid() { return empid; } public String getFirst_name() { return first_name; } public Integer getSalary() { return salary; } @Override public String toString() { return "user{" + "empid=" + empid + ", first_name=" + first_name + ", salary=" + salary + "}\n"; } }
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8& jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.user=root jdbc.password=******
applicationContext.xml
这里需要注意
1.ref后面是引用数据类型(对象), value后面是基本数据类型 ref="dataSource"就是引dataSource的bean
2.classpath的路径不要写错了
<context:property-placeholder location="./jdbc.properties"/> jdbc.properties文件相对于applicationContext.xml的路径
<property name="mapperLocations" value="classpath:./mapper/EmpMapper.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:facelets="http://java.sun.com/jsf/facelets" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--读取jdbc.properties--> <context:property-placeholder location="./jdbc.properties"/> <!--创建datasource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--创建sqlsessionfactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--关联连接池--> <property name="dataSource" ref="dataSource"/> <!--加载SQL映射文件--> <property name="mapperLocations" value="classpath:./mapper/EmpMapper.xml"/> </bean> <!--创建empimpl对象,注入sqlsessionfactory--> <bean id="empmapper" class="com.wxy.domain.empimpl"> <!--关联sqlsessionfactory--> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
mybatisSpring.java
测试类
import com.wxy.domain.Emp; import com.wxy.dao.empdao; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class mybatisSpring { @Test public void test() { //加载spring配置 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); //获取对象 empdao ed=(empdao)ac.getBean("empmapper"); //拿到接口后,调用方法 Emp emp=new Emp(); emp.setEmpid(18); emp.setFirst_name("xddx"); emp.setSalary(12345); ed.saveEmp(emp); } }
log4j.properties
#日志输出级别 log4j.rootLogger=debug,stdout,D,E #设置stdout的日志输出控制台 log4j.appender.stdout=org.apache.log4j.ConsoleAppender #输出日志到控制台的方式,默认为System.out log4j.appender.stdout.Target = System.out #设置使用灵活布局 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout #灵活定义输出格式 log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%c (%rms)] - %m%n #每天产生一个日志文件 log4j.appender.D=org.apache.log4j.DailyRollingFileAppender #设置的输出日志 log4j.appender.D.File=E:/Workspaces/IDEA15/demo/src/main/webapp/WEB-INF/logs/all/log.txt #设置的日志最大限制 log4j.appender.D.MaxFileSize=6000KB #最多只保存20个备份文件 log4j.appender.D.MaxBackupIndex=20 #输出INFO级别以上的日志 og4j.appender.D.Threshold=debug log4j.appender.D.Append = true log4j.appender.D.ImmediateFlush = true #log4j.appender.D.DatePattern ='.'yyyy-MM-dd #设置使用灵活布局 log4j.appender.D.layout=org.apache.log4j.PatternLayout #灵活定义输出格式 log4j.appender.D.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%l (%rms)] - %m%n log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =E:/Workspaces/IDEA15/demo/src/main/webapp/WEB-INF/logs/error/error.txt log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR #log4j.appender.E.DatePattern = '_'yyyyMMdd'.log' log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} -[%p] method:[%l (%rms)] - %m%n
经测试,成功向数据库插入了数据。
2)方法2:不需要实现类
删除empimpl.java实现类
修改applicationContext.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:facelets="http://java.sun.com/jsf/facelets" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--读取jdbc.properties--> <context:property-placeholder location="./jdbc.properties"/> <!--创建datasource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--创建sqlsessionfactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--关联连接池--> <property name="dataSource" ref="dataSource"/> <!--加载SQL映射文件--> <property name="mapperLocations" value="classpath:./mapper/EmpMapper.xml"/> </bean> <!--配置mapper接口--> <bean id="empmapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--关联mapper接口--> <property name="mapperInterface" value="com.wxy.dao.empdao"/> <!--关联sqlSessionFactory--> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
<bean id="empmapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
在applicationContext.xml中配置mapper接口的ID名需要与测试类中getBean传入的参数一样
empdao ed=(empdao)ac.getBean("empmapper");
经测试,成功。
3)Spring-mapper接口扫描
如果项目中有非常多的接口,那么按照上面的方法就要配置非常多的bean,为了简化我们可以用接口扫描的方法。
同方法2),删除实现类
修改applicationContext.xml
如果使用mapper接口包扫描,那么每个mapper接口在spring容器中的ID名称为类名:empdao->empdao 如果接口名称的首字母为大写,在spring容器中的ID名称的首字母要改成小写
不然会报错的
EmpMapper->empMapper
<?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:facelets="http://java.sun.com/jsf/facelets" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--读取jdbc.properties--> <context:property-placeholder location="./jdbc.properties"/> <!--创建datasource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--创建sqlsessionfactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--关联连接池--> <property name="dataSource" ref="dataSource"/> <!--加载SQL映射文件--> <property name="mapperLocations" value="classpath:./mapper/empMapper.xml"/> </bean> <!--mapper接口的扫描--> <bean id="empMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--配置mapper接口所在包路径 注意!!是包的路径!!!不是接口的路径!!!--> <property name="basePackage" value="com.wxy.dao"/> </bean> </beans>
经测试,成功。
2.mybatis整合spring-加入事务管理
在上面写的3种方法中,事务都是自动提交。如果在类中出现异常,不开启事务管理则,没有办法回滚,数据还是会留在数据库里。
那么如何加入spring的事务管理呢?
saveempdao.java
创建一个接口
package com.wxy.dao; import com.wxy.domain.Emp; public interface saveempdao { public void save(Emp e); }
empimpl.java
创建接口的实现类
在没有开启事务管理的情况下,测试类中有误,会抛出异常,但是数据还是会存入数据库。开启事务管理后,则会回滚。
@Service注解的使用:
在applicationContext.xml中加入<context:component-scan base-package="com.wxy"/>
将自动扫描路径下面的包,如果一个类中有@Service注解,将自动注册到Spring容器,相当于定义某个类为一个bean,不需要再在applicationContext.xml文件定义bean了。
@Resource注解的使用:
默认按byname注入
package com.wxy.domain; import com.wxy.dao.saveempdao; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.transaction.Transactional; @Service("emp")//对应mybatisSpring.java中的saveempdao ed=(saveempdao)ac.getBean("emp"); @Transactional//注解 public class empimpl implements saveempdao { //注入mapper对象 @Resource private saveempdao e; public void save(Emp emp) { //模拟异常 int i=100/0; //在业务方法添加注解后,异常照样抛出。但是插入数据没有回滚,代表方法已被事务控制。 e.save(emp); } }
applicationContext.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--读取jdbc.properties--> <context:property-placeholder location="./jdbc.properties"/> <!--创建datasource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--创建sqlsessionfactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--关联连接池--> <property name="dataSource" ref="dataSource"/> <!--加载SQL映射文件--> <property name="mapperLocations" value="classpath:./mapper/empMapper.xml"/> </bean> <!--mapper接口的扫描--> <bean id="empMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--配置mapper接口所在包路径--> <property name="basePackage" value="com.wxy.dao"/> </bean> <!--开启spring的IOC注解扫描--> <context:component-scan base-package="com.wxy"/> <!--开启spring事务和启用spring事务注解后,事务得到管理--> <!--开启spring的事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--启用spring事务注解--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
通配符的匹配很全面, 但无法找到元素 'tx:annotation-driven' 的声明
出现上述错误,可能是此XML的头部文件出现了一些错误,可能是没有引入
xmlns:tx="http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
注意上下要对应。
Emp.java,mybatisSpring.java,empMapper.xml,jdbc.properties,log4j.properties 同 方法1中的
经测试,成功。
3.mybatis整合spring整合springmvc
1.maven中导入需要的包(spring与springmvc包的版本需要一致)
2.配置web.xml
3.配置spring-mvc.xml
4.编写Controller
5.编写页面
我做了两个功能-增加信息和查询信息
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--配置springMVC编码过滤器--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!--设置一个初始参数--> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--启动springmvc--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--参数:读取spring-mvc.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!--启动spring--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--修改路径--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:contenxt="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/p http://www.springframework.org/schema/p/spring-p.xsd "> <!--扫描Controller所在的包--> <contenxt:component-scan base-package="com.wxy.controller"/> <!--注解驱动--> <mvc:annotation-driven> </mvc:annotation-driven> <!--视图解析器:简化Controller类编写的视图路径--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"> </bean> </beans>
empMapper.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="com.wxy.dao.saveempdao"> <!--id对应接口的方法 这里我实现的是一个插入功能 parameterType插入数据的类型--> <insert id="save" parameterType="com.wxy.domain.Emp"> INSERT into emp (empid, first_name, salary ) values ( #{empid}, #{first_name}, #{salary} ); </insert> </mapper>
showMapper.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="com.wxy.dao.showempdao"> <!-- parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中。 resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。如果有多条数据,则分别进行映射,并把对象放到容器List中 --> <select id="findAll" resultType="com.wxy.domain.Emp"> select empid, first_name, salary from emp; </select> </mapper>
application.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--读取jdbc.properties--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--创建datasource--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClass}"/> <property name="username" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--创建sqlsessionfactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--关联连接池--> <property name="dataSource" ref="dataSource"/> <!--加载SQL映射文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--mapper接口的扫描--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--配置mapper接口所在包路径--> <property name="basePackage" value="com.wxy.dao"/> </bean> <!--开启spring的IOC注解扫描--> <context:component-scan base-package="com.wxy"/> <!--开启spring事务和启用spring事务注解后,事务得到管理--> <!--开启spring的事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--启用spring事务注解--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
empimpl.java
import javax.transaction.Transactional; @Service("emp")//对应saveempdao ed=(saveempdao)ac.getBean("emp"); @Transactional//注解 public class empimpl implements saveempdao { //注入mapper对象 @Resource(name = "saveempdao") private saveempdao e; public void save(Emp emp) { e.save(emp); //模拟异常 //int i=100/0; //在业务方法添加注解后,异常照样抛出。但是插入数据没有回滚,代表方法已被事务控制。 //e.save(emp); } }
showempimpl.java
package com.wxy.domain; import com.wxy.dao.showempdao; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.transaction.Transactional; import java.util.List; @Service("show") @Transactional public class showempimpl implements showempdao { //注入接口 @Resource(name = "showempdao") private showempdao sed; public List<Emp> findAll() { return sed.findAll(); } }
succ.xml
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>查看职员信息</title> </head> <body> save successfully!<br/> <form action="${pageContext.request.contextPath}/show/list.action" method="post"/> <input type="submit" value="查看所有职员信息"> </body> </html>
t.jsp
<%-- Created by IntelliJ IDEA. User: mac Date: 2019/11/21 Time: 下午5:30 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>录入页面</title> <style type="text/css"> *{ margin: 0; padding: 0; } #head{ background-color:#66CCCC ; text-align: center; position: relative; margin-right: 220px; margin-left: 220px; } #h2{ background-color: palegoldenrod; height: 18px; margin-left: 220px; margin-right: 220px; font-size: 12px; } #h3{ background-color: beige; margin-left: 220px; margin-right: 220px; height: 300px; } .logD{ color: yellowgreen; } .logC{ margin-right: 100px; left: 48%; position: absolute; color: yellow; border: 3px orange double; background-color: pink; } .h4{ height: 18px; background-color: gainsboro; font-size: 12px; } .footer{ font-size: 12px; } </style> </head> <form action="${pageContext.request.contextPath}/emp/save.action" method="post"/> <body> <div class="header" id="head"> <div class="title"> 职员信息系统 </div> </div> <div id="h2">Copyright © com.wxy All Right Reserved.</div> <div id="h3"> <br> <div class="logD"> <div class="logD1" style="color: yellowgreen" >员工ID: <input type="text" placeholder="输入职员编号" name="empid" value="${e.empid}"/><br/> </div> <br/> <div class="logD2"> 员工姓名: <input type="text" placeholder="输入职员姓名" name="first_name" value="${e.first_name}"/><br/> </div> <br/> <div class="logD3"> 员工薪水: <input type="text" placeholder="输入职员薪水" name="salary" value="${e.salary}"/><br/> </div> <br/> <div class="logC"> <input type="submit" value="保存" /> </div> </div> <br/><br/> <div class="h4">联系方式</div> <br> <div class="footer" id="foot"> <div class="copyright"> <p>联系电话☎️:123456789</p> </div> <div class="copyright"> 联系邮箱📮:123456789@qq.com </div> <div class="copyright"> <span> 联系地址👀:Shanghai Institute of Technology </span> </div> </div> </div> </body> </html>
logging.properties(启动tomcat可以输出tomcat异常日志)
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
############################################################
Handler specific properties.
Describes specific configuration info for Handlers.
############################################################
org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ../logs
org.apache.juli.FileHandler.prefix = error-debug.
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
jdbc.properties和log4j.properties同上方法1
测试结果:
搞了几天,出了好多bug,终于做出来了,嘿嘿!!!