美文网首页
一分钟搭建Spring结合Mybatis

一分钟搭建Spring结合Mybatis

作者: PenguinMan | 来源:发表于2020-05-04 19:10 被阅读0次

前言

MyBatis 是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。有了MyBatis的帮助,使得Spring后端开发过程对数据库的操作变得轻而易举,下面我们就来看一下在实际项目中Spring与MyBatis是如何合体出现的吧。


MyBatis_logo.png

Spring环境搭建

这里使用Idea作为操作平台,通过File-->New-->Project-->Spring Initializr初始化Spring工程。


Spring.png

为了方便通过网页进行调试,在初始化条目中选择Spring Web


Spring_web.png

添加MyBatis依赖

集成MyBatis需要在Spring工程下的pom文件下添加如下依赖,添加完后记得Import Changes。

        <!--配置mybatis开始-->
        <dependency>
            <groupId>org.mybatis.spring.</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>1.1.3</version>
        </dependency>
        <!--配置mybatis结束-->

配置application

pom依赖添加完成后,我们需要在application.properties文件中进行数据源的配置,以及POJO包,Config文件等扫描文件的配置,如下:

#配置数据源
spring.datasource.url=jdbc:mysql://localhost:3306/t?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#指定POJO扫描包来让mybatis自动扫描到自定义POJO
mybatis.type-aliases-package=com.yanghaoyi.mybatis.model
#配置Config文件
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
#配置mapper
mybatis.mapper-locations=classpath:com.yanghaoyi.mybatis.dao/*.xml

数据库的链接与用户名密码一定要多检查几遍,很多时候都会因为这个微小的细节导致工程无法编译通过。

创建用户表

为了方便演示对数据库的操作,我们先来创建一个用户表,如下:

CREATE TABLE `user_info` ( 
`id` int(10) NOT NULL AUTO_INCREMENT, 
`username` varchar(20) DEFAULT NULL, 
`password` int(10) DEFAULT NULL,
 PRIMARY KEY (`id`) )
 ENGINE=InnoDB DEFAULT CHARSET=utf8;

对应的,在Idea中创建用户Entity类

@Data
public class UserEntity implements Serializable {
    private Integer id;
    private String token;
    private String userName;
    private String password;
}

@Data是为了方便用户类可以免去get set操作,maven依赖如下:

        <!--省去get set方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>

MyBatis映射

在我们的工程目录下创建dao目录,在这个目录下进行mybatis对数据库的操作,首先创建Mapper接口文件:

@Mapper
public interface UserMapper {

    /** 插入用户 */
    int insertUser(UserEntity userEntity);

    /** 通过用户名查找用户 */
    UserEntity findUserByUserName(String userName);

    /** 通过用户Id查找用户 */
    UserEntity findUserById(int id);

}

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目录-->
<mapper namespace="com.yanghaoyi.mybatis.dao.UserMapper">
    <!-- 通过id 查找用户 -->
    <select id="findUserByUserName" parameterType="String" resultType="com.yanghaoyi.mybatis.model.UserEntity">
        select * from user_info where userName=#{userName}
   </select>
    <!-- 插入用户 -->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"    parameterType="com.yanghaoyi.mybatis.model.UserEntity" >
         INSERT INTO user_info VALUES (0,#{userName},#{password});
    </insert>
    <!-- 通过id 查找用户 -->
    <select id="findUserById" parameterType="Integer" resultType="com.yanghaoyi.mybatis.model.UserEntity">
        select * from user_info where "id"=#{id}
   </select>
</mapper>

因为xml文件是放在dao目录下的,为了让spring能够成功扫描,需要在pom文件的build中新增如下配置:

        <!--配置后才可以扫描到dao目录下的xml mapper文件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>

Service服务

为了减轻Controller的负担,这里对数据的操作进行了Service封装,如下:

public interface IUserService {

    /** 插入用户 */
    UserEntity insertUser(String userName, String password);

    /** 通过用户名查找用户 */
    UserEntity findUserByUserName(String userName);

    /** 通过用户Id查找用户 */
    UserEntity findUserById(int id);
}

服务实现类如下:

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserEntity insertUser(String userName, String password) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(userName);
        userEntity.setPassword(password);
        return userEntity;
    }

    @Override
    public UserEntity findUserByUserName(String userName) {
        return userMapper.findUserByUserName(userName);
    }

    @Override
    public UserEntity findUserById(int id) {
        UserEntity userEntity;
        userEntity = userMapper.findUserById(id);
        return userEntity;
    }

}

测试服务

Controller代码如下:

@RestController
@RequestMapping(value = "api/v1/user")
public class UserController {

    @Resource
    private IUserService userService;

    @RequestMapping(value = "/info", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
    public UserEntity getUserInfo() {
        UserEntity userEntity =  userService.findUserById(0);
        return userEntity;
    }

}

application.properties中我设置的端口号是6061,所以运行Application后,服务运行地址就是http://localhost:6061,结合controller中的接口,Demo的运行api即为http://localhost:6061/api/v1/user/info

运行结果.png

示例源码

文章对Spring结合MyBatis的Demo已上传至GitHub,感兴趣的朋友可以Clone下来共同探讨学习一下。
GitHub源码

相关文章

网友评论

      本文标题:一分钟搭建Spring结合Mybatis

      本文链接:https://www.haomeiwen.com/subject/schyghtx.html