Mybatis与Spring整合(CURD)
项目采用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)的更多相关文章
- MyBatis学习(四)MyBatis和Spring整合
MyBatis和Spring整合 思路 1.让spring管理SqlSessionFactory 2.让spring管理mapper对象和dao. 使用spring和mybatis整合开发mapper ...
- Mybatis与Spring整合,使用了maven管理项目,作为初学者觉得不错,转载下来
转载自:http://www.cnblogs.com/xdp-gacl/p/4271627.html 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype ...
- Mybatis+struts2+spring整合
把student项目改造成ssm struts2 +mybatis+spring 1,先添加spring支持:类库三个,applicationContext.xml写在webinf下四个命名空间,监 ...
- mybatis与spring整合(基于配置文件)
本文主要介绍了如何将mybatis和spring整合在一起使用,本人使用的是mybatis3.05 + spring3.1.0M2 ,使用dbcp作为数据库连接池. 1.编写数据访问接口(UserDa ...
- mybatis与spring整合时读取properties问题的解决
在学习mybatis与spring整合是,想从外部引用一个db.properties数据库配置文件,在配置文件中使用占位符进行引用,如下: <context:property-placehold ...
- Spring+SpringMVC+MyBatis深入学习及搭建(九)——MyBatis和Spring整合
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6964162.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(八)--My ...
- Mybatis第五篇【Mybatis与Spring整合】
Mybatis与Spring整合 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用的是Oracle数据库来进行测试 导入jar包 aopallia ...
- MyBatis 与 Spring 整合
MyBatis-Spring 项目 目前大部分的 Java 互联网项目,都是用 Spring MVC + Spring + MyBatis 搭建平台的. 使用 Spring IoC 可以有效的管理各类 ...
- Mybatis(六) Spring整合mybatis
心莫浮躁~踏踏实实走,一步一个脚印,就算不学习,玩,能干嘛呢?人生就是那样,要找点有意思,打发时间的事情来做,而钻研技术,动脑动手的过程,还是比其他工作更有意思些~ so,努力啥的都是强迫自己做自以为 ...
- MyBatis学习(三)---MyBatis和Spring整合
想要了解MyBatis基础的朋友可以通过传送门: MyBatis学习(一)---配置文件,Mapper接口和动态SQL http://www.cnblogs.com/ghq120/p/8322302. ...
随机推荐
- docker常用
1. docker 查看正在运行 2. docker 查看所有 3. docker 查看镜像 4. docker 运行使用 docker run --name 镜像名(自己起的镜像名字)-d(后台) ...
- pycharm中django同步数据库问题
一.Django数据同步过程中遇到的问题: 1.raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you hav ...
- mybatis执行test07测试类却显示test05测试类调用的sql语句出错
1.测试类 @Test public void test07() { IStudentDao studentDao = new IStudentDaoImpl(); Student student = ...
- python--接口类与抽象类
一. 继承有两种用途: """ 一:继承基类的方法,并且做出自己的改变或者扩展(代码重用) 二:声明某个子类兼容于某基类,定义一个接口类Interface,接口类中定义了 ...
- Java中在磁盘上复制文件
使用字节流实现 public static void main(String[] args) throws IOException { InputStream in = new FileInputSt ...
- 什么是URI、URL、URN、URC和Data URI?
前言 不知道大家有没有电话拨号通过'猫'上网的经历,那时测试网络是否连接,最好的方式就是打开浏览器输入: www.baidu.com 那会管这一连串字母叫' 网址 '.之后上大学(计算机专业),知道了 ...
- String.join() --Java8中String类新增方法
序言 在看别人的代码时发现一个方法String.join(),因为之前没有见过所以比较好奇. 跟踪源码发现源码很给力,居然有用法示例,以下是源码: /** * Returns a new String ...
- 多flavor导致的源码依赖问题-- Cannot choose between the following configurations of project :sample:
一.背景: 当我们在源码依赖的时候经常会导致一些问题. 我们的主工程有如下配置,它依赖了一个sample的本地工程 flavorDimensions "demo" productF ...
- python 基本输入输出
- jq-demo-tab切换
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...