SpringBoot整合MyBatis(XML)

(1)、添加依赖

1         <dependency>
2             <groupId>org.mybatis.spring.boot</groupId>
3             <artifactId>mybatis-spring-boot-starter</artifactId>
4             <version>2.0.0</version>
5         </dependency>

(2)、编写Mapper接口类

 1 package cn.coreqi.mapper;
 2 
 3 import cn.coreqi.entities.User;
 4 import org.apache.ibatis.annotations.Mapper;
 5 
 6 @Mapper
 7 public interface UserMapper {
 8 
 9     public User getUserById(Integer id);
10 
11     public int addUser(User user);
12 
13     public int modifyUser(User user);
14 
15     public int delUserById(Integer id);
16 }

(3)、编写Mybatis配置文件

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration
3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 <configuration>
6     <settings>
7         <setting name="mapUnderscoreToCamelCase" value="True"/>
8     </settings>
9 </configuration>

(4)、编写Mapper接口对应的Mapper配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="cn.coreqi.mapper.UserMapper">
 6     <select id="getUserById" resultType="cn.coreqi.entities.User">
 7         select * from users where Id = #{id}
 8     </select>
 9 
10     <insert id="addUser" useGeneratedKeys="true" keyProperty="Id">
11         insert into users(UserName,PassWord,Enabled) values(#{UserName},#{PassWord},#{Enabled})
12     </insert>
13 
14     <update id="modifyUser">
15         update users set UserName = #{UserName},PassWord = #{PassWord},Enabled = #{Enabled} where Id = #{Id}
16     </update>
17 
18     <delete id="delUserById">
19         delete from users where Id = #{id}
20     </delete>
21 </mapper>

(5)、在配置文件中配置mybatis

1 spring.datasource.username=root
2 spring.datasource.password=123456
3 spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC
4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
5 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
6 
7 mybatis.config-location=classpath:mybatis/mybatis-config.xml
8 mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

 

posted @ 2019-02-01 20:06  SpringCore  阅读(182)  评论(0编辑  收藏  举报