1. 程式人生 > >SSM整合系列之 實現物件的增刪查改(CRUD)操作

SSM整合系列之 實現物件的增刪查改(CRUD)操作

本文將詳細介紹SSM整合後通過Mybatis實現物件的增刪查改
1.根據Mybatis逆向工程生產實體類,Mapper(Dao),Sql
我自己實現了一個專案,並且帶有自定義註釋,
專案git地址:https://github.com/gitcaiqing/mybatis_generator_zh.git
專案部落格地址:https://blog.csdn.net/caiqing116/article/details/84586914
此係列文章主要講SSM整合,對應無Mybatis基礎的同學可先學習之,後續我也會專門寫一個Mybatis的教程供大家參考。
2.這裡我們簡單的建立資料庫db_ssmdemo,和一個使用者表,用於本文的增刪查改操作

DROP TABLE IF EXISTS tb_basic_user;
CREATE TABLE tb_basic_user (
  id int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵自增',
  userId varchar(32) DEFAULT NULL COMMENT '使用者ID',
  utype int(1) DEFAULT 0 COMMENT '使用者型別 0管理員1普通使用者',
  username varchar(20) NOT NULL COMMENT '使用者名稱',
  password varchar(100) NOT NULL COMMENT 'MD5加密密碼',
  headimg varchar(200) DEFAULT NULL COMMENT '頭像',
  realname varchar(20) DEFAULT NULL COMMENT '真實姓名',
  sex int(1) DEFAULT NULL COMMENT '性別',
  age int(2) DEFAULT NULL COMMENT '年齡',
  mobile varchar(20) DEFAULT NULL COMMENT '手機號',
  email varchar(50) DEFAULT NULL COMMENT '郵件地址',
  credate datetime DEFAULT NULL COMMENT '建立時間',
  upddate datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (id)
);

3.生成的實體類,mapper,sql大致如下:
實體類很簡單,這裡就不全部貼出,需要看全部的,可下載原始碼

public class BasicUser {
    /**
     * 主鍵自增
     */
    private Integer id;

    /**
     * 使用者ID
     */
    private String userid;

    /**
     * 使用者型別 0管理員1普通使用者
     */
    private Integer utype;

    /**
     * 使用者名稱
     */
    private String username;

    /**
     * MD5加密密碼
     */
    private String password;
    ......

Mapper的通用CRUD操作,這裡我們新增一個根據使用者名稱獲取使用者資訊,登陸的時候正好可複用

    package com.ssm.mapper;
    import com.ssm.entity.BasicUser;
    /**
     * @author https://blog.csdn.net/caiqing116 2018-11-28
     */
    public interface BasicUserMapper{
       
    	int deleteByPrimaryKey(Integer id);
        int insert(BasicUser record);
        int insertSelective(BasicUser record);
        BasicUser selectByPrimaryKey(Integer id);
        int updateByPrimaryKeySelective(BasicUser record);
        int updateByPrimaryKey(BasicUser record);
        /**
        * 根據使用者名稱查詢
        */
    	BasicUser selectByUsername(String username);
    }

Mapper的實現類,包含selectByUsername的實現,在這裡我刪除了預設生成的insert 和 updateByPrimaryKey兩個實現,這兩個實現要求所有欄位都需要賦值,因為幾乎是不用的,完全可以用insertSelective 和 updateByPrimaryKeySelective代替,具體SQL如下:

<?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.ssm.mapper.BasicUserMapper" >
  <resultMap id="BaseResultMap" type="com.ssm.entity.BasicUser" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="userId" property="userid" jdbcType="VARCHAR" />
    <result column="utype" property="utype" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
    <result column="headimg" property="headimg" jdbcType="VARCHAR" />
    <result column="realname" property="realname" jdbcType="VARCHAR" />
    <result column="sex" property="sex" jdbcType="INTEGER" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="mobile" property="mobile" jdbcType="VARCHAR" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="credate" property="credate" jdbcType="TIMESTAMP" />
    <result column="upddate" property="upddate" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, userId, utype, username, password, headimg, realname, sex, age, mobile, email, 
    credate, upddate
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from tb_basic_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tb_basic_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insertSelective" parameterType="com.ssm.entity.BasicUser" >
    insert into tb_basic_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="userid != null" >
        userId,
      </if>
      <if test="utype != null" >
        utype,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="password != null" >
        password,
      </if>
      <if test="headimg != null" >
        headimg,
      </if>
      <if test="realname != null" >
        realname,
      </if>
      <if test="sex != null" >
        sex,
      </if>
      <if test="age != null" >
        age,
      </if>
      <if test="mobile != null" >
        mobile,
      </if>
      <if test="email != null" >
        email,
      </if>
      <if test="credate != null" >
        credate,
      </if>
      <if test="upddate != null" >
        upddate,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="userid != null" >
        #{userid,jdbcType=VARCHAR},
      </if>
      <if test="utype != null" >
        #{utype,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="headimg != null" >
        #{headimg,jdbcType=VARCHAR},
      </if>
      <if test="realname != null" >
        #{realname,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=INTEGER},
      </if>
      <if test="age != null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="mobile != null" >
        #{mobile,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="credate != null" >
        #{credate,jdbcType=TIMESTAMP},
      </if>
      <if test="upddate != null" >
        #{upddate,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.ssm.entity.BasicUser" >
    update tb_basic_user
    <set >
      <if test="userid != null" >
        userId = #{userid,jdbcType=VARCHAR},
      </if>
      <if test="utype != null" >
        utype = #{utype,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null" >
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="headimg != null" >
        headimg = #{headimg,jdbcType=VARCHAR},
      </if>
      <if test="realname != null" >
        realname = #{realname,jdbcType=VARCHAR},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=INTEGER},
      </if>
      <if test="age != null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="mobile != null" >
        mobile = #{mobile,jdbcType=VARCHAR},
      </if>
      <if test="email != null" >
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="credate != null" >
        credate = #{credate,jdbcType=TIMESTAMP},
      </if>
      <if test="upddate != null" >
        upddate = #{upddate,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <!-- 根據使用者名稱查詢 -->
  <select id="selectByUsername" parameterType="java.lang.String" resultMap="BaseResultMap">
  	select 
    <include refid="Base_Column_List" />
    from tb_basic_user
    where username = #{username,jdbcType=VARCHAR}
  </select>
</mapper>

4. 使用者Service和實現類的開發
基於上文中生成和自己實現的Mapper和SQL我們現在可以正式進行使用者的增刪查改操作了
4.1建立使用者Service介面

package com.ssm.service;
import com.ssm.entity.BasicUser;
/**
 * 使用者Service
 * @author https://blog.csdn.net/caiqing116
 *
 */
public interface BasicUserService {
	
