springboot 整合mybatis

因?yàn)閬?lái)到這邊公司要用到mybatis,之前因?yàn)橛玫氖莝pringboot,所以就想在springboot下面去整合mybatis. 因?yàn)橹坝玫氖莌ibernate,所以做起來(lái)也很簡(jiǎn)單,我覺(jué)得mybatis定制化很好,就是配置起來(lái)有點(diǎn)麻煩,之前hibernate 和 JPA用起來(lái)很快,mybatis就是要寫(xiě)一寫(xiě)mapper.xml,但是這可以鍛煉你的一個(gè)sql編寫(xiě)能力。廢話就說(shuō)這么多,先上結(jié)構(gòu)圖吧。

結(jié)構(gòu)圖:

structure.png

Model:

@Data
public class User {
   private Integer id;
   private String name;
   private Integer age;
   private String email;
}

其中data 注解是lombok插件里的,自動(dòng)實(shí)現(xiàn)get set 以及hashcode 、euqals 和 toString 還有默認(rèn)的構(gòu)造函數(shù)

Mapper:

@Mapper
public interface UserMapper {

    User findUserById(@Param("id") Integer id);

    int updateUser(@Param("name") String name, @Param("id") Integer id);

    int insertUser(@Param("id") Integer id, @Param("name") String name,
                   @Param("age") Integer age, @Param("email") String email);

    int deleteUser(@Param("id") Integer id);

}

@Mapper注解會(huì)自動(dòng)的生成UserMapper的代理類(lèi),并注入到spring容器中,所以在Service層的話,直接@Autowired的注入就行了。

Mapping:

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC
        "-//mybatis.org//DTD com.example.Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
    <resultMap id="result" type="com.example.model.User">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <result property="email" column="email"/>
    </resultMap>
    <select id="findUserById" resultMap="result">
        SELECT * FROM user where id = #{id};
    </select>

    <update id="updateUser">
        UPDATE user
        SET
        NAME = #{name}
        where id = #{id}
    </update>

    <insert id="insertUser">
        INSERT INTO user(id,name,age,email)
        VALUES (
        #{id,jdbcType=INTEGER},
        #{name,jdbcType=VARCHAR},
        #{age,jdbcType=INTEGER},
        #{email,jdbcType=VARCHAR}
        )
    </insert>

    <delete id="deleteUser">
        delete from user where id = #{id}
    </delete>
</mapper>

DAO:

@Component
public class UserDao {
    @Autowired
    private UserMapper mapper;

    public User findUserById(Integer id) {
        return mapper.findUserById(id);
    }

    public int insert(Integer id, String name, Integer age, String email) {
        return mapper.insertUser(id, name, age, email);
    }

    public int update(String name, Integer id) {
        return mapper.updateUser(name, id);
    }

    public int delete(Integer id) {
        return mapper.deleteUser(id);
    }
}

Controller:

@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    @RequestMapping("/user")
    public User getUserById(@RequestParam(value = "id") Integer id) {
        User user;
        user = userDao.findUserById(id);
        return user;
    }

    @RequestMapping("/update")
    public int updateById(@RequestParam(value = "name") String name,
                          @RequestParam(value = "id") Integer id) {
        return userDao.update(name, id);
    }

    @RequestMapping("/insert")
    public int insert(@RequestParam(value = "name") String name,
                      @RequestParam(value = "id") Integer id,
                      @RequestParam(value = "age") Integer age,
                      @RequestParam(value = "email") String email) {
        return userDao.insert(id, name, age, email);
    }

    @RequestMapping("/delete")
    public int delete(@RequestParam(value = "id") Integer id) {
        return userDao.delete(id);
    }

}

Dependencies:

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    compile('org.springframework.boot:spring-boot-devtools')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1')
    compile('org.projectlombok:lombok:1.16.8')
    compile('mysql:mysql-connector-java:6.0.5')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

配置文件:

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapperLocations=classpath*:Mapper/**/*.xml

Schema:

CREATE TABLE `user` (
  `id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `name` varchar(255) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年齡',
  `email` varchar(255) CHARACTER SET latin1 DEFAULT NULL COMMENT '郵件',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在項(xiàng)目的技術(shù)選型中,持久層框架常用的有Hibernate/JPA,Mybatis,JDBC等等,雖然之前特別喜歡J...
    星塵0085閱讀 631評(píng)論 0 1
  • 摘要: 原創(chuàng)出處:www.bysocket.com 泥瓦匠BYSocket 希望轉(zhuǎn)載,保留摘要,謝謝! 推薦一本書(shū)...
    子木聊出海閱讀 5,243評(píng)論 6 66
  • springboot免去了一大堆的xml配置,達(dá)到了開(kāi)箱即用,springboot中的springdatajpa是...
    馬木木閱讀 1,684評(píng)論 0 1
  • 不知從什么時(shí)候開(kāi)始,我們的生活充滿了著各種刻奇。 紅玫瑰如同一只穩(wěn)健而無(wú)聊的股票,身價(jià)有規(guī)律的漲跌。 巧克力如同一...
    圖癢閱讀 846評(píng)論 0 2
  • 音樂(lè)創(chuàng)作人,也是民謠歌手------安來(lái)寧,有一首歌《烏蘭巴托的夜》,初聽(tīng)到的時(shí)候,覺(jué)得很耳熟,但歌手和曲名卻陌生...
    草莓味呀巴扎嘿閱讀 5,949評(píng)論 2 2

友情鏈接更多精彩內(nèi)容