使用SSM框架组合实现增删改查的功能

基于ssm框架组合的增删改查功能

ssm框架组合之前已经搭建完成了,下面基于该框架组合实现增删改查的功能,首先创建一个数据库和一张表:

CREATE DATABASE `ssmteam` /*!40100 DEFAULT CHARACTER SET utf8 */;

创建t_user表:

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

创建User类:

package com.monkey1024.bean;

import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.time.LocalDate;

public class User implements Serializable{

    private static final long serialVersionUID = 1L;

    private int id;

    private String name;

    private String phone;

    private String address;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate birthday;


    public User(){}

    public User(String name, String phone, String address, LocalDate birthday) {
        this.name = name;
        this.phone = phone;
        this.address = address;
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public LocalDate getBirthday() {
        return birthday;
    }

    public void setBirthday(LocalDate birthday) {
        this.birthday = birthday;
    }
}

创建UserDao.xml的mybatis的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">
<mapper namespace="com.monkey1024.dao.UserDao">

    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

    <insert id="addUser">
        INSERT INTO t_user(name,phone,address,birthday) VALUES (#{name},#{phone},#{address},#{birthday})
        <selectKey resultType="int" keyProperty="id" order="AFTER">
            SELECT @@identity
        </selectKey>
    </insert>

    <delete id="deleteUser">
        DELETE FROM t_user where id=#{id}
    </delete>

    <update id="updateUser">
        UPDATE t_user set name=#{name},phone=#{phone},address=#{address},birthday=#{birthday} where id=#{id}
    </update>

    <select id="selectUsers" resultType="user">
        SELECT id,name,phone,address,birthday FROM t_user
    </select>

    <select id="selectUserById" resultType="user">
        SELECT id,name,phone,address,birthday FROM t_user where id=#{id}
    </select>

</mapper>

创建UserDao接口,注意名称要跟上面的mapper名称一致:

package com.monkey1024.dao;

import com.monkey1024.bean.User;

import java.util.List;

public interface UserDao {

    void addUser(User user);

    void updateUser(User user);

    List<User> selectUsers();

    User selectUserById(int id);

    void deleteUser(int id);
}

创建UserService接口和实现类:

package com.monkey1024.service;

import com.monkey1024.bean.User;

import java.util.List;

public interface UserService {

    void addUser(User user) throws Exception;

    void updateUser(User user);

    List<User> selectUsers();

    User selectUserById(int id);

    void deleteUser(int id) throws Exception;
}

实现类:

package com.monkey1024.service.impl;

import com.monkey1024.bean.User;
import com.monkey1024.dao.UserDao;
import com.monkey1024.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = NullPointerException.class)
    public void addUser(User user) throws Exception {
        userDao.addUser(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
        throw new RuntimeException();

    }

    @Override
    public List<User> selectUsers() {

        return userDao.selectUsers();
    }

    @Override
    public User selectUserById(int id) {

        return userDao.selectUserById(id);
    }

    @Override
    public void deleteUser(int id){
        userDao.deleteUser(id);
        throw new RuntimeException();

    }
}

创建controller类,使用restful风格:

package com.monkey1024.controller;

import com.alibaba.fastjson.JSON;
import com.monkey1024.bean.User;
import com.monkey1024.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public String selectUsers(){

        List<User> users = userService.selectUsers();


        return JSON.toJSONString(users);
    }

    @GetMapping("/users/{id}")
    public String selectUserById(@PathVariable int id) {

        User user = userService.selectUserById(id);

        return JSON.toJSONString(user);
    }

    @PostMapping("/users")
    public String addUser(@RequestBody User user) {


        try {
            userService.addUser(user);

            return JSON.toJSONString("success");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString("fail");
        }

    }

    @PutMapping("/users/{id}")
    public String updateUser(@PathVariable int id, @RequestBody User user) {


        try {
            user.setId(id);
            userService.updateUser(user);

            return JSON.toJSONString("success");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString("fail");
        }
    }

    @DeleteMapping("/users/{id}")
    public String deleteUser(@PathVariable int id) {

        try {
            userService.deleteUser(id);

            return JSON.toJSONString("success");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString("fail");
        }
    }
}

至此,后台的内容就都已经完成了,在controller中基本上使用的是之前在spring mvc中的增删改查的例子,所以前台部分也使用spring mvc中的例子。
前台部分的内容参考:http://www.monkey1024.com/framework/1322