项目采用Maven构建,用Junit进行测试,数据库是Mysql,连接池是c3p0,未测试缓存部分
1、Maven的“pom.xml”文件
1 <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/xsd/maven-4.0.0.xsd"> 2 <modelVersion>4.0.0</modelVersion> 3 <groupId>com.mcs</groupId> 4 <artifactId>mybatis04</artifactId> 5 <version>0.0.1-SNAPSHOT</version> 6 7 <properties> 8 <!-- Generic properties --> 9 <java.version>1.8</java.version> 10 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 11 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 12 <!-- Custom properties --> 13 <mybatis.version>3.3.0</mybatis.version> 14 </properties> 15 16 <dependencies> 17 <!-- junit --> 18 <dependency> 19 <groupId>junit</groupId> 20 <artifactId>junit</artifactId> 21 <scope>test</scope> 22 </dependency> 23 <!-- log4j --> 24 <dependency> 25 <groupId>log4j</groupId> 26 <artifactId>log4j</artifactId> 27 </dependency> 28 <!-- 数据库连接驱动 --> 29 <dependency> 30 <groupId>mysql</groupId> 31 <artifactId>mysql-connector-java</artifactId> 32 </dependency> 33 <!-- c3p0 --> 34 <dependency> 35 <groupId>com.mchange</groupId> 36 <artifactId>c3p0</artifactId> 37 </dependency> 38 39 <!-- spring --> 40 <dependency> 41 <groupId>org.springframework</groupId> 42 <artifactId>spring-core</artifactId> 43 </dependency> 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-context</artifactId> 47 </dependency> 48 <dependency> 49 <groupId>org.springframework</groupId> 50 <artifactId>spring-context-support</artifactId> 51 </dependency> 52 <dependency> 53 <groupId>org.springframework</groupId> 54 <artifactId>spring-orm</artifactId> 55 </dependency> 56 <dependency> 57 <groupId>org.springframework</groupId> 58 <artifactId>spring-webmvc</artifactId> 59 </dependency> 60 <dependency> 61 <groupId>org.springframework</groupId> 62 <artifactId>spring-tx</artifactId> 63 </dependency> 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-jdbc</artifactId> 67 </dependency> 68 <dependency> 69 <groupId>org.springframework</groupId> 70 <artifactId>spring-aspects</artifactId> 71 </dependency> 72 <dependency> 73 <groupId>org.springframework</groupId> 74 <artifactId>spring-messaging</artifactId> 75 </dependency> 76 <dependency> 77 <groupId>org.springframework</groupId> 78 <artifactId>spring-test</artifactId> 79 </dependency> 80 81 <!-- apache commons --> 82 <dependency> 83 <groupId>commons-logging</groupId> 84 <artifactId>commons-logging</artifactId> 85 </dependency> 86 87 <!-- mybatis --> 88 <dependency> 89 <groupId>org.mybatis</groupId> 90 <artifactId>mybatis</artifactId> 91 <version>${mybatis.version}</version> 92 </dependency> 93 <dependency> 94 <groupId>org.mybatis</groupId> 95 <artifactId>mybatis-spring</artifactId> 96 <version>1.2.3</version> 97 </dependency> 98 99 </dependencies> 100 101 102 <dependencyManagement> 103 <dependencies> 104 <dependency> 105 <groupId>io.spring.platform</groupId> 106 <artifactId>platform-bom</artifactId> 107 <version>2.0.0.RELEASE</version> 108 <type>pom</type> 109 <scope>import</scope> 110 </dependency> 111 </dependencies> 112 </dependencyManagement> 113 114 <build> 115 <finalName>Mybatis</finalName> 116 <plugins> 117 <plugin> 118 <groupId>org.apache.maven.plugins</groupId> 119 <artifactId>maven-surefire-plugin</artifactId> 120 <version>2.19</version> 121 <configuration> 122 <!-- Maven 跳过运行 Test 代码的配置 --> 123 <skipTests>true</skipTests> 124 </configuration> 125 </plugin> 126 </plugins> 127 </build> 128 </project>
2、配置文件
2.1、db.properties
1 jdbc.driverClass = com.mysql.jdbc.Driver 2 jdbc.jdbcUrl = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8 3 jdbc.user = root 4 jdbc.password = root 5 6 c3p0.initialPoolSize = 5 7 c3p0.maxPoolSize = 100
2.2、spring-core.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 3 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> 4 5 <!-- 配置自动扫描的包 --> 6 <context:component-scan base-package="com.mcs"> 7 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 8 <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> 9 </context:component-scan> 10 11 </beans>
2.3、spring-mybatis.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd 3 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 4 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 5 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 6 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> 7 8 <!-- 加载数据库配置文件 --> 9 <context:property-placeholder location="classpath:db.properties"/> 10 11 <!-- 1、配置数据源 --> 12 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 13 <property name="user" value="${jdbc.user}"></property> 14 <property name="password" value="${jdbc.password}"></property> 15 <property name="driverClass" value="${jdbc.driverClass}"></property> 16 <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> 17 18 <property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property> 19 <property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property> 20 </bean> 21 22 <!-- 2、配置sqlSessionFactory --> 23 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 24 <!-- 加载数据源 --> 25 <property name="dataSource" ref="dataSource"></property> 26 <!-- 加载MyBatis配置文件 --> 27 <property name="configLocation" value="classpath:mybatis.xml"></property> 28 </bean> 29 30 <!-- 3、配置Mapper文件自动扫描 --> 31 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 32 <property name="basePackage" value="com.mcs.dao" ></property> 33 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 34 </bean> 35 36 <!-- 4、配置事务管理器 --> 37 <!-- MyBatis默认使用Spring JDBC的事务管理器 --> 38 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 39 <property name="dataSource" ref="dataSource"></property> 40 </bean> 41 42 <!-- 5、拦截器方式配置事物 --> 43 <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> 44 <tx:attributes> 45 <tx:method name="add*" propagation="REQUIRED" /> 46 <tx:method name="append*" propagation="REQUIRED" /> 47 <tx:method name="save*" propagation="REQUIRED" /> 48 <tx:method name="update*" propagation="REQUIRED" /> 49 <tx:method name="modify*" propagation="REQUIRED" /> 50 <tx:method name="edit*" propagation="REQUIRED" /> 51 <tx:method name="delete*" propagation="REQUIRED" /> 52 <tx:method name="remove*" propagation="REQUIRED" /> 53 <tx:method name="init" propagation="REQUIRED" /> 54 <tx:method name="delAndInit" propagation="REQUIRED" /> 55 56 <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> 57 <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> 58 <tx:method name="load*" propagation="SUPPORTS" read-only="true" /> 59 <tx:method name="search*" propagation="SUPPORTS" read-only="true" /> 60 <tx:method name="datagrid*" propagation="SUPPORTS" read-only="true" /> 61 62 <tx:method name="*" propagation="REQUIRED" /> 63 </tx:attributes> 64 </tx:advice> 65 <aop:config> 66 <aop:pointcut id="transactionPointcut" expression="execution(* com.mcs.service..*Impl.*(..))" /> 67 <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> 68 </aop:config> 69 70 </beans>
2.4、mybatis.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 7 <!-- 全局的参数配置,如开启二级缓存等 --> 8 <settings> 9 <!-- 配置延迟加载,按需加载对象属性 --> 10 <setting name="lazyLoadingEnabled" value="true"/> 11 <setting name="aggressiveLazyLoading" value="false"/> 12 </settings> 13 14 <!-- 使用别名 --> 15 <typeAliases> 16 <!-- 为包下的所有文件设置别名,别名为类名,不分大小写 --> 17 <package name="com.mcs.entity"/> 18 </typeAliases> 19 20 </configuration>
2.5、log4j.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> 3 <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> 4 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> 5 <layout class="org.apache.log4j.PatternLayout"> 6 <param name="ConversionPattern" 7 value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) " /> 8 </layout> 9 </appender> 10 <logger name="java.sql"> 11 <level value="debug" /> 12 </logger> 13 <logger name="org.apache.ibatis"> 14 <level value="debug" /> 15 </logger> 16 <root> 17 <level value="debug" /> 18 <appender-ref ref="STDOUT" /> 19 </root> 20 </log4j:configuration>
3、数据库实体类
1 package com.mcs.entity; 2 3 import java.io.Serializable; 4 5 public class Department implements Serializable { 6 7 private static final long serialVersionUID = 6706877732712610561L; 8 9 private Integer id; 10 11 private String name; 12 13 private String telephone; 14 15 private Integer managerId; 16 17 private Integer parentId; 18 19 public Integer getId() { 20 return id; 21 } 22 23 public void setId(Integer id) { 24 this.id = id; 25 } 26 27 public String getName() { 28 return name; 29 } 30 31 public void setName(String name) { 32 this.name = name == null ? null : name.trim(); 33 } 34 35 public String getTelephone() { 36 return telephone; 37 } 38 39 public void setTelephone(String telephone) { 40 this.telephone = telephone == null ? null : telephone.trim(); 41 } 42 43 public Integer getManagerId() { 44 return managerId; 45 } 46 47 public void setManagerId(Integer managerId) { 48 this.managerId = managerId; 49 } 50 51 public Integer getParentId() { 52 return parentId; 53 } 54 55 public void setParentId(Integer parentId) { 56 this.parentId = parentId; 57 } 58 59 @Override 60 public String toString() { 61 return "Department [id=" + id + ", name=" + name + ", telephone=" + telephone + ", managerId=" + managerId 62 + ", parentId=" + parentId + "]"; 63 } 64 65 66 }
4、Mapper.xml文件与对应的接口
4.1、DepartmentMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.mcs.dao.DepartmentMapper"> 4 5 <resultMap id="departmentResultMap" type="Department"> 6 <id column="id" property="id" jdbcType="INTEGER" /> 7 <result column="name" property="name" jdbcType="VARCHAR" /> 8 <result column="telephone" property="telephone" jdbcType="VARCHAR" /> 9 <result column="manager_id" property="managerId" jdbcType="INTEGER" /> 10 <result column="parent_id" property="parentId" jdbcType="INTEGER" /> 11 </resultMap> 12 13 <sql id="Base_Column_List"> 14 id, name, telephone, manager_id, parent_id 15 </sql> 16 17 <select id="findById" parameterType="Integer" resultMap ="departmentResultMap"> 18 select * from t_department where id = #{id} 19 </select> 20 21 <select id="findAll" resultMap="departmentResultMap"> 22 select * from t_department 23 </select> 24 25 <select id="findDetails" parameterType="Integer" resultMap="departmentResultMap"> 26 select * from t_department where parent_id = #{value} 27 </select> 28 29 30 <insert id="add" parameterType="com.mcs.entity.Department"> 31 <!-- 将Insert插入的数据的主键返回到User对象中,只限Mysql的自增长的Key --> 32 <selectKey keyProperty="id" order="AFTER" resultType="int"> 33 SELECT LAST_INSERT_ID() 34 </selectKey> 35 36 insert into t_department 37 (name, telephone, manager_id, parent_id) 38 values 39 (#{name}, #{telephone}, #{managerId}, #{parentId}) 40 </insert> 41 42 <!-- 43 新增获取自增Key的另外一种方式 44 <insert id="add" keyColumn="id" keyProperty="id" useGeneratedKeys="true" parameterType="com.mcs.entity.Department"> 45 insert into t_department 46 (name, telephone, manager_id, parent_id) 47 values 48 (#{name}, #{telephone}, #{managerId}, #{parentId}) 49 </insert> 50 --> 51 52 <update id="updateById" parameterType="com.mcs.entity.Department"> 53 update t_department 54 set name = #{name}, 55 telephone = #{telephone}, 56 manager_id = #{managerId}, 57 parent_id = #{parentId} 58 where id = #{id} 59 </update> 60 61 <delete id="deleteById" parameterType="Integer"> 62 delete from t_department where id = #{id} 63 </delete> 64 65 </mapper>
4.2、DepartmentMapper.java
1 package com.mcs.dao; 2 3 import java.util.List; 4 5 import com.mcs.entity.Department; 6 7 public interface DepartmentMapper { 8 9 public void add(Department department) throws Exception; 10 11 public void updateById(Department department) throws Exception; 12 13 public void deleteById(Integer id) throws Exception; 14 15 public Department findById(Integer id) throws Exception; 16 17 public List<Department> findAll() throws Exception; 18 19 public List<Department> findDetails(Integer parentId) throws Exception; 20 21 22 }
5、Service层代码
5.1、DepartmentService.java
1 package com.mcs.service; 2 3 import java.util.List; 4 5 import com.mcs.entity.Department; 6 7 public interface DepartmentService { 8 public Department add(Department department) throws Exception; 9 10 public void updateById(Integer id, Department department) throws Exception; 11 12 public void deleteById(Integer id) throws Exception; 13 14 public Department findById(Integer id) throws Exception; 15 16 public List<Department> findAll() throws Exception; 17 18 public List<Department> findDetails(Integer parentId) throws Exception; 19 20 }
5.2、DepartmentServiceImpl.java
1 package com.mcs.service.impl; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.springframework.beans.BeanUtils; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Service; 9 10 import com.mcs.dao.DepartmentMapper; 11 import com.mcs.entity.Department; 12 import com.mcs.service.DepartmentService; 13 14 @Service("departmentService") 15 public class DepartmentServiceImpl implements DepartmentService { 16 17 @Autowired 18 private DepartmentMapper departmentMapper; 19 20 public Department add(Department department) throws Exception { 21 departmentMapper.add(department); 22 return department; 23 } 24 25 public void updateById(Integer id, Department department) throws Exception { 26 Department d = departmentMapper.findById(id); 27 BeanUtils.copyProperties(department, d); 28 departmentMapper.updateById(d); 29 } 30 31 public void deleteById(Integer id) throws Exception { 32 departmentMapper.deleteById(id); 33 } 34 35 public Department findById(Integer id) throws Exception { 36 return departmentMapper.findById(id); 37 } 38 39 public List<Department> findAll() throws Exception { 40 List<Department> departments = new ArrayList<Department>(); 41 departments = departmentMapper.findAll(); 42 return departments; 43 } 44 45 public List<Department> findDetails(Integer parentId) throws Exception { 46 List<Department> departments = new ArrayList<Department>(); 47 departments = departmentMapper.findDetails(parentId); 48 return departments; 49 } 50 51 52 }
6、测试代码TestDepartmentService.java
1 package com.mcs.test; 2 3 import java.util.List; 4 5 import org.apache.log4j.Logger; 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.test.context.ContextConfiguration; 10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 11 12 import com.mcs.entity.Department; 13 import com.mcs.service.DepartmentService; 14 15 @RunWith(SpringJUnit4ClassRunner.class) 16 @ContextConfiguration(locations = { "classpath:spring-core.xml", "classpath:spring-mybatis.xml" }) 17 public class TestDepartmentService { 18 /** 19 * Logger for this class 20 */ 21 private static final Logger logger = Logger.getLogger(TestDepartmentService.class); 22 23 @Autowired 24 private DepartmentService departmentService; 25 26 @Test 27 public void test() throws Exception { 28 29 } 30 31 @Test 32 public void testFindById() throws Exception { 33 Department department = departmentService.findById(3); 34 logger.debug(department); 35 } 36 37 @Test 38 public void testAdd() throws Exception { 39 Department department = new Department(); 40 department.setName("行政部"); 41 department.setTelephone("021-86868686"); 42 department.setParentId(2); 43 44 department = departmentService.add(department); 45 logger.debug(department); 46 } 47 48 @Test 49 public void testUpdateById() throws Exception { 50 Department department = departmentService.findById(14); 51 52 department.setTelephone("010-66668888"); 53 54 departmentService.updateById(14, department); 55 logger.debug("部门更新成功!"); 56 } 57 58 @Test 59 public void testDeleteById() throws Exception { 60 departmentService.deleteById(15); 61 } 62 63 @Test 64 public void testFindAll() throws Exception { 65 List<Department> departments = departmentService.findAll(); 66 67 logger.debug(departments); 68 } 69 70 @Test 71 public void testFindDetails() throws Exception { 72 List<Department> departments = departmentService.findDetails(1); 73 74 logger.debug(departments); 75 } 76 77 78 }