MyBatis学习教程(八)

网友投稿 184 2023-07-16


MyBatis学习教程(八)

一、搭建开发环境

1.1、使用Maven创建Web项目

执行如下命令:

复制代码 代码如下:

mvn archetype:create -DgroupId=me.gacl -DartifactId=spring4-mybatis3 -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

如下图所示:

创建好的项目如下:

编辑pom.xml文件

xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">

..

me.gacl

spring-mybatis

war

.-SNAPSHOT

spring-mybatis Maven Webapp

http://maven.apache.org

junit

junit

..

test

spring-mybatis

xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">

..

me.gacl

spring-mybatis

war

.-SNAPSHOT

spring-mybatis Maven Webapp

http://maven.apache.org

junit

junit

..

test

spring-mybatis

修改spring4-mybatis3 Maven Webapp部分,把"Maven Webapp"这部分包含空格的内容去掉,否则Maven在编译项目时会因为空格的原因导致一些莫名其妙的错误出现,修改成:spring4-mybatis3

另外,把以下内容删掉:

junit

junit

..

test

这部分是junit的jar包依赖信息,这个版本太低了,我们不使用这个Junit测试版本,修改过后的pom.xml内容如下:

xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">

..

me.gacl

spring-mybatis

war

.-SNAPSHOT

spring-mybatis

http://maven.apache.org

spring-mybatis

xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">

..

me.gacl

spring-mybatis

war

.-SNAPSHOT

spring-mybatis

http://maven.apache.org

spring-mybatis

1.2、将创建好的项目导入MyEclipse中

具体操作步骤如下图所示:

手动创建【src/main/java】、【src/test/resources】、【src/test/java】这三个source folder,如下图所示:

到此,项目搭建的工作就算是全部完成了。

二、创建数据库和表(针对mysql)

SQL脚本如下:

Create DATABASE spring4_mybatis3;

USE spring4_mybatis3;

DROP TABLE IF EXISTS t_user;

CREATE TABLE t_user (

user_id char(32) NOT NULL,

user_name varchar(30) DEFAULT NULL,

user_birthday date DEFAULT NULL,

user_salary double DEFAULT NULL,

PRIMARY KEY (user_id)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

创建好的数据库和表如下:

三、使用generator工具生成代码

在网上找到了一个generator工具可以根据创建好的数据库表生成MyBatis的表对应的实体类,SQL映射文件和dao,找到generator工具根目录下的generator.xml文件,这个文件是用来配置代码生成规则的,如下图所示:

编辑generator.xml文件,内容如下:

打开命令行窗口,切换到生成工具的根目录下,执行如下命令:

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

如下图所示:

刚才我们在generator.xml文件中配置将生成的代码和SQL映射文件放到"C:\Users\gacl\spring4-mybatis3\src\main\java"这个目录下,这个目录就是我们的spring4-mybatis3项目所在目录,我们刷新一下src/main/java目录,就可以看到生成的代码和映射文件了,如下图所示:

生成的代码和映射文件一行都不用改,可以直接应用到项目当中。下面我们看一眼由generator工具生成的代码和映射文件:

1、生成的dao类

package me.gacl.dao;

import me.gacl.domain.User;

public interface UserMapper {

int deleteByPrimaryKey(String userId);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(String userId);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);

}

生成的UserMapper是一个接口,里面定义了一些操作t_user表的增删改查方法。

2、生成的实体类

package me.gacl.domain;

import java.util.Date;

public class User {

private String userId;

private String userName;

private Date userBirthday;

private Double userSalary;

public String getUserId() {

return userId;

}

public void setUserId(String userId) {

this.userId = userId == null ? null : userId.trim();

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName == null ? null : userName.trim();

}

public Date getUserBirthday() {

return userBirthday;

}

public void setUserBirthday(Date userBirthday) {

this.userBirthday = userBirthday;

}

public Double getUserSalary() {

return userSalary;

}

public void setUserSalary(Double userSalary) {

this.userSalary = userSalary;

}

}

User类是t_user表的对应的实体类,User类中定义的属性和t_user表中的字段一一对应。

