Spring MVC 实现CRUD功能

Spring web项目开发

一、Spring MVC 项目搭建

二、Spring MVC 集成 MyBatis

三、Spring MVC 实现CRUD功能


UserMapper.xml




<mapper namespace="spring.mybatis.sample.basic.user.dao.UserDao">

    <select id="selectOne" parameterType="spring.mybatis.sample.basic.user.dao.domain.User"
            resultType="spring.mybatis.sample.basic.user.dao.domain.User">
        SELECT
        id as id,
        user_name as userName,
        age as age,
        sex as sex,
        address as address
        FROM SYSTEM_USER
        <trim prefix="WHERE" prefixOverrides="AND">
            <if test="id != null and id != ''">
                and id = #{id}
            if>
            <if test="userName != null and userNmae != ''">
                and user_name = #{userName}
            if>
            <if test="age != null">
                and age = #{age}
            if>
            <if test="sex != null">
                and sex = #{sex}
            if>
            <if test="address != null and address != ''">
                and address = #{address}
            if>
        trim>
    select>

    <insert id="insert" parameterType="spring.mybatis.sample.basic.user.dao.domain.User">
        INSERT INTO SYSTEM_USER (id, user_name, age, sex, address)
        VALUES (#{id}, #{userName}, #{age}, #{sex}, #{address})
    insert>

    <update id="update" parameterType="spring.mybatis.sample.basic.user.dao.domain.User">
        UPDATE SYSTEM_USER
        <trim prefix="SET" suffixOverrides=",">
            user_name = #{userName},
            age = #{age},
            sex = #{sex},
            address = #{address},
        trim>
        <trim prefix="WHERE" prefixOverrides="AND">
            AND id = #{id}
        trim>
    update>

    <delete id="delete" parameterType="spring.mybatis.sample.basic.user.dao.domain.User">
        DELETE FROM SYSTEM_USER
        <trim prefix="WHERE" prefixOverrides="AND">
            <if test="id != null and id != ''">
                AND id = #{id}
            if>
            <if test="userName != null and userName != ''">
                AND user_name = #{userName}
            if>
            <if test="age != null">
                AND age = #{age}
            if>
            <if test="sex != null">
                AND sex = #{sex}
            if>
            <if test="address != null and address != ''">
                AND address = #{address}
            if>
        trim>
    delete>
mapper>

UserDao.java

package spring.mybatis.sample.basic.user.dao;

import spring.mybatis.sample.basic.user.dao.domain.User;

/**
 * Created by liuquan on 2019/3/19.
 */
public interface UserDao {

    Integer insert(User user);

    Integer update(User user);

    Integer delete(User user);

    User selectOne(User user);

}

UserDaoImpl.java

package spring.mybatis.sample.basic.user.dao.impl;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import spring.mybatis.sample.basic.user.dao.UserDao;
import spring.mybatis.sample.basic.user.dao.domain.User;

/**
 * Created by liuquan on 2019/3/19.
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public Integer insert(User user) {
        return this.sqlSessionTemplate.insert("spring.mybatis.sample.basic.user.dao.UserDao.insert", user);
    }

    @Override
    public Integer update(User user) {
        return this.sqlSessionTemplate.insert("spring.mybatis.sample.basic.user.dao.UserDao.update", user);
    }

    @Override
    public Integer delete(User user) {
        return this.sqlSessionTemplate.insert("spring.mybatis.sample.basic.user.dao.UserDao.delete", user);
    }

    @Override
    public User selectOne(User user) {
        return this.sqlSessionTemplate.selectOne("spring.mybatis.sample.basic.user.dao.UserDao.selectOne", user);
    }
}

UserService.java

package spring.mybatis.sample.basic.user.service;

import spring.mybatis.sample.basic.user.bo.UserBO;

/**
 * Created by liuquan on 2019/3/19.
 */
public interface UserService {

    UserBO queryOneUser(UserBO userBO);

    Integer insertUser(UserBO userBO);

    Integer updateUser(UserBO userBO);

    Integer deleteUser(UserBO userBO);
}

UserServiceImpl.java

package spring.mybatis.sample.basic.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.mybatis.sample.basic.user.bo.UserBO;
import spring.mybatis.sample.basic.user.dao.UserDao;
import spring.mybatis.sample.basic.user.dao.domain.User;
import spring.mybatis.sample.basic.user.service.UserService;
import spring.mybatis.sample.utils.BeanCopyUtils;

/**
 * Created by liuquan on 2019/3/19.
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserBO queryOneUser(UserBO userBO) {
        User user = BeanCopyUtils.copyProperties(new User(), userBO);

        User newUser = null;
        try{
            newUser = userDao.selectOne(user);
        }catch (Exception ex){
            // throw Exception
        }

        if (newUser == null){
            // throw Exception
        }
        UserBO newUserBO = BeanCopyUtils.copyProperties(new UserBO(), newUser);
        return newUserBO;
    }

    @Override
    public Integer insertUser(UserBO userBO) {
        User user = BeanCopyUtils.copyProperties(new User(), userBO);

        Integer insertNum = null;
        try{
            insertNum = userDao.insert(user);
        }catch (Exception ex){
            // throw Exception
        }

        if (insertNum.intValue() <= 0){
            // throw Exception
        }

        return insertNum;
    }

    @Override
    public Integer updateUser(UserBO userBO) {
        User user = BeanCopyUtils.copyProperties(new User(), userBO);

        Integer updateNum = null;
        try{
            updateNum = userDao.update(user);
        }catch(Exception ex){
            // throw Exception
        }

        if (updateNum.intValue() <= 0){
            // throw Exception
        }
        return updateNum;
    }

    @Override
    public Integer deleteUser(UserBO userBO) {
        User user = BeanCopyUtils.copyProperties(new User(), userBO);

        Integer deleteNum = null;
        try{
            deleteNum = userDao.delete(user);
        }catch(Exception ex){
            // throw Exception
        }

        if (deleteNum.intValue() <= 0){
            // throw Exception
        }

        return deleteNum;
    }
}

UserController.java

package spring.mybatis.sample.basic.user.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import spring.mybatis.sample.basic.user.bo.UserBO;
import spring.mybatis.sample.basic.user.service.UserService;
import spring.mybatis.sample.basic.user.vo.UserVO;
import spring.mybatis.sample.common.Response;
import spring.mybatis.sample.utils.BeanCopyUtils;

/**
 * Created by liuquan on 2019/3/19.
 */
@Controller
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("/query-user-detail.json")
    public UserBO queryUserDetail(UserVO userVO){

        UserBO userBO = BeanCopyUtils.copyProperties(new UserBO(), userVO);
        UserBO newUserBO = userService.queryOneUser(userBO);
        return newUserBO;
    }


    @ResponseBody
    @RequestMapping("/save-user.json")
    public Response saveUser(UserVO userVO){

        Response response = new Response();
        UserBO userBO = BeanCopyUtils.copyProperties(new UserBO(), userVO);
        try{
            userService.insertUser(userBO);
            response.setCode(Response.SUCCESS);
        } catch(Exception ex){
            response.setCode(Response.FAIL);
        }

        return response;
    }

    @ResponseBody
    @RequestMapping("/edit-user.json")
    public Response editUser(UserVO userVO){

        Response response = new Response();
        UserBO userBO = BeanCopyUtils.copyProperties(new UserBO(), userVO);
        try{
            userService.updateUser(userBO);
            response.setCode(Response.SUCCESS);
        } catch(Exception ex){
            response.setCode(Response.FAIL);
        }

        return response;
    }

    @ResponseBody
    @RequestMapping("/delete-user.json")
    public Response deleteUser(UserVO userVO){

        Response response = new Response();
        UserBO userBO = BeanCopyUtils.copyProperties(new UserBO(), userVO);
        try{
            userService.deleteUser(userBO);
            response.setCode(Response.SUCCESS);
        } catch(Exception ex){
            response.setCode(Response.FAIL);
        }

        return response;
    }

}

