环境:java8
IDE:idea
demo git地址:https://github.com/yhan219/shop,由于demo一直在更新,请自行回退。
依赖:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
gradle请自行替换。
yml中数据源配置:
spring: datasource: url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8 username: root password:
yml中mybatis配置文件:
mybatis: typeAliasesPackage: com.thunisoft.domain mapper-locations: classpath:mapper/*.xml
添加事务:在@SpringBootApplication下添加@EnableTransactionManagement
简单的整合到此结束。
以demo为例简单说一下使用:
实体类:
package com.yhan219.domain; import java.io.Serializable; /** * Created by yhan219 on 2017/1/6. */ public class User implements Serializable { private String id; private String username; private String password; private String tel; private Integer role; public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public void setTel(String tel) { this.tel = tel; } public String getTel() { return tel; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setId(String id) { this.id = id; } public String getId() { return id; } public void setRole(Integer role) { this.role = role; } public Integer getRole() { return role; } }
mapper:
package com.yhan219.repository; import com.yhan219.domain.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * Created by yhan219 on 2017/1/7. */ @Mapper public interface UserMapper { int save(User user); User selectById(String id); int updateById(User user); int deleteById(String id); List<User> queryAll(); }
<?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.yhan219.repository.UserMapper" > <insert id="save" parameterType="com.yhan219.domain.User"> insert into t_user(id,username,password,tel) values(#{id,jdbcType=VARCHAR},#{username,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR},#{tel,jdbcType=VARCHAR}) </insert> <select id="selectById" resultType="com.yhan219.domain.User"> select * from t_user where id = #{id,jdbcType=VARCHAR} </select> <update id="updateById" parameterType="com.yhan219.domain.User"> update t_user set username = #{username,jdbcType=VARCHAR} , password = #{password,jdbcType=VARCHAR} , tel = #{tel,jdbcType=VARCHAR}, role = #{role,jdbcType=INTEGER} where id = #{id,jdbcType=VARCHAR} </update> <delete id="deleteById"> delete from t_user where id = #{id,jdbcType=VARCHAR} </delete> <select id="queryAll" resultType="com.yhan219.domain.User"> select * from t_user </select> </mapper>
使用方法同一般mybatis通常来说。spring boot是简化配置,并不简化代码。service和controller请看demo源码。