3、生成的SQL映射文件

user_id, user_name, user_birthday, user_salary

select

from t_user

where user_id = #{userId,jdbcType=CHAR}

delete from t_user

where user_id = #{userId,jdbcType=CHAR}

insert into t_user (user_id, user_name, user_birthday,

user_salary)

values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE},

#{userSalary,jdbcType=DOUBLE})

insert into t_user

user_id,

user_name,

user_birthday,

user_salary,

#{userId,jdbcType=CHAR},

#{userName,jdbcType=VARCHAR},

#{userBirthday,jdbcType=DATE},

#{userSalary,jdbcType=DOUBLE},

update t_user

user_name = #{userName,jdbcType=VARCHAR},

user_birthday = #{userBirthday,jdbcType=DATE},

user_salary = #{userSalary,jdbcType=DOUBLE},

where user_id = #{userId,jdbcType=CHAR}

update t_user

set user_name = #{userName,jdbcType=VARCHAR},

user_birthday = #{userBirthday,jdbcType=DATE},

user_salary = #{userSalary,jdbcType=DOUBLE}

where user_id = #{userId,jdbcType=CHAR}

UserMapper.xml这个文件的内容是编写操作t_user表的SQL语句,重点说一下UserMapper.xml配置中需要注意的几个小细节问题:

1、UserMapper.xml的标签的namespace必须是UserMapper接口的全类名,既

2、UserMapper.xml的定义操作数据库的

之所以有上述说的这两点要求,就是为了能够让MyBatis能够根据UserMapper接口和UserMapper.xml文件去自动实现UserMapper接口中定义的相关方法,这样我们就不再需要针对UserMapper接口去编写具体的实现代码了。

四、Spring与MyBatis整合

首先我们要在项目中加入我们需要的相关jar包,我们可以到Maven的中央仓库:http://search.maven.org/找到我们要的相关jar包,如下图所示:

我们只需要在搜索框中输入要找的jar包的名称,点击【SEARCH】按钮,就可以找到我们要的jar包了。

4.1、添加Spring与Mybatis的相关jar包

1、添加spring-core,输入spring-core关键字进行查找,如下图所示:

找到关于spring-core的依赖描述信息,如下图所示:

org.springframework

spring-core

4.1.4.RELEASE

复制到项目的pom.xml文件中,如下所示:

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

me.gacl

spring4-mybatis3

war

1.0-SNAPSHOT

spring4-mybatis3

http://maven.apache.org

org.springframework

spring-core

4.1.4.RELEASE

spring4-mybatis3

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

me.gacl

spring4-mybatis3

war

1.0-SNAPSHOT

spring4-mybatis3

http://maven.apache.org

org.springframework

spring-core

4.1.4.RELEASE

spring4-mybatis3

这样Maven就会自动帮我们从Maven的中央仓库中下载spring-core这个jar包到我们的本地仓库,然后将spring-core这个jar包以及它的相关依赖包加入到我们的项目当中,如下所示:

spring4.x与mybatis3.x所需要的相关jar包都可以采用上述所说的方式进行查找,然后添加到项目当中,添加完spring4.x与mybatis3.x相关jar包后,pom.xml文件内容最终如下:

xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">

..

me.gacl

spring-mybatis

war

.-SNAPSHOT

spring-mybatis

http://maven.apache.org

org.springframework

spring-core

...RELEASE

org.springframework

spring-context

...RELEASE

org.springframework

spring-tx

...RELEASE

org.springframework

spring-jdbc

...RELEASE

org.springframework

spring-test

...RELEASE

org.springframework

spring-web

...RELEASE

org.aspectj

aspectjweaver

..

org.mybatis

mybatis

..

org.mybatis

mybatis-spring

..

javax.servlet

javax.servlet-api

..

javax.servlet.jsp

javax.servlet.jsp-api

..-b

javax.servlet

&ltJSnGGUpxwq;artifactId>jstl

.

mysql

mysql-connector-java

..

com.alibaba

druid

..

junit

junit

.

test

spring-mybatis

xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">

..

me.gacl

spring-mybatis

war

.-SNAPSHOT

spring-mybatis

