SSM整合系列之 实现对象的增删查改(CRUD)操作

版权声明:如需转载,请注明出处。 https://blog.csdn.net/caiqing116/article/details/84581171

本文将详细介绍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);
	}
}

猜你喜欢

转载自blog.csdn.net/caiqing116/article/details/84581171