新增

http://localhost:8080/userController/save-user.json?id=6&userName=apple&age=20&sex=1&address=wuhan

查询

http://localhost:8080/userController/query-user-detail.json?id=6
{"id":"6","userName":"apple","age":20,"sex":1,"address":"wuhan"}

编辑

localhost:8080/userController/edit-user.json?id=6&age=12
{"id":"6","userName":null,"age":12,"sex":null,"address":null}

编辑保存的时候我们只想将第六条记录中age字段改成12,其它字段值不变,可实际却导致另外三个字段值成为null了。原因就是在更新的时候没有对字段值是否为空进行判断。
修改后的sql如下:

    <update id="update" parameterType="spring.mybatis.sample.basic.user.dao.domain.User">
        UPDATE SYSTEM_USER
        <trim prefix="SET" suffixOverrides=",">
        	<if test="userName != null and userName != ''">
				user_name = #{userName},
			if>
			<if test="age != null">
            	age = #{age},
			if>
			<if test="sex != null">
            	sex = #{sex},
			if>
			<if test="address != null and address != ''">
	            address = #{address},
			if>
        trim>
        <trim prefix="WHERE" prefixOverrides="AND">
            AND id = #{id}
        trim>
    update>

删除

localhost:8080/userController/delete-user.json?id=6
{"id":null,"userName":null,"age":null,"sex":null,"address":null}

你可能感兴趣的:(Spring)