项目采用Maven构建,用Junit进行测试,数据库是Mysql,连接池是c3p0,未测试缓存部分

1、Maven的“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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion>
<groupId>com.mcs</groupId>
<artifactId>mybatis04</artifactId>
<version>0.0.-SNAPSHOT</version> <properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<!-- Custom properties -->
<mybatis.version>3.3.</mybatis.version>
</properties> <dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<!-- 数据库连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
</dependency> <!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency> <!-- apache commons -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</dependency> <!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.</version>
</dependency> </dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>2.0..RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<finalName>Mybatis</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<!-- Maven 跳过运行 Test 代码的配置 -->
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

2、配置文件

2.1、db.properties  

 jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.user = root
jdbc.password = root c3p0.initialPoolSize =
c3p0.maxPoolSize =

2.2、spring-core.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: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/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.mcs">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan> </beans>

2.3、spring-mybatis.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: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
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:db.properties"/> <!-- 、配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>
</bean> <!-- 、配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 加载MyBatis配置文件 -->
<property name="configLocation" value="classpath:mybatis.xml"></property>
</bean> <!-- 、配置Mapper文件自动扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mcs.dao" ></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean> <!-- 、配置事务管理器 -->
<!-- MyBatis默认使用Spring JDBC的事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 、拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="append*" 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="init" propagation="REQUIRED" />
<tx:method name="delAndInit" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="load*" propagation="SUPPORTS" read-only="true" />
<tx:method name="search*" propagation="SUPPORTS" read-only="true" />
<tx:method name="datagrid*" propagation="SUPPORTS" read-only="true" /> <tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.mcs.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config> </beans>

2.4、mybatis.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> <!-- 全局的参数配置,如开启二级缓存等 -->
<settings>
<!-- 配置延迟加载,按需加载对象属性 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings> <!-- 使用别名 -->
<typeAliases>
<!-- 为包下的所有文件设置别名,别名为类名,不分大小写 -->
<package name="com.mcs.entity"/>
</typeAliases> </configuration>

2.5、log4j.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

3、数据库实体类

 package com.mcs.entity;

 import java.io.Serializable;

 public class Department implements Serializable {

     private static final long serialVersionUID = 6706877732712610561L;

     private Integer id;

     private String name;

     private String telephone;

     private Integer managerId;

     private Integer parentId;

     public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name == null ? null : name.trim();
} public String getTelephone() {
return telephone;
} public void setTelephone(String telephone) {
this.telephone = telephone == null ? null : telephone.trim();
} public Integer getManagerId() {
return managerId;
} public void setManagerId(Integer managerId) {
this.managerId = managerId;
} public Integer getParentId() {
return parentId;
} public void setParentId(Integer parentId) {
this.parentId = parentId;
} @Override
public String toString() {
return "Department [id=" + id + ", name=" + name + ", telephone=" + telephone + ", managerId=" + managerId
+ ", parentId=" + parentId + "]";
} }

4、Mapper.xml文件与对应的接口