	Integer insert(BasicUser basicUser);
	
	Integer deleteById(Integer id);
	
	BasicUser selectById(Integer id);
	
	Integer updateById(BasicUser basicUser);
	
	BasicUser selectByUsername(String username);

}

4.2 實現使用者Service介面

package com.ssm.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ssm.entity.BasicUser;
import com.ssm.mapper.BasicUserMapper;
import com.ssm.service.BasicUserService;

/**
 * 使用者Service實現類
 * @author https://blog.csdn.net/caiqing116
 */
@Service
public class BasicUserServiceImpl implements BasicUserService{

	@Autowired
	private BasicUserMapper basicUserMapper;
	
	/**
	 * 插入使用者
	 */
	public Integer insert(BasicUser basicUser) {
		return basicUserMapper.insertSelective(basicUser);
	}

	/**
	 * 根據id刪除
	 */
	public Integer deleteById(Integer id) {
		return basicUserMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 根據id查詢
	 */
	public BasicUser selectById(Integer id) {
		return basicUserMapper.selectByPrimaryKey(id);
	}

	/**
	 * 根據id更新
	 */
	public Integer updateById(BasicUser basicUser) {
		return basicUserMapper.updateByPrimaryKeySelective(basicUser);
	}

	/**
	 * 根據使用者名稱查詢
	 */
	public BasicUser selectByUsername(String username) {
		return basicUserMapper.selectByUsername(username);
	}
}

5. 編寫使用者Service測試類
(1)建立測試例項,在BasicService類上右鍵new–>other–>JUnit–>JUnit Test Case,然後如下圖操作

在這裡插入圖片描述
在這裡插入圖片描述
執行完以上步驟後在src-java-test com.ssm.service下自動生成BasicUserServiceTest.java類
(2)實現測試,在生成的測試類上新增如下註解即可正常載入配置檔案測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/*.xml","classpath:servlet/*.xml" })

具體實現如下:

package com.ssm.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ssm.entity.BasicUser;
import com.ssm.util.EncryptKit;
import com.ssm.util.UuidUtil;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/*.xml","classpath:servlet/*.xml" })
public class BasicUserServiceTest {
	
	private static final Logger log = LoggerFactory.getLogger(BasicUserServiceTest.class);
	
	@Autowired
	private BasicUserService basicUserService;

	@Test
	public void testInsert() {
		BasicUser basicUser = new BasicUser();
		basicUser.setId(1);
		basicUser.setUtype(1);
		basicUser.setUserid(UuidUtil.getUuid());
		basicUser.setUsername("墨傾池");
		basicUser.setPassword(EncryptKit.MD5("123456"));
		basicUser.setAge(18);
		int result = basicUserService.insert(basicUser);
		log.info("basicUser:"+basicUser);
		log.info("插入行數:"+result);
	}

	@Test
	public void testDeleteById() {
		int result = basicUserService.deleteById(1);
		log.info("刪除行數:"+result);
	}

	@Test
	public void testSelectById() {
		BasicUser basicUser = basicUserService.selectById(1);
		log.info("basicUser:"+basicUser);
	}

	@Test
	public void testUpdateById() {
		BasicUser basicUser = new BasicUser();
		basicUser.setId(1);
		basicUser.setAge(19);
		int result = basicUserService.updateById(basicUser);
		log.info("更新行數:"+result);
	}

	@Test
	public void testSelectByUsername() {
		String username = "墨傾池";
		BasicUser basicUser = basicUserService.selectByUsername(username);
		log.info("basicUser:"+basicUser);
	}
}