转载

Web应用全栈之旅-Spring篇(二)集成mybatis

一、pom文件

引入mybatis

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

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

二、yml配置

添加数据库配置和mybatis配置:

database.url=127.0.0.1:3306
spring.datasource.url=jdbc:mysql://${database.url}/demodb?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin123

mybatis.mapper-locations=classpath:mapper/*.xml

三、DAO

定义DAO接口,添加@Mapper注解:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import com.javashizhan.demo.mybatis.domain.User;

@Mapper
public interface UserDAO {

    User findUserByName(@Param(value = "name") String name) throws Exception;

    void createUser(@Param(value = "user") User user) throws Exception;

    int deleteUserByName(@Param(value = "name") String name) throws Exception;
}

四、mybatis数据库脚本配置文件

脚本配置文件User.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.javashizhan.demo.mybatis.dao.UserDAO">
    
    <!-- id值和DAO方法名保持一致,返回类型和DAO返回对象一致,字段别名和User字段名一致 -->
    <select id="findUserByName" resultType="com.javashizhan.demo.mybatis.domain.User">
        select
          NAME name,
          AGE age,
          GENDER gender
        from USER where name = #{name}
    </select>
    
    <insert id="createUser">
        insert USER(
          NAME,
          AGE,
          GENDER
        ) values(
          #{user.name},
          #{user.age},
          #{user.gender}
         )
    </insert>
    
    <insert id="deleteUserByName">
        delete from USER where name = #{name}
    </insert>
</mapper>

将此文件放到resources目录的子目录mapper下,和yml配置文件中的路径一致。

Web应用全栈之旅-Spring篇(二)集成mybatis

五、Service中调用DAO

@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;

    public User findUserByName(@Param(value = "name") String name) throws Exception {
        return userDAO.findUserByName(name);
    }

    public void createUser(@Param(value = "user") User user) throws Exception {
        userDAO.createUser(user);
    }

    public int deleteUserByName(@Param(value = "name") String name) throws Exception {
        return userDAO.deleteUserByName(name);
    }
}

以上为spring集成mybatis的所有步骤,完整实例代码扫码加入微信公众号并回复:<font color="RED">webfullstack</font>,获取仓库地址。

end.

站点: http://javashizhan.com/

微信公众号:

Web应用全栈之旅-Spring篇(二)集成mybatis

加入知识星球,参与讨论,更多实战代码分享!

https://t.zsxq.com/RNzfi2j

Web应用全栈之旅-Spring篇(二)集成mybatis

原文  https://segmentfault.com/a/1190000020038827
正文到此结束
Loading...