http://maven.apache.org

org.springframework

spring-core

...RELEASE

org.springframework

spring-context

...RELEASE

org.springframework

spring-tx

...RELEASE

org.springframework

spring-jdbc

...RELEASE

org.springframework

spring-test

...RELEASE

org.springframework

spring-web

...RELEASE

org.aspectj

aspectjweaver

..

org.mybatis

mybatis

..

org.mybatis

mybatis-spring

..

javax.servlet

javax.servlet-api

..

javax.servlet.jsp

javax.servlet.jsp-api

..-b

javax.servlet

&ltJSnGGUpxwq;artifactId>jstl

.

mysql

mysql-connector-java

..

com.alibaba

druid

..

junit

junit

.

test

spring-mybatis

4.2、编写相关配置文件

1、dbconfig.properties

在src/main/resources目录下创建一个dbconfig.properties文件,用于编写连接MySQL数据库的相关信息,dbconfig.properties的内容如下:

driverClassName=com.mysql.jdbc.Driver

validationQuery=SELECT 1

jdbc_url=jdbc:mysql://localhost:3306/spring4_mybatis3?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull

jdbc_username=root

jdbc_password=XDP

2、spring.xml(spring框架的配置文件)

在src/main/resources目录下创建一个spring.xml文件,spring.xml文件就是针对Spring框架编写的核心配置文件,spring.xml的内容如下:

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.0.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.0.xsd">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="

http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-3.0.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-3.0.xsd">

我们的spring.xml文件的配置非常简单,就两个配置。

3、spring-mybatis.xml(spring与mybatis整合的配置文件)

在src/main/resources目录下创建一个spring-mybatis.xml文件,spring-mybatis.xml文件就是针对Spring框架与Mybatis框架整合编写的配置文件,spring-mybatis.xml的内容如下:

me.gacl.service.*

到此,相关的配置文件算是编写完成了,如下图所示:

4.3、进行单元测试

经过以上两个步骤,spring4与mybatis3的整合算是全部完成了。接下来我们要做的工作就算进行单元测试,测试一下spring4与mybatis3的整合是否成功。

1、在src/main/java目录下创建一个me.gacl.service包,然后在me.gacl.service包创建一个UserServiceI接口,如下所示:

package me.gacl.service;

import me.gacl.domain.User;

public interface UserServiceI {

/**

* 添加用户

* @param user

*/

void addUser(User user);

/**

* 根据用户id获取用户

* @param userId

* @return

*/

User getUserById(String userId);

}

2、在src/main/java目录下创建一个me.gacl.service.impl包,然后在me.gacl.service.impl包创建一个针对UserServiceI接口的实现类:UserServiceImpl,如下所示:

package me.gacl.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import me.gacl.dao.UserMapper;

import me.gacl.domain.User;

import me.gacl.service.UserServiceI;

/**

* @author gacl

* 使用@Service注解将UserServiceImpl类标注为一个service

* service的id是userService

*/

@Service("userService")

public class UserServiceImpl implements UserServiceI {

/**

* 使用@Autowired注解标注userMapper变量,

* 当需要使用UserMapper时,Spring就会自动注入UserMapper

*/

@Autowired

private UserMapper userMapper;//注入dao

@Override

public void addUser(User user) {

userMapper.insert(user);

}

@Override

public User getUserById(String userId) {

return userMapper.selectByPrimaryKey(userId);

}

}

创建好的两个类如下所示:

3、在src/test/java目录下编写单元测试类,新建一个me.gacl.test包,然后在这个包下创建一个MyBatisTest类,代码如下:

package me.gacl.test;

import java.util.Date;

import java.util.UUID;

import me.gacl.domain.User;

import me.gacl.service.UserServiceI;

//import me.gacl.service.UserServiceI;

import org.junit.Before;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyBatisTest {

private UserServiceI userService;

/**

* 这个before方法在所有的测试方法之前执行,并且只执行一次

* 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行

* 比如在before方法里面初始化ApplicationContext和userService

*/

@Before

public void before(){

//使用"spring.xml"和"spring-mybatis.xml"这两个配置文件创建Spring上下文

ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});

