A.7 springboot mybatis

springboot mybatis

1. 工程搭建

依據(jù)第一章節(jié)的樣例工程,進(jìn)行更改凑懂。

1.1 pom修改

需要引入:

  • mysql jdbc 驅(qū)動(dòng)包
  • mybatis-spring-boot-starter(整合MyBatis的核心依賴)

詳細(xì)內(nèi)容如下:

<!-- mybatis & db -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

1.2 application.properties 修改

  • 增加數(shù)據(jù)庫(kù)連接
  • mybatis mapper文件掃描位置
#jdbc config
spring.datasource.url=jdbc:mysql://192.168.137.101:3306/spring-boot-demo?characterEncoding=utf-8&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-active=5
spring.datasource.max-idle=3
spring.datasource.test-on-borrow=true
spring.datasource.test-while-idle=true
spring.datasource.validation-query=SELECT 1;

#mybatis config
mybatis.mapperLocations = classpath:mapper/*.xml
mybatis.typeAliasesPackage = pers.mateng.demo.springboot

2. 業(yè)務(wù)編碼

2.1 創(chuàng)建pojo

package pers.mateng.demo.springboot.domain;

public class User {
    
    private Long id;
    
    private String name;
    
    private Integer age;
    
    get/set ...
}
package pers.mateng.demo.springboot.dto;

public class UserCondition {

    /**用戶名*/
    private String name;
    
    /**根據(jù)年齡范圍查詢用戶,范圍的最小值*/
    private Integer minAge;
    
    /**根據(jù)年齡范圍查詢用戶梧宫,范圍的最大值*/
    private Integer maxAge;
    
    /**分頁(yè)條件接谨,起始位置*/
    private Integer startPosition;
    
    /**分頁(yè)條件,查詢的最大條數(shù)*/
    private Integer maxResult;
}

2.2 創(chuàng)建DAO

interface

@Mapper
public interface UserDao {
    
    public int add(User user);
    
    public int delete(Long id);
    
    public User getById(Long id);
    
    public List<User> getList(UserCondition condition);
    
    public Long getCount(UserCondition condition);

}

mapper

<?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" > 
<?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="pers.mateng.demo.springboot.dao.UserDao" >

    <resultMap id="user" type="pers.mateng.demo.springboot.domain.User">
        <id column="u_id" property="id" />
        <result column="u_name" property="name" />
        <result column="u_age" property="age" />
    </resultMap>
      
    <select id="getById" resultMap="user">  
        select * from tb_user where u_id = #{id}  
    </select>
      
    <select id="getList" resultMap="user" parameterType="pers.mateng.demo.springboot.dto.UserCondition">  
        select * from tb_user 
        <include refid="where"></include>
        limit #{startPosition}, #{maxResult}
    </select> 
    
    <select id="getCount" parameterType="pers.mateng.demo.springboot.dto.UserCondition" resultType="Long">  
        select count(1) from tb_user 
        <include refid="where"></include>
    </select>
    
    <sql id="where">
        <where>
            <if test="name != null and name.length() > 0">
                and u_name LIKE CONCAT('%', #{name}, '%')
            </if>
            <if test="minAge != null">
                and u_age <![CDATA[ >= ]]> #{minAge}
            </if>
            <if test="maxAge != null">
                and u_age <![CDATA[ <= ]]> #{maxAge}
            </if>
        </where>
    </sql>
      
    <insert id="add" parameterType="pers.mateng.demo.springboot.domain.User">  
        insert into tb_user(u_name, u_age) values(#{name,jdbcType=VARCHAR}, #{age,jdbcType=TINYINT})
    </insert>  
      
    <delete id="delete">  
        delete from tb_user where u_id = #{id}  
    </delete>  
    
</mapper>  

2.3 controller

/**
 * 用戶管理的controller
 * @author mateng
 */
@RestController
@RequestMapping(path="user")
public class UserController {
    
    @Autowired
    private UserDao userDao;
    
    @RequestMapping(method=RequestMethod.GET)
    public Map<String, Object> page(@ModelAttribute UserCondition condition) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", userDao.getCount(condition));
        result.put("rows", userDao.getList(condition));
        return result;
    }
    
    @RequestMapping(method=RequestMethod.POST)
    public int add(@ModelAttribute User user) {
        return userDao.add(user);
    }
    
    @RequestMapping(path="/{id}", method=RequestMethod.GET)
    public User findById(@PathVariable Long id) {
        return userDao.getById(id);
    }
    
    @RequestMapping(path="/{id}", method=RequestMethod.DELETE)
    public int delete(@PathVariable Long id) {
        return userDao.delete(id);
    }

}

3. 驗(yàn)證

啟動(dòng)工程塘匣,使用如下命令測(cè)試增加脓豪、查詢接口。注意:下面連接中的ip地址(當(dāng)前開(kāi)發(fā)機(jī)器的ip地址)

1忌卤、增加:

curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' -d "name=zhansan&age=30" 'http://192.168.50.7:8888/user'

2扫夜、查詢:

分頁(yè)查詢

curl -X GET 'http://192.168.50.7:8888/user'

根據(jù)id查詢

curl -X GET 'http://192.168.50.7:8888/user/1'

5. 源碼

springboot-demo-5

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市埠巨,隨后出現(xiàn)的幾起案子历谍,更是在濱河造成了極大的恐慌,老刑警劉巖辣垒,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異印蔬,居然都是意外死亡勋桶,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)例驹,“玉大人捐韩,你說(shuō)我怎么就攤上這事【樾猓” “怎么了荤胁?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵帮碰,是天一觀的道長(zhǎng)撰糠。 經(jīng)常有香客問(wèn)我篱瞎,道長(zhǎng)投慈,這世上最難降的妖魔是什么郊丛? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任躯喇,我火速辦了婚禮辫封,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘廉丽。我一直安慰自己倦微,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布正压。 她就那樣靜靜地躺著璃诀,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蔑匣。 梳的紋絲不亂的頭發(fā)上劣欢,一...
    開(kāi)封第一講書(shū)人閱讀 51,573評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音裁良,去河邊找鬼凿将。 笑死,一個(gè)胖子當(dāng)著我的面吹牛价脾,可吹牛的內(nèi)容都是我干的牧抵。 我是一名探鬼主播,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼侨把,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼犀变!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起秋柄,我...
    開(kāi)封第一講書(shū)人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤获枝,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后骇笔,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體省店,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嚣崭,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了懦傍。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片雹舀。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖粗俱,靈堂內(nèi)的尸體忽然破棺而出说榆,到底是詐尸還是另有隱情,我是刑警寧澤寸认,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布签财,位于F島的核電站,受9級(jí)特大地震影響废麻,放射性物質(zhì)發(fā)生泄漏荠卷。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一烛愧、第九天 我趴在偏房一處隱蔽的房頂上張望油宜。 院中可真熱鬧,春花似錦怜姿、人聲如沸慎冤。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蚁堤。三九已至,卻和暖如春但狭,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背立磁。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工唱歧, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人几于。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓沿后,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親膝蜈。 傳聞我的和親對(duì)象是個(gè)殘疾皇子熔掺,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容