项目采用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. systemctl命令配置系统服务

    1.systemd的配置文件目录 systemd将daemon执行的脚本视作服务单位(unit),服务依据功能区分时,分为不同的类型(type). 常见的systemd服务类型如下表: 后缀名称    ...

  2. pefile解析PE格式

    import os,sys import pefile import pydasm import struct #print sys.argv def show_section(pe): print ...

  3. JUC源码分析-集合篇(四)CopyOnWriteArrayList

    JUC源码分析-集合篇(四)CopyOnWriteArrayList Copy-On-Write 简称 COW,是一种用于程序设计中的优化策略.其基本思路是,从一开始大家都在共享同一个内容,当某个人想 ...

  4. JQuery中内容操作函数、validation表单校验

    JQuery:内容体拼接(可以直接拼接元素节点和内容节点) JQuery实现: 方案1:A.append(B); == B.appendTo(A);A的后面拼接B 方案2: A.prepend(B); ...

  5. vmvare下centos7配置静态ip

    首先,将网络适配设置成为桥接模式 查看本机IP地址,ipconfig,记住ipv4地址和默认网关地址,等会配置的时候要用 启动Centos,进入终端模式,设置IP地址, 切换到这个目录下,cd /et ...

  6. SpringBoot Controller 中使用多个@RequestBody的正确姿势

    最近遇到Controller中需要多个@RequestBody的情况,但是发现并不支持这种写法, 这样导致 1.单个字符串等包装类型都要写一个对象才可以用@RequestBody接收: 2.多个对象需 ...

  7. python--面向对象:封装

    广义上面向对象的封装 :代码的保护,面向对象的思想本身就是一种只让自己的对象能调用自己类中的方法 狭义上的封装 ——> 面向对象的三大特性之一属性 和 方法都藏起来 不让你看见 "&q ...

  8. pandas--排序和排名

    排序 要对行或列索引进行排序,可使用sort_index方法,它将返回一个已排序的新对象: Series 1.对Series索引排序 obj=Series(range(4),index=['d','a ...

  9. 关于print()里面的sep和end参数的使用

    print('hello', 'world') #默认用空格隔开 #hello world print('hello', 'world', sep='wuli') #sep=''可以用来设置连接的字符 ...

  10. vue 单元素过渡

    demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...