//从Spring容器中根据bean的id取出我们要使用的userService对象

userService = (UserServiceI) ac.getBean("userService");

}

@Test

public void testAddUser(){

//ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});

//UserServiceI userService = (UserServiceI) ac.getBean("userService");

User user = new User();

user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));

user.setUserName("白虎神皇xdp");

user.setUserBirthday(new Date());

user.setUserSalary(D);

userService.addUser(user);

}

}

执行单元测试代码,这时候会报如下错误:

错误提示是说没有找到"me.gacl.test.MyBatisTest"这个类,这是因为我们没有使用maven编译项目中的类的缘故。

下面我们使用Maven编译项目,选中项目的pom.xml文件→【Debug As】→【maven install】,如下所示:

编译结果如下:

在这里说一下我执行Maven install之后遇到的问题,第一次执行Maven install命令时,就出现了如下一堆乱七八糟的错误:

后来我把项目删掉,再重新导入项目,然后再执行Clean项目操作之后,如下图所示:

再执行Maven install操作又可以正常编译通过了,这让我郁闷了好久,这应该不是我项目配置的原因,而是Maven的原因,具体也不知道为啥会这样。反正这算是一种解决办法吧,如果遇到执行Maven install操作不能正常编译通过的情况:可以尝试采用:Maven clean→Clean项目→Maven install这三个步骤去解决问题。

除了可以用常规的Junit进行单元测试之外,我们还可以使用Spring提供的Junit测试框架进行单元测试,在me.gacl.test下新建一个MyBatisTestBySpringTestFramework类,代码如下:

package me.gacl.test;

import java.util.Date;

import java.util.UUID;

import me.gacl.domain.User;

import me.gacl.service.UserServiceI;

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.junit.SpringJUnitClassRunner;

@RunWith(SpringJUnitClassRunner.class)

//配置了@ContextConfiguration注解并使用该注解的locations属性指明spring和配置文件之后,

@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml" })

public class MyBatisTestBySpringTestFramework {

//注入userService

@Autowired

private UserServiceI userService;

@Test

public void testAddUser(){

User user = new User();

user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));

user.setUserName("xdp_gacl_白虎神皇");

user.setUserBirthday(new Date());

user.setUserSalary(D);

userService.addUser(user);

}

@Test

public void testGetUserById(){

String userId = "fbcebfdada";

User user = userService.getUserById(userId);

System.out.println(user.getUserName());

}

}

执行这两个测试方法,是可以正常测试通过的,如下所示:

到此,我们框架的整合测试工作就算是全部通过了,整合成功。

4.4、在web服务器中进行测试

1、编辑web.xml文件,添加spring监听器配置项,内容如下:

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

version="3.0">

index.jsp

Spring监听器

org.springframework.web.context.ContextLoaderListener

contextConfigLocation

classpath:spring.xml,classpath:spring-mybatis.xml

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

version="3.0">

index.jsp

Spring监听器

org.springframework.web.context.ContextLoaderListener

contextConfigLocation

classpath:spring.xml,classpath:spring-mybatis.xml

2、在UserMapper接口中添加一个获取所有用户信息的getAllUser()方法,如下所示:

package me.gacl.dao;

import java.util.List;

import me.gacl.domain.User;

public interface UserMapper {

int deleteByPrimaryKey(String userId);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(String userId);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);

/**获取所有用户信息

* @return List

*/

List getAllUser();

}

3、在UserMapper.xml文件中编写getAllUser()方法要执行的SQL语句,如下所示:

user_id, user_name, user_birthday, user_salary

select

from t_user

where user_id = #{userId,jdbcType=CHAR}

delete from t_user

where user_id = #{userId,jdbcType=CHAR}

insert into t_user (user_id, user_name, user_birthday,

user_salary)

values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE},

#{userSalary,jdbcType=DOUBLE})

insert into t_user

user_id,

user_name,

user_birthday,

user_salary,

#{userId,jdbcType=CHAR},

#{userName,jdbcType=VARCHAR},

#{userBirthday,jdbcType=DATE},

#{userSalary,jdbcType=DOUBLE},

