新建項目,規劃好各層的包,並導入所需jar包
applicationContext.xml myBatis-config.xml spring-mvc.xml log4j.properties
1.1 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> <!-- 通過別名簡化對類的使用 <typeAliases> <typeAlias type="cn.itcast.scm.entity.Dept" alias="Dept" /> </typeAliases> <mappers> <mapper resource="cn/itcast/scm/entity/DeptMapper.xml" /> </mappers> --> </configuration>
1.2 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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <!-- 配置數據源,記得去掉myBatis-config.xml的數據源相關配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" /> <property name="user" value="root" /> <property name="password" value="root" /> </bean> <!-- 配置session工廠 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:myBatis-config.xml" /> </bean> <!-- 配置事務管理器,管理數據源事務處理--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事務通知 --> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <!-- 默認只處理運行時異常,可加rollback-for="Exception/Throwable"等處理所有異常或包括錯誤 --> <tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <!-- 配置切面織入的范圍,後邊要把事務邊界定在service層 --> <aop:config> <aop:advisor advice-ref="advice" pointcut="execution(* cn.itcast.scm.dao.impl.*.*(..))"/> </aop:config> <!-- 配置SessionTemplate,已封裝了繁瑣的數據操作--> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <context:component-scan base-package="*"/> </beans>
1.3 編寫實體及sql映射文件
1.3.1 sql 腳本,插入測試數據
drop database if exists test; create database test CHARACTER SET UTF8; use mybatis; create table dept( dept_id int primary key auto_increment, dept_name varchar(50), dept_address varchar(50) ); insert into dept(dept_name,dept_address) values('研發部一部','廣州'); insert into dept(dept_name,dept_address) values('研發部二部','廣州'); insert into dept(dept_name,dept_address) values('研發部三部','深圳');
select * from dept;
1.3.2 編寫實體類
package cn.itcast.scm.entity; import java.io.Serializable; public class Dept implements Serializable { /** * */ private static final long serialVersionUID = 807184188547688524L; private Integer deptId; private String deptName; private String deptAddress; public Integer getDeptId() { return deptId; } public void setDeptId(Integer deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getDeptAddress() { return deptAddress; } public void setDeptAddress(String deptAddress) { this.deptAddress = deptAddress; } @Override public String toString() { return "Dept [deptId=" + deptId + ", deptName=" + deptName + ", deptAddress=" + deptAddress + "]"; } }
1.3.3 SQL映射文件
<?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.itcast.scm.entity.DeptMapper"> <resultMap type="Dept" id="deptResultMap"> <id property="deptId" column="dept_id" /> <result property="deptName" column="dept_name" /> <result property="deptAddress" column="dept_address" /> </resultMap> <!-- id和命名空間用來定位SQL語句,parameterType表示參數的類型,resultMap返回類型 --> <select id="selectDept" parameterType="Integer" resultMap="deptResultMap"> <!--參數的寫法#{deptID} --> select dept_id,dept_name,dept_address from dept where dept_id=#{deptID} </select> <insert id="insertDept" parameterType="Dept"> insert into dept(dept_name,dept_address) values(#{deptName},#{deptAddress}); </insert> </mapper>
1.3.4 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> <!-- 通過別名簡化對類的使用 --> <typeAliases> <typeAlias type="cn.itcast.scm.entity.Dept" alias="Dept" /> </typeAliases> <mappers> <mapper resource="cn/itcast/scm/entity/DeptMapper.xml" /> </mappers> </configuration>
package cn.itcast.scm.dao.impl; import javax.annotation.Resource; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; import cn.itcast.scm.entity.Dept; @Repository("deptDao") public class DeptDaoImpl { @Resource private SqlSessionTemplate sqlSessionTemplate; /** * 根據部門編號查詢部門信息 * * @param deptId * 部門編號 * @return 部門信息 */ public Dept selectDept(Integer deptId) { Dept dept = sqlSessionTemplate.selectOne( "cn.itcast.scm.entity.DeptMapper.selectDept", deptId); return dept; } /** * 添加部門信息 * * @param dept * 部門信息 * @return 添加成功的記錄數 */ public int insertDept(Dept dept) { System.out.println("------dao.dept:" + dept); return sqlSessionTemplate.insert( "cn.itcast.scm.entity.DeptMapper.insertDept", dept); } }
3.測試spring與mybatis整合
package cn.itcast.scm.test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.scm.dao.impl.DeptDaoImpl; import cn.itcast.scm.entity.Dept; public class TestDeptDao { //@Resource //這裡沒法使用,後繼版本有其它方式可以注入 static private DeptDaoImpl deptDao; @BeforeClass public static void setUpBeforeClass() throws Exception { ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml"); deptDao=(DeptDaoImpl) context.getBean("deptDao"); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Test public void testSelectDept() { System.out.println(deptDao.selectDept(1)); } @Test public void testInsertDept() { Dept dept=new Dept(); //dept.setDeptId(117); dept.setDeptName("name118"); dept.setDeptAddress("address118"); System.out.println("受影響行數:"+deptDao.insertDept(dept)); } }
修改web.xml文件,加入springmvc相關信息,編寫 控制器類及相關jsp 文件
4.1 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:context="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-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="*"/> </beans>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
package cn.itcast.scm.test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.scm.dao.impl.DeptDaoImpl; import cn.itcast.scm.entity.Dept; public class TestDeptDao { //@Resource //這裡沒法使用,後繼版本有其它方式可以注入 static private DeptDaoImpl deptDao; @BeforeClass public static void setUpBeforeClass() throws Exception { ApplicationContext context =new ClassPathXmlApplicationContext("applicationContext.xml"); deptDao=(DeptDaoImpl) context.getBean("deptDao"); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Test public void testSelectDept() { System.out.println(deptDao.selectDept(1)); } @Test public void testInsertDept() { Dept dept=new Dept(); //dept.setDeptId(117); dept.setDeptName("name118"); dept.setDeptAddress("address118"); System.out.println("受影響行數:"+deptDao.insertDept(dept)); } }
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> </head> <body>this is main jsp </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> </head> <body> <form action="dept/insert.action" method="post"> 名稱:<input type="text" name="deptName"><br> 地址:<input type="text" name="deptAddress"><br> <input type="submit" value="ok"> </form> </body> </html>