两周前学习mybatis框架,参考了网上多位大神的博客,但因为各种原因(不解释)总是没法成功搭建环境并运行项目。周末花了点时间阅读了文档并整理之前琐碎的内容,解决掉之前遇到的问题。现将整合环境的关键步骤整理成学习手记一篇。

  文章只提取了整合环境的主体过程,没有太深入的解析其中内容,若想深入学习mybaits,请自行阅读文档、源码,或参看网上其他大神的博客,本人菜鸟一只,只是做做学习笔记(ps:吃货请直接拖到底部)。

1、导入spring核心包、spring测试包、mybatis核心包、mysql驱动包、druid数据库连接池以及mybatis-spring包(用于整合mybatis和spring):

  在pom.xml文件中添加依赖,不详述。

2、数据库建表(新建了一张练习用的简单表格):

建表sql如下:

  CREATE TABLE `user` (
    `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
    `name` varchar(128) DEFAULT NULL COMMENT '姓名',
    `age` int(11) DEFAULT NULL COMMENT '年龄',
   PRIMARY KEY (`id`)
  ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

  

3、创建user表对应的实体类:

package xlkyt.mybatis.model;

/**
* Created by Administrator on 2016/5/6.
*/
public class User {
private int id;
private String name;
private int age; public User() {
} public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

4、创建实体类对应的dao:

package xlkyt.mybatis.dao;

import xlkyt.mybatis.model.User;

/**
* Created by Administrator on 2016/5/15.
*/
public interface UserMapper { /**
*
* @param id
* @return
*/
User getUserById(int id); /**
*
* @param user
*/
void addUser(User user);
}

5、创建dao对应的mapper.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="xlkyt.mybatis.dao.UserMapper">
<select id="getUserById" parameterType="int" resultType="User" >
SELECT * FROM USER WHERE ID = #{id}
</select> <insert id="addUser" parameterType="User" >
INSERT INTO USER(name, age) VALUES (#{name}, #{age})
</insert>
</mapper>

6、编写spring配置文件:

  文件路径:src/main/resources/spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--引入mybatis配置文件-->
<import resource="classpath:spring-mybatis.xml" /> <!--自动扫描注入-->
<context:component-scan base-package="xlkyt.mybatis.service" /> <!--引入db.properties文件-->
<context:property-placeholder location="classpath:db.properties" />
</beans>

7、编写spring-mybatis配置文件:

  文件路径:src/main/resources/spring-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean> <!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<!--引用数据源-->
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:xlkyt/mybatis/mapping/*.xml" />
<!--指定实体类包,自动将包内实体的简单类名映射为别名-->
<property name="typeAliasesPackage" value="xlkyt.mybatis.model" />
</bean> <!--扫描mapping文件对应dao文件所在的包-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name="basePackage" value="xlkyt.mybatis.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean> <!--配置事务管理-->
</beans>

8、修改maven的pom文件配置(解决idea下,maven项目中src源代码里的xml等资源文件无法编译进classes文件夹的问题):

  ps:在idea的maven项目中,默认源代码目录下的xml等资源文件并不会在编译的时候一起打包进classes文件夹,而是直接舍弃掉。如果使用的是eclipse,eclipse的src目录下的xml等资源文件在编译的时候会自动打包进输出到classes文件夹。hibernate、mybatis和spring有时会将配置文件放置在src目录下,编译后要一起打包进classes文件夹,所以存在着需要将xml等资源文件放置在源代码目录下的需求。

  解决方式:在pom文件中找到<build>节点,添加下列代码:

<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>

9、编写service:

package xlkyt.mybatis.service.impl;

import xlkyt.mybatis.dao.UserMapper;
import xlkyt.mybatis.model.User;
import xlkyt.mybatis.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; /**
* Created by Administrator on 2016/5/15.
*/ @Service("userService")
public class UserServiceImpl implements IUserService { private UserMapper userMapper; @Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
} public User getUserById(int id) {
return userMapper.getUserById(id);
} public void addUser(User user) {
userMapper.addUser(user);
}
}

10、单元测试:

package com.mybatis;

import xlkyt.mybatis.model.User;
import xlkyt.mybatis.service.IUserService;
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; /**
* Created by Administrator on 2016/5/6.
*/ @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class TestMyBatis {
private IUserService userService; @Autowired
public void setUserService(IUserService userService) {
this.userService = userService;
} @Test
public void testGetUserById() {
User user = userService.getUserById(3);
System.out.println(user);
} @Test
public void testAddUser() {
userService.addUser(new User(1, "allen", 18));
}
}

11、测试通过,至此框架整合成功,接下来该干啥干啥。

歪个楼系列:

  木屋烧烤有道菜叫香辣烤羊蹄,吃过一次至今念念不忘,第二次回去的时候已经下架,不知道何时能再吃一次,强势推荐一下。夏夜里三两好友、满天繁星,天台烧烤加冰啤,向来绝配,不喝酒的童鞋可以搭配店里的酸梅汁,一样绝配~

  未经作者同意,贴个链接:http://s.dianping.com/topic/6343385  不谢。

  记得去年还是只菜鸟中的菜鸟,和直系boss一起被同事坑了一道背了黑锅,下午一起闷闷不乐的去南山听讲座,没记错的话是深圳百公里徒步那一天(那天事真多,不要问我为什么会记得=_=)。完了去烧烤店腐败(白吃白喝)了一顿,其中就点了香辣烤羊蹄搭配酸梅汁,美食过后所有烦恼顿时烟消云散,如今所有的不愉快早已抛诸脑后,只记得当时啃完蹄子后闷一口梅汁的酸爽!

  想起个包名的时候想起了那只蹄子,于是包就叫做xlkyt。纪念那只羊,同时感恩那些在你最落魄的时候拉了你一把的人。

idea的maven项目下spring与mybatis整合的更多相关文章

  1. idea下maven项目下spring junit 测试用例

    使用idea在编写的类下右键Go->Test或者ctrl+shift+t,点击create new test会在相应目录下创建test类 别写代码如下 @RunWith(value = Spri ...

  2. Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderL

    Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderL     严重: Error config ...

  3. Maven项目下update maven后Eclipse报错

    Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderL     严重: Error config ...

  4. Maven项目下HttpServletRequest 或 HttpServletResponse需引用的依赖包

    转载: http://xyly624.blog.51cto.com/842520/865630/ Maven项目下HttpServletRequest 或 HttpServletResponse需引用 ...

  5. Maven+SSM框架(Spring+SpringMVC+MyBatis) - Hello World(转发)

    [JSP]Maven+SSM框架(Spring+SpringMVC+MyBatis) - Hello World 来源:http://blog.csdn.net/zhshulin/article/de ...

  6. 框架篇:Spring+SpringMVC+Mybatis整合开发

    前言: 前面我已搭建过ssh框架(http://www.cnblogs.com/xrog/p/6359706.html),然而mybatis表示不服啊. Mybatis:"我抗议!" ...

  7. Spring boot Mybatis 整合(完整版)

    个人开源项目 springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页.个人作品.个人博客) 朋友自制的springboot接口文档组件swagge ...

  8. Java基础-SSM之Spring和Mybatis整合案例

    Java基础-SSM之Spring和Mybatis整合案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.   在之前我分享过mybatis和Spring的配置案例,想必大家对它们的 ...

  9. Spring boot Mybatis 整合(注解版)

    之前写过一篇关于springboot 与 mybatis整合的博文,使用了一段时间spring-data-jpa,发现那种方式真的是太爽了,mybatis的xml的映射配置总觉得有点麻烦.接口定义和映 ...

随机推荐

  1. tp剩余未验证内容-7

    bash脚本中 的 set -e表示 exit immediately if a simple command returns a non-zero value.主要是为了防止错误被忽略.会被立即退出 ...

  2. 微信小程序wepy开发循环wx:for需要注意

    微信小程序wepy开发循环wx:for需要注意 item index值必须在wx:for之后使用 <view wx:for="{{tablist}}" class=" ...

  3. 【NOI 2015】品酒大会

    Problem Description 一年一度的"幻影阁夏日品酒大会"隆重开幕了.大会包含品尝和趣味挑战两个环节,分别向优胜者颁发"首席品酒家"和" ...

  4. PHP isset 和 array_key_exists 对比

    经常使用 isset 判断变量或数组中的键是否存在,但是数组中可以使用 array_key_exists 这个函数,那么这两个 哪一个更优呢? 官方文档这样定义两者: isset:语言构造器,用于检测 ...

  5. Linux下更新Git

     查看git版本,卸载旧版本(如果没有安装git请直接到下一步) git --version yum remove git  安装依赖软件 yum install curl-devel expat-d ...

  6. source insight常用设置问题

    http://www.cnblogs.com/bluestorm/archive/2012/10/28/2743792.html

  7. python内置类型:列表,包括 list 和 tuple

    列表list 是一种有序的集合 ,假定list的名字为class list的元素个数:len( class) 访问元素: a. 索引从0开始    b. 也可以使用[-1],[-2],[-3] 从后面 ...

  8. JavaScript基础三

    1.10 关于DOM的事件操作 1.10.1 JavaScript的组成 JavaScript基础分为三个部分: ECMAScript:JavaScript的语法标准.包括变量.表达式.运算符.函数. ...

  9. python中实现并发的手段之 协程

    几种实现并发的手段 进程 启动多个进程 进程之间是由操作系统负责调用线程 启动多个线程 真正被CPU执行的最小单位实际是线程 开启一个线程 创建一个线程 寄存器 堆栈 关闭一个线程协程 本质上是一个线 ...

  10. spring基础知识,未完待续

    https://blog.csdn.net/slow_wakler/article/details/54895508   http://www.runoob.com/design-pattern/ch ...