4.1、DepartmentMapper.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.mcs.dao.DepartmentMapper"> <resultMap id="departmentResultMap" type="Department">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="telephone" property="telephone" jdbcType="VARCHAR" />
<result column="manager_id" property="managerId" jdbcType="INTEGER" />
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
</resultMap> <sql id="Base_Column_List">
id, name, telephone, manager_id, parent_id
</sql> <select id="findById" parameterType="Integer" resultMap ="departmentResultMap">
select * from t_department where id = #{id}
</select> <select id="findAll" resultMap="departmentResultMap">
select * from t_department
</select> <select id="findDetails" parameterType="Integer" resultMap="departmentResultMap">
select * from t_department where parent_id = #{value}
</select> <insert id="add" parameterType="com.mcs.entity.Department">
<!-- 将Insert插入的数据的主键返回到User对象中,只限Mysql的自增长的Key -->
<selectKey keyProperty="id" order="AFTER" resultType="int">
SELECT LAST_INSERT_ID()
</selectKey> insert into t_department
(name, telephone, manager_id, parent_id)
values
(#{name}, #{telephone}, #{managerId}, #{parentId})
</insert> <!--
新增获取自增Key的另外一种方式
<insert id="add" keyColumn="id" keyProperty="id" useGeneratedKeys="true" parameterType="com.mcs.entity.Department">
insert into t_department
(name, telephone, manager_id, parent_id)
values
(#{name}, #{telephone}, #{managerId}, #{parentId})
</insert>
--> <update id="updateById" parameterType="com.mcs.entity.Department">
update t_department
set name = #{name},
telephone = #{telephone},
manager_id = #{managerId},
parent_id = #{parentId}
where id = #{id}
</update> <delete id="deleteById" parameterType="Integer">
delete from t_department where id = #{id}
</delete> </mapper>

4.2、DepartmentMapper.java

 package com.mcs.dao;

 import java.util.List;

 import com.mcs.entity.Department;

 public interface DepartmentMapper {

     public void add(Department department) throws Exception;

     public void updateById(Department department) throws Exception;

     public void deleteById(Integer id) throws Exception;

     public Department findById(Integer id) throws Exception;

     public List<Department> findAll() throws Exception;

     public List<Department> findDetails(Integer parentId) throws Exception;

 }

5、Service层代码

5.1、DepartmentService.java

 package com.mcs.service;

 import java.util.List;

 import com.mcs.entity.Department;

 public interface DepartmentService {
public Department add(Department department) throws Exception; public void updateById(Integer id, Department department) throws Exception; public void deleteById(Integer id) throws Exception; public Department findById(Integer id) throws Exception; public List<Department> findAll() throws Exception; public List<Department> findDetails(Integer parentId) throws Exception; }

5.2、DepartmentServiceImpl.java

 package com.mcs.service.impl;

 import java.util.ArrayList;
import java.util.List; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.mcs.dao.DepartmentMapper;
import com.mcs.entity.Department;
import com.mcs.service.DepartmentService; @Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService { @Autowired
private DepartmentMapper departmentMapper; public Department add(Department department) throws Exception {
departmentMapper.add(department);
return department;
} public void updateById(Integer id, Department department) throws Exception {
Department d = departmentMapper.findById(id);
BeanUtils.copyProperties(department, d);
departmentMapper.updateById(d);
} public void deleteById(Integer id) throws Exception {
departmentMapper.deleteById(id);
} public Department findById(Integer id) throws Exception {
return departmentMapper.findById(id);
} public List<Department> findAll() throws Exception {
List<Department> departments = new ArrayList<Department>();
departments = departmentMapper.findAll();
return departments;
} public List<Department> findDetails(Integer parentId) throws Exception {
List<Department> departments = new ArrayList<Department>();
departments = departmentMapper.findDetails(parentId);
return departments;
} }

6、测试代码TestDepartmentService.java

 package com.mcs.test;

 import java.util.List;

 import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mcs.entity.Department;
import com.mcs.service.DepartmentService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-core.xml", "classpath:spring-mybatis.xml" })
public class TestDepartmentService {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(TestDepartmentService.class); @Autowired
private DepartmentService departmentService; @Test
public void test() throws Exception { } @Test
public void testFindById() throws Exception {
Department department = departmentService.findById();
logger.debug(department);
} @Test
public void testAdd() throws Exception {
Department department = new Department();
department.setName("行政部");
department.setTelephone("021-86868686");
department.setParentId(); department = departmentService.add(department);
logger.debug(department);
} @Test
public void testUpdateById() throws Exception {
Department department = departmentService.findById(); department.setTelephone("010-66668888"); departmentService.updateById(, department);
logger.debug("部门更新成功!");
} @Test
public void testDeleteById() throws Exception {
departmentService.deleteById();
} @Test
public void testFindAll() throws Exception {
List<Department> departments = departmentService.findAll(); logger.debug(departments);
} @Test
public void testFindDetails() throws Exception {
List<Department> departments = departmentService.findDetails(); logger.debug(departments);
} }

Mybatis与Spring整合(CURD)的更多相关文章

  1. MyBatis学习(四)MyBatis和Spring整合

    MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...

  2. Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来

    转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...

  3. Mybatis+struts2+spring整合

    把student项目改造成ssm  struts2 +mybatis+spring 1,先添加spring支持:类库三个,applicationContext.xml写在webinf下四个命名空间,监 ...

  4. mybatis与spring整合(基于配置文件)

    本文主要介绍了如何将mybatis和spring整合在一起使用,本人使用的是mybatis3.05 + spring3.1.0M2 ,使用dbcp作为数据库连接池. 1.编写数据访问接口(UserDa ...

  5. mybatis与spring整合时读取properties问题的解决

    在学习mybatis与spring整合是,想从外部引用一个db.properties数据库配置文件,在配置文件中使用占位符进行引用,如下: <context:property-placehold ...

  6. Spring+SpringMVC+MyBatis深入学习及搭建(九)——MyBatis和Spring整合

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6964162.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(八)--My ...

  7. Mybatis第五篇【Mybatis与Spring整合】

    Mybatis与Spring整合 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用的是Oracle数据库来进行测试 导入jar包 aopallia ...

  8. MyBatis 与 Spring 整合

    MyBatis-Spring 项目 目前大部分的 Java 互联网项目,都是用 Spring MVC + Spring + MyBatis 搭建平台的. 使用 Spring IoC 可以有效的管理各类 ...

  9. Mybatis(六) Spring整合mybatis

    心莫浮躁~踏踏实实走,一步一个脚印,就算不学习,玩,能干嘛呢?人生就是那样,要找点有意思,打发时间的事情来做,而钻研技术,动脑动手的过程,还是比其他工作更有意思些~ so,努力啥的都是强迫自己做自以为 ...

  10. MyBatis学习(三)---MyBatis和Spring整合

    想要了解MyBatis基础的朋友可以通过传送门: MyBatis学习(一)---配置文件,Mapper接口和动态SQL http://www.cnblogs.com/ghq120/p/8322302. ...

随机推荐

  1. python Pool并行执行

    # -*- coding: utf-8 -*- import time from multiprocessing import Pool def run(fn): #fn: 函数参数是数据列表的一个元 ...

  2. yum设置代理

    echo "proxy=http://[proxy_url]:8080" >> /etc/yum.conf

  3. TIKA环境配置

    本章将指导完成设置Apache Tika在Windows和Linux的配置过程.用户管理是必要的,同时安装了Apache Tika. 系统要求 JDK Java SE 2 JDK 1.6 或以上 内存 ...

  4. 深入理解JAVA虚拟机原理之垃圾回收器机制(一)

    更多Android高级架构进阶视频学习请点击:https://space.bilibili.com/474380680 对于程序计数器.虚拟机栈.本地方法栈这三个部分而言,其生命周期与相关线程有关,随 ...

  5. Selenium3 + Python3自动化测试系列七——多窗口切换

    多窗口切换 在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口上进行操作. WebDriver提供了switch_to.window()方法,可以实现在不同的窗口之间切 ...

  6. 读书笔记---《Docker 技术入门与实践》---为镜像添加SSH服务

    之前说到可以通过attach和exec两个命令登陆容器,但是如果遇到需要远程通过ssh登陆容器的场景,就需要手动添加ssh服务. 下面介绍两种方法创建带有ssh服务的镜像,commit命令创建和通过D ...

  7. 关于虚拟机中linux系统时间的问题

    由于考试需求,我在vm上放置了考试用的linux环境,在进行操作的时候需要回调时间才能进行一些操作.但是每次重启之后,时间总是会和物理服务器的时间进行同步,让我非常的苦恼. 终于有一天我想清楚了如何表 ...

  8. 换盘符cd的用法

    如果是在本盘内切换文件夹,直接使用cd 后面跟地址即可. 如果是跨区切换地址,cd 后面就需要跟/d,斜杠d, /d就代表着跨分区切换地址. cd /d d:\ C:\ProgramData\Anac ...

  9. fedora 28 missing PROG bison

    yum install bison Missing PROG dlltool Missing PROG flex Missing PROG mt

  10. could not load the tomcat server configuration ...

    参考文档:  https://blog.csdn.net/u013381651/article/details/51567758 问题解决. 原因是你把项目里的tomcat的server项目也关闭了, ...