Mybatis實戰(zhàn)1--簡單增刪改查使用

一寓涨、Mybatis介紹

MyBatis是一個支持普通SQL查詢吼句,存儲過程和高級映射的優(yōu)秀持久層框架先煎。MyBatis消除了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及對結(jié)果集的檢索封裝肩狂。MyBatis可以使用簡單的XML或注解用于配置和原始映射套么,將接口和Java的POJO(Plain Old Java Objects饼酿,普通的Java對象)映射成數(shù)據(jù)庫中的記錄帮毁。

二铭乾、準(zhǔn)備環(huán)境

1 創(chuàng)建用戶表

-- 創(chuàng)建用戶表
CREATE TABLE `user_info` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶id',
  `user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用戶名',
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '密碼',
  `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手機(jī)',
  `icon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '頭像鏈接地址',
  `sex` int(5) NOT NULL DEFAULT '3' COMMENT '性別: 1 男汛蝙,2 女烈涮, 3 保密',
  `age` int(5) NOT NULL DEFAULT '0' COMMENT '年齡',
  `birthday` bigint(15) DEFAULT '0' COMMENT '出生年月',
  `create_time` bigint(15) NOT NULL DEFAULT '0' COMMENT '創(chuàng)建時間',
  `update_time` bigint(15) NOT NULL DEFAULT '0' COMMENT '更新時間',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `index_name` (`user_name`) USING BTREE COMMENT '用戶名唯一索引',
  KEY `index_phone` (`phone`) USING BTREE COMMENT '手機(jī)號索引'
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT='用戶表';

-- 插入數(shù)據(jù)
INSERT INTO `demo`.`user_info`(`user_name`, `password`, `phone`, `icon`, `sex`, `age`, `birthday`, `create_time`, `update_time`) VALUES ('test01', 'test01', '15810101010', '', 3, 0, 1577460560869, 1577460560869, 1577460560869);

2 添加jar包

        <!--組件引用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>
        <!--添加spring boot mybatis依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!--添加數(shù)據(jù)庫連接池依賴-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!--添加數(shù)據(jù)庫依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

三、使用Mybatis查詢數(shù)據(jù)

1.在yml配置文件中添加mybatis配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: demo
    password: demo
    driver-class-name: com.mysql.cj.jdbc.Driver
    druid:
      initial-size: 5  # 初始化大小
      min-idle: 5  # 最小
      max-active: 100  # 最大
      max-wait: 60000  # 連接超時時間
      time-between-eviction-runs-millis: 60000  # 配置間隔多久才進(jìn)行一次檢測窖剑,檢測需要關(guān)閉的空閑連接坚洽,單位是毫秒
      min-evictable-idle-time-millis: 300000  # 指定一個空閑連接最少空閑多久后可被清除,單位是毫秒
      validationQuery: select 'x'
      test-while-idle: true  # 當(dāng)連接空閑時西土,是否執(zhí)行連接測試
      test-on-borrow: false  # 當(dāng)從連接池借用連接時讶舰,是否測試該連接
      test-on-return: false  # 在連接歸還到連接池時是否測試該連接
      filters: config,wall,stat  # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計需了,'wall'用于防火墻
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      maxOpenPreparedStatements: 20
      connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
        session-stat-enable: true
        session-stat-max-count: 10
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        login-username: admin
        login-password: admin
      filter:
        slf4j:
          statement-log-enabled: true

#配置mapper xml 文件路徑跳昼,即在resources目錄下創(chuàng)建mapper文件夾
mybatis:
  mapper-locations: /mapper/*.xml

#開啟打印sql語句
logging:
  level:
    com.gqlofe.userinfo.dao: debug

2.通過mybatis generator 生成實體類和mapper,以及xml

實體類

@Data
public class UserInfo implements Serializable {
    // 用戶id
    private Integer id;

    // 用戶名
    private String userName;

    // 密碼
    private String password;

    // 手機(jī)
    private String phone;

    // 頭像鏈接地址
    private String icon;

    // 性別: 1 男肋乍,2 女鹅颊, 3 保密
    private Integer sex;

    // 年齡
    private Integer age;

    // 出生年月
    private Long birthday;

    // 創(chuàng)建時間
    private Long createTime;

    // 更新時間
    private Long updateTime;

    private static final long serialVersionUID = 1L;

}

生成mapper類,注意 @Mapper 注解 是mybatis的框架的注解墓造,需要手動加上

@Mapper
public interface UserInfoMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(UserInfo record);

    int insertSelective(UserInfo record);

    UserInfo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(UserInfo record);

    int updateByPrimaryKey(UserInfo record);

    UserInfo selectByNamePwd(@Param("userName") String userName, @Param("password") String password);

    UserInfo getUser(UserInfo query);
}

生成的UserInfoMapper.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.gqlofe.userinfo.dao.mapper.UserInfoMapper">
  <resultMap id="BaseResultMap" type="com.gqlofe.userinfo.bean.entity.UserInfo">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="phone" jdbcType="VARCHAR" property="phone" />
    <result column="icon" jdbcType="VARCHAR" property="icon" />
    <result column="sex" jdbcType="INTEGER" property="sex" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="birthday" jdbcType="BIGINT" property="birthday" />
    <result column="create_time" jdbcType="BIGINT" property="createTime" />
    <result column="update_time" jdbcType="BIGINT" property="updateTime" />
  </resultMap>
  <sql id="Base_Column_List">
    id, user_name, password, phone, icon, sex, age, birthday, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user_info
    where id = #{id,jdbcType=INTEGER}
  </select>

  <!--通過用戶名和密碼查詢-->
  <select id="selectByNamePwd" resultType="com.gqlofe.userinfo.bean.entity.UserInfo">
    select
    <include refid="Base_Column_List" />
    from user_info
    where user_name = #{userName} and password = #{password}

  </select>


  <!--通過用戶名或手機(jī)號查詢-->
  <select id="getUser" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from user_info
    where 1 = 1
    <if test="userName">
      and user_name = #{userName}
    </if>
    <if test="phone">
      and phone = #{phone}
    </if>
    and password = #{password}
  </select>


  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user_info
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo" keyProperty="id" useGeneratedKeys="true">
    insert into user_info (id, user_name, password, 
      phone, icon, sex, age, 
      birthday, create_time, update_time
      )
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{phone,jdbcType=VARCHAR}, #{icon,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER}, #{age,jdbcType=INTEGER}, 
      #{birthday,jdbcType=BIGINT}, #{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo" useGeneratedKeys="true" keyProperty="id">
    insert into user_info
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="userName != null">
        user_name,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="phone != null">
        phone,
      </if>
      <if test="icon != null">
        icon,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="age != null">
        age,
      </if>
      <if test="birthday != null">
        birthday,
      </if>
      <if test="createTime != null">
        create_time,
      </if>
      <if test="updateTime != null">
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userName != null">
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        #{phone,jdbcType=VARCHAR},
      </if>
      <if test="icon != null">
        #{icon,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=INTEGER},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
      <if test="birthday != null">
        #{birthday,jdbcType=BIGINT},
      </if>
      <if test="createTime != null">
        #{createTime,jdbcType=BIGINT},
      </if>
      <if test="updateTime != null">
        #{updateTime,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo">
    update user_info
    <set>
      <if test="userName != null">
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        phone = #{phone,jdbcType=VARCHAR},
      </if>
      <if test="icon != null">
        icon = #{icon,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=INTEGER},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="birthday != null">
        birthday = #{birthday,jdbcType=BIGINT},
      </if>
      <if test="createTime != null">
        create_time = #{createTime,jdbcType=BIGINT},
      </if>
      <if test="updateTime != null">
        update_time = #{updateTime,jdbcType=BIGINT},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo">
    update user_info
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR},
      icon = #{icon,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=INTEGER},
      age = #{age,jdbcType=INTEGER},
      birthday = #{birthday,jdbcType=BIGINT},
      create_time = #{createTime,jdbcType=BIGINT},
      update_time = #{updateTime,jdbcType=BIGINT}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

3.基本增刪改查

1.查詢

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Test
    public void selectUserInfo() {

        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(6);
        System.out.println(userInfo);
    }

查詢結(jié)果:

image.png

可以看到執(zhí)行的sql語句也打印了堪伍,數(shù)據(jù)也查出來了。

2.插入

    @Test
    public void addUserInfo() {
        long now = System.currentTimeMillis();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName("test02").setPassword("test02").setPhone("15811111111")
                .setIcon("").setSex(1).setAge(10).setBirthday(now)
                .setCreateTime(now).setUpdateTime(now);
        int insert = userInfoMapper.insert(userInfo);
        System.out.println("insert = " + insert);

查詢結(jié)果:

image.png
image.png

可以看到數(shù)據(jù)庫多了一條記錄.

3.更新

    @Test
    public void updateUserInfo() {
        long now = System.currentTimeMillis();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(12).setPhone("15800000000").setUpdateTime(now);
        int i = userInfoMapper.updateByPrimaryKeySelective(userInfo);
        System.out.println("i = " + i);
    }

更新結(jié)果:

image.png
image.png

4.刪除

    @Test
    public void deleteUserInfo() {
        int i = userInfoMapper.deleteByPrimaryKey(12);
        System.out.println("i = " + i);
    }

刪除結(jié)果:

image.png
image.png

可以看到已經(jīng)被刪除了觅闽。

4.基于注解的增刪改查

使用注解方式帝雇,就需要將對應(yīng)的xml去掉

@Mapper
public interface UserInfoMapper {
    int deleteByPrimaryKey(Integer id);

    @Insert("insert into user_info (id, user_name, password, phone, icon, sex, age, birthday, create_time, update_time)values (#{id}, #{userName}, #{password}, #{phone}, #{icon}, #{sex}, #{age}, #{birthday}, #{createTime}, #{updateTime})")
    int insert(UserInfo record);

    int insertSelective(UserInfo record);

    @Select("select * from user_info where id = #{id}")
    UserInfo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(UserInfo record);

    int updateByPrimaryKey(UserInfo record);

    UserInfo selectByNamePwd(@Param("userName") String userName, @Param("password") String password);

    UserInfo getUser(UserInfo query);
}

經(jīng)過測試結(jié)果同上。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谱煤,一起剝皮案震驚了整個濱河市摊求,隨后出現(xiàn)的幾起案子禽拔,更是在濱河造成了極大的恐慌刘离,老刑警劉巖室叉,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異硫惕,居然都是意外死亡茧痕,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門恼除,熙熙樓的掌柜王于貴愁眉苦臉地迎上來踪旷,“玉大人,你說我怎么就攤上這事豁辉×钜埃” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵徽级,是天一觀的道長气破。 經(jīng)常有香客問我,道長餐抢,這世上最難降的妖魔是什么现使? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮旷痕,結(jié)果婚禮上碳锈,老公的妹妹穿的比我還像新娘。我一直安慰自己欺抗,他們只是感情好售碳,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著绞呈,像睡著了一般团滥。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上报强,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天灸姊,我揣著相機(jī)與錄音,去河邊找鬼秉溉。 笑死力惯,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的召嘶。 我是一名探鬼主播父晶,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼弄跌!你這毒婦竟也來了甲喝?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤铛只,失蹤者是張志新(化名)和其女友劉穎埠胖,沒想到半個月后糠溜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡直撤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年非竿,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谋竖。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡红柱,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蓖乘,到底是詐尸還是另有隱情锤悄,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布嘉抒,位于F島的核電站铁蹈,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏众眨。R本人自食惡果不足惜握牧,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望娩梨。 院中可真熱鬧沿腰,春花似錦、人聲如沸狈定。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽纽什。三九已至措嵌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間芦缰,已是汗流浹背企巢。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留让蕾,地道東北人浪规。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像探孝,于是被迫代替她去往敵國和親笋婿。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354