update t_user

user_name = #{userName,jdbcType=VARCHAR},

user_birthday = #{userBirthday,jdbcType=DATE},

user_salary = #{userSalary,jdbcType=DOUBLE},

where user_id = #{userId,jdbcType=CHAR}

update t_user

set user_name = #{userName,jdbcType=VARCHAR},

user_birthday = #{userBirthday,jdbcType=DATE},

user_salary = #{userSalary,jdbcType=DOUBLE}

where user_id = #{userId,jdbcType=CHAR}

select user_id, user_name, user_birthday, user_salary from t_user

4、在UserServiceI接口中也添加一个getAllUser()方法,如下:

package me.gacl.service;

import java.util.List;

import me.gacl.domain.User;

public interface UserServiceI {

/**

* 添加用户

* @param user

*/

void addUser(User user);

/**

* 根据用户id获取用户

* @param userId

* @return

*/

User getUserById(String userId);

/**获取所有用户信息

* @return List

*/

List getAllUser();

}

5、在UserServiceImpl类中实现getAllUser方法,如下:

package me.gacl.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import me.gacl.dao.UserMapper;

import me.gacl.domain.User;

import me.gacl.service.UserServiceI;

/**

* @author gacl

* 使用@Service注解将UserServiceImpl类标注为一个service

* service的id是userService

*/

@Service("userService")

public class UserServiceImpl implements UserServiceI {

/**

* 使用@Autowired注解标注userMapper变量,

* 当需要使用UserMapper时,Spring就会自动注入UserMapper

*/

@Autowired

private UserMapper userMapper;//注入dao

@Override

public void addUser(User user) {

userMapper.insert(user);

}

@Override

public User getUserById(String userId) {

return userMapper.selectByPrimaryKey(userId);

}

@Override

public List getAllUser() {

return userMapper.getAllUser();

}

}

6、在src/main/java目录下创建一个me.gacl.web.controller包,然后在me.gacl.web.controller下创建一个UserServlet,如下:

package me.gacl.web.controller;

import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

import me.gacl.domain.User;

import me.gacl.service.UserServiceI;

/**

* @author gacl

* @WebServlet是Servlet.提供的注解,目的是将一个继承了HttpServlet类的普通java类标注为一个Servlet

* UserServlet使用了@WebServlet标注之后,就不需要在web.xml中配置了

*/

@WebServlet("/UserServlet")

public class UserServlet extends HttpServlet {

//处理业务逻辑的userService

private UserServiceI userService;

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//获取所有的用户信息

List lstUsers = userService.getAllUser();

request.setAttribute("lstUsers", lstUsers);

request.getRequestDispatcher("/index.jsp").forward(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doGet(request, response);

}

public void init() throws ServletException {

//在Servlet初始化时获取Spring上下文对象(ApplicationContext)

ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

//从ApplicationContext中获取userService

userService = (UserServiceI) ac.getBean("userService");

}

}

7、编辑index.jsp页面,用于展示查询到的用户信息,内容如下:

<%@ page language="java" pageEncoding="UTF-8"%>

<%--引入JSTL核心标签库 --%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%--遍历lstUsers集合中的User对象 --%>

8、执行maven install命令编译项目,然后将项目部署到tomcat服务器中运行,注意,由于要使用Servlet3.0,所以必须将项目部署到tomcat7.x以上的服务器中去运行,如下所示:

输入地址:http://localhost:8080/spring4-mybatis3/UserServlet访问UserServlet,访问结果如下:

可以看到,t_user表中的用户信息全部查询出来显示到页面上了。这样在web服务器中的测试也正常通过了。

以上就是Spring4.x与MyBatis3.x整合的全部内容了。编写这个整合例子花了不少时间,使用Maven编译时总是出现莫名其妙的问题,有时候成功,有时候失败,反正很莫名其妙。如果遇到执行Maven install操作不能正常编译通过的情况:可以尝试采用:Maven clean→Clean项目→Maven install这三个步骤去解决问题


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:谈一谈bootstrap响应式布局
下一篇:基于BootStrap的图片轮播效果展示实例代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~