两周前学习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. linux基础之grep

    grep: Global search REgular expression and Print out the line 作用: 文本搜索工具,根据用户指定的模式对目标文本逐行进行匹配检查,打印匹配 ...

  2. 【NET Core】事务TransactionScope

    .NET FrameWork时期: TransactionScope是FCL System.Transactions命名空间下的分布式事务组件,它默认为本地事务,当系统有需要时可以自动提升为分布式事务 ...

  3. ado.net 批量添加 更新 删除

    自曾列就别往下看 别折腾了   使用 SqlBulkCopy ,dataTable 必须跟sql里面的表字段完全一样 下面在sqlserver中演示 mysql 请google MySqlBulkLo ...

  4. CentOS7.x系统中使用Docker时,在存储方面需要注意的问题

    简述: 1.Docker 1.12.6/v17.03文档中CentOS7系统下安装时,明确说明,用于生产时,必须使用devicemapper驱动的direct-lvm模式,需要我们提前准备好块设备,以 ...

  5. Hive和HBase区别

    1. 两者分别是什么? Apache Hive是一个构建在Hadoop基础设施之上的数据仓库.通过Hive可以使用HQL语言查询存放在HDFS上的数据.HQL是一种类SQL语言,这种语言最终被转化为M ...

  6. JxBrowser之二:常用函数addLoadListener

    1.常用函数addLoadListener,包含对页面加载状态的多种监控回调. browser.addLoadListener(new LoadAdapter() { @Override public ...

  7. 7.9 GRASP原则九: 隔离变化

    GRASP原则九: 隔离变化  Protected Variations  需求一定会变化的!如何做到以系统的局部变化为代价就可以应对这一点?4.1 GRASP rule9: Protected ...

  8. CSS中的盒子模型与 box-sizing 属性

    盒子模型是css中一个重要的概念,是开发网页必须要用的布局方法.盒子模型有两种,分别是标准 w3c 盒子模型和 ie 盒子模型. 标准 w3c 盒子模型:包括 magin(外边距).border(边框 ...

  9. Linq(一)

    概述 LINQ是.NET框架的扩展,它允许我们以使用SQL查询数据库的方式来查询数据集合. 使用LINQ,你可以从数据库.程序对象集合以及XML文档中查询数据. 需要注意的是,对于比较简单的功能,与其 ...

  10. [atcoder contest 010] F - Tree Game

    [atcoder contest 010] F - Tree Game Time limit : 2sec / Memory limit : 256MB Score : 1600 points Pro ...