1. 程式人生 > >mybatis 在前端對資料庫進行增刪改查

mybatis 在前端對資料庫進行增刪改查

Springboot 對資料庫進行增刪改查

首先要實現在idea裡面能實現對資料看的增刪改查,最後再實現前後端互動

1.首先在資料庫裡面先建好資料庫(test01)和表(t_user)

在這裡插入圖片描述

2.配置檔案pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.wencui</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
   	<groupId>org.springframework.boot</groupId>
   	<artifactId>spring-boot-starter-parent</artifactId>
   	<version>2.0.5.RELEASE</version>
   	<relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
   	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
   	<java.version>1.8</java.version>
   </properties>

   <dependencies>
   	<dependency>
   		<groupId>org.springframework.boot</groupId>
   		<artifactId>spring-boot-starter-web</artifactId>
   	</dependency>

   	<dependency>
   		<groupId>org.springframework.boot</groupId>
   		<artifactId>spring-boot-starter-test</artifactId>
   		<scope>test</scope>
   	</dependency>
   	<dependency>
   		<groupId>org.xmlunit</groupId>
   		<artifactId>xmlunit-core</artifactId>
   	</dependency>
   	<dependency>
   		<groupId>com.vaadin.external.google</groupId>
   		<artifactId>android-json</artifactId>
   		<version>RELEASE</version>
   	</dependency>
   	<dependency>
   		<groupId>net.minidev</groupId>
   		<artifactId>json-smart</artifactId>
   		<version>RELEASE</version>
   	</dependency>
   	<dependency>
   		<groupId>org.apache.maven.plugins</groupId>
   		<artifactId>maven-clean-plugin</artifactId>
   		<version>2.5</version>
   	</dependency>



   	<dependency>
   		<groupId>org.mybatis.spring.boot</groupId>
   		<artifactId>mybatis-spring-boot-starter</artifactId>
   		<version>1.3.1</version>
   	</dependency>
   	<dependency>
   		<groupId>mysql</groupId>
   		<artifactId>mysql-connector-java</artifactId>
   	</dependency>

   	<dependency>
   		<groupId>org.springframework</groupId>
   		<artifactId>spring-test</artifactId>
   		<version>4.3.13.RELEASE</version>
   		<scope>test</scope>
   	</dependency>
   	<dependency>
   		<groupId>junit</groupId>
   		<artifactId>junit</artifactId>
   		<scope>test</scope>
   	</dependency>

   	<dependency>
   	<groupId>org.springframework.boot</groupId>
   	<artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>


   </dependencies>

   <build>
   	<plugins>
   		<plugin>
   			<groupId>org.springframework.boot</groupId>
   			<artifactId>spring-boot-maven-plugin</artifactId>
   		</plugin>
   	</plugins>
   </build>


</project>

3.在model檔案下建立實體類User

public class User {


    //和表裡面的屬性一一對應
    private int id;

    private String username;

    private String password;

    private String nickname;

    private int gid;

    
    //構造方法
    //快捷鍵:Ctrl + Insert
    public User(int id, String username, String password, String nickname, int gid) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.gid = gid;
    }

    //getter 和 setter 方法
    //快捷鍵 : Ctrl + Insert
    public User() {
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public int getGid() {
        return gid;
    }

    public void setGid(int gid) {
        this.gid = gid;
    }

    
    //用於列印顯示
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", nickname='" + nickname + '\'' +
                ", gid=" + gid +
                '}';
    }
}

4.新建配置檔案mapper 下的UserMapper.xml 檔案

注意:此檔案是對資料庫進行操作,這裡面的增刪改查語句是在資料庫裡面都可以執行 的

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http:/5/mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--對應 dao下的 Usermapper介面 -->
<mapper namespace="com.wencui.demo.dao.UserMapper">

    <!--配置資料庫的連結資訊,注意,column 是資料庫的欄位的屬性,property 是實體類 User 裡面的屬性-->
    <resultMap id="baseResultMap" type="com.wencui.demo.model.User">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="nick_name" property="nickname" jdbcType="INTEGER"/>
        <result column="user_name" property="username" jdbcType="INTEGER"/>
        <result column="pass_word" property="password" jdbcType="VARCHAR"/>
        <result column="gid" property="gid" jdbcType="VARCHAR"/>
    </resultMap>

    <!--要返回的資料庫裡面的內容-->
    <sql id="baseColumnList">
        id, nick_name, user_name,pass_word,gid
    </sql>


    <!--增 這裡的 id 要對應 Usermapper 裡面的方法名 -->
    <insert id="add" parameterType="com.wencui.demo.model.User">
        insert into t_user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <!--在資料庫中 id 設定的是主鍵,並且自動遞增,所以不需要手動新增 id-->
            <!-- <if test="id != null">
                 id,
             </if>-->
            <if test="username != null">
                user_name,
            </if>
            <if test="nickname != null">
                nick_name,
            </if>
            <if test="password != null">
                pass_word,
            </if>
            <if test="gid != null">
                gid,
            </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="nickname != null">
                #{nickname,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="gid != null">
                #{gid,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>


    <!--刪,通過 id 刪,parameterType 表示 dao檔案下 Usermapper接口裡面 delete方法傳的引數的資料型別-->
    <delete id="delete" parameterType="java.lang.Integer" >
        delete from t_user
        where id = #{id,jdbcType=INTEGER}
    </delete>


    <!--改 ,通過 id 改,parameterType 表示 dao檔案下 Usermapper接口裡面 update方法傳的引數的資料型別-->
    <update id="update" parameterType="com.wencui.demo.model.User" >
        update t_user
        set user_name = #{username,jdbcType=VARCHAR},
        pass_word = #{password,jdbcType=VARCHAR},
        nick_name = #{nickname,jdbcType=VARCHAR},
        gid = #{gid,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
    </update>


    <!--查,通過查 id,rusultMap 對應的是上面的resultMap 裡面的id,parameterType 表示 dao檔案下 Usermapper接口裡面 loadid方法傳的引數的資料型別 -->
    <select id="loadid" resultMap="baseResultMap" parameterType="java.lang.Integer">
        SELECT
        <!--這裡的是上面的sql 裡面的id-->
        <include refid="baseColumnList"/>
        FROM t_user
        WHERE id = #{id}
    </select>

    <!--查,通過 username 查,rusultMap 對應的是上面的resultMap 裡面的id,parameterType 表示 dao檔案下 Usermapper接口裡面 loadname方法傳的引數的資料型別-->
    <select id="loadname" resultMap="baseResultMap" parameterType="java.lang.String">
        SELECT
        <!--這裡的是上面的sql 裡面的id-->
        <include refid="baseColumnList"/>
        FROM t_user
        WHERE user_name = #{username}
    </select>


    <!--返回Json資料,rusultMap 對應的是上面的resultMap 裡面的id,parameterType 表示 dao檔案下 Usermapper接口裡面 list方法傳的引數的資料型別-->
    <select id="list" resultMap="baseResultMap" parameterType="java.util.HashMap">
        select
        <!--這裡的是上面的sql 裡面的id-->
        <include refid="baseColumnList"/>
        from t_user
    </select>

</mapper>

5.在dao(持久層)裡面寫增刪改查的方法

注意:Usermapper這是一個介面,定義方法名字是要和mapper檔案下的Usermapper.xml的id值相對應


//@mapper 是為了找到 mybitis 的配置檔案 mapper,不寫會報錯
@Mapper
public interface UserMapper {

    //增
   public void add(User user);

   //刪
   public void delete(int id);

   //改
   public void update(User user);

   //通過id查,用於輔助刪除,改
   public User loadid(int id);

   //通過username來查,用於輔助改
   public User loadname(User username);

   //返回 JSon 資料
   public List<User> list();

}


6.這時我們可以寫一個測試類來測試一下dao裡面的Usermapper接口裡面的方法能不能用

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)

public class TestUserDao {

    @Autowired
    protected UserMapper userMapper;

    @org.junit.Test
    public void Testadd() {
        User user = new User();
        user.setUsername("溫dada");
        user.setPassword("123");
        user.setNickname("wen");
        user.setGid(2);
        userMapper.add(user);
    }


    @org.junit.Test
    public void Testdelete(){
        userMapper.delete(13);

    }

    
    @org.junit.Test
    public void Testupdate(){
        User user = new User();
        user.setId(7);
        user.setUsername("溫大大");
        user.setPassword("123");
        user.setNickname("wen");
        user.setGid(2);
        userMapper.update(user);
    }


    @org.junit.Test
    public void Testloadid(){
        User user = new User();
        int id = user.getId();
        userMapper.loadid(id);
        System.out.println(id);
        System.out.println(userMapper.loadid(id));
    }
    
    
    @org.junit.Test
    public void Testlist(){
        System.out.println(userMapper.list());
    }

}

7.新建service(業務層)

這一層是用來和前端做資料操作用的,同樣要寫一個介面UserService用來寫方法,這裡介面就不用寫@Mapper了

public interface UserService {
	//這裡面的方法和dao層裡面的UserMapper接口裡面的方法幾乎一樣就不做多的解釋
    public List<User> list();

    public void add(User user);

    public User loadid(int id);

    public void delete(int id);

    public void update(User user);

	// 這裡新增一個方法,用於登入用
    public String login(String url,User user);

}

8. 再在service下寫一個實現類UserServiceImpl


//@Service 標註這是一個service,不可不寫
@Service("userService")
public class UserServiceImpl implements UserService {


    //@Resouce 表示通過名字注入
    @Resource
    private UserMapper userMapper;


    //@Override是Java5的元資料,自動加上去的一個標誌,告訴你說下面這個方法是從父類/介面 繼承過來的,不寫會報錯
    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public void add(User user) {
        userMapper.add(user);
    }

    @Override
    public User loadid(int id) {
        return userMapper.loadid(id);
    }

    @Override
    public void delete(int id) {
         userMapper.delete(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);

    }

    @Override
    public String login(String url,User user) {

        User name =userMapper.loadname(user);
        if (name == null){
            System.out.println("此使用者不存在!請註冊。");
            url="/login/login";
        }
        else {
            if(name.getPassword().equals( user.getPassword())){
             url ="/user/load";
            }
            else {
                System.out.println("密碼錯誤");
            }
        }
        return url;
    }


}


}

9.新建一個controller 資料夾

在Controller裡面新建類UserController去檢驗service層


//@Controller表示這是一個Controller
@Controller
@RequestMapping("/user")  //表示網頁訪問的路徑
public class UserController {

    //@Autowired 表示通過型別來找,區分 @Rsource
    @Autowired
    private UserService userService;

    @RequestMapping("/listjson")
    @ResponseBody  // 表示在網頁中返回Json資料
    public List<User> list() {
        System.out.println(userService.list());
        return userService.list();
    }


    // get方法,從後臺得到資料
    @RequestMapping(value = "/load",method = RequestMethod.GET)
    public String load(Model model){
        model.addAttribute("users",new User());
        model.addAttribute("users",userService.list());
        return "user/load"; // 返回到load的頁面
    }


    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(Model model){
        model.addAttribute("user",new User());
       return "user/add";
    }


    // post方法,向後臺傳送資料
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(User user){
        userService.add(user);
       // System.out.println(user);
        return "redirect:/user/load"; //跳轉到load頁面
    }
    

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable int id) {
        userService.delete(id);
      //  System.out.println(id);
        return "redirect:/user/load";
    }
    

    @RequestMapping(value = "/{id}/update",method = RequestMethod.GET)
    public String update(@PathVariable int id,Model model){
        model.addAttribute(userService.loadid(id));
        model.addAttribute("user",userService.loadid(id));
     //   System.out.println(userService.loadid(id));
        return "user/update";
    }

    
    @RequestMapping(value = "/{id}/update",method = RequestMethod.POST)
    public String update(User user ){
            userService.update(user);
          //  System.out.println(user);
            return "redirect:/user/load";

    }
}

再新建一個LoginController 來寫登入,也可以直接寫在UserController裡面,不過要注意路徑是否改變

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model){
        model.addAttribute("user", new User());
        return "user/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user){
        String  url = "/login";
        url = userService.login(url,user);
        System.out.println(user);
        System.out.println(url);
        return "redirect:"+url;
    }

}

UserController裡面對應的HTML頁面

add

<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8 ">
    <title>study01 - helloWorld</title>
</head>

<body>

<div id="bigbox">

<form class="form-horizontal" method="post" th:action="@{add}" th:object="${user}">
    <fieldset>
        <div id="legend" class="">
            <legend class="">新增使用者</legend>
        </div>
        <div class="control-group">

            <label class="control-label" >使用者名稱</label>
            <div class="controls">
                <input type="text" placeholder="username" class="input-xlarge" th:field="*{username}"/>
                <p class="help-block"></p>
            </div>
        </div><div class="control-group">

        <!-- Text input-->
        <label class="control-label" >密碼</label>
        <div class="controls">
            <input type="text" placeholder="password" class="input-xlarge" th:field="*{password}"/>
            <p class="help-block"></p>
        </div>
    </div>

        <div class="control-group">

            <!-- Text input-->
            <label class="control-label">暱稱</label>
            <div class="controls">
                <input type="text" placeholder="nickname" class="input-xlarge" th:field="*{nickname}"/>
                <p class="help-block"></p>
            </div>
        </div>

        <div class="control-group">

            <!-- Text input-->
            <label class="control-label">gid</label>
            <div class="controls">
                <input type="text" placeholder="gid" class="input-xlarge" th:field="*{gid}"/>
                <p class="help-block"></p>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label"></label>

            <!-- Button -->
            <div class="controls">
                <button class="btn btn-success">提交</button>
            </div>
        </div>
    </fieldset>
</form>
</div>
</body>
</html>

update

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>updete</title>
</head>
<body>

<form class="form-horizontal" method="post" th:action="@{update}" th:object="${user}">
    <fieldset>
        <div id="legend" class="">
            <legend class="">修改使用者</legend>
        </div>
        <div class="control-group">
            
            <label class="control-label" >使用者名稱</label>
            <div class="controls">
                <input type="text" placeholder="username" class="input-xlarge" th:field="*{username}"/>
                <p class="help-block"></p>
            </div>
        </div><div class="control-group">

        <!-- Text input-->
        <label class="control-label" >密碼</label>
        <div class="controls">
            <input type="text" placeholder="password" class="input-xlarge" th:field="*{password}"/>
            <p class="help-block"></p>
        </div>
    </div>

        <div class="control-group">

            <!-- Text input-->
            <label class="control-label">暱稱</label>
            <div class="controls">
                <input type="text" placeholder="nickname" class="input-xlarge" th:field="*{nickname}"/>
                <p class="help-block"></p>
            </div>
        </div>

        <div class="control-group">

            <!-- Text input-->
            <label class="control-label">gid</label>
            <div class="controls">
                <input type="text" placeholder="gid" class="input-xlarge" th:field="*{gid}"/>
                <p class="help-block"></p>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label"></label>

            <!-- Button -->
            <div class="controls">
                <button class="btn btn-success">提交</button>
            </div>
        </div>
    </fieldset>
</form>

</body>
</html>

load

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>load</title>
</head>
<body>

<div>
    <ul th:each="user:${users}">
        <li th:text="${user.id}"></li>
        <li th:text="${user.username}"></li>
        <li th:text="${user.password}"></li>
        <li th:text="${user.nickname}"></li>
        <li th:text="${user.gid}"></li>
        <li><a th:href="@{{id}/update(id=${user.id})}">修改</a></li>
        <li><a th:href="@{{id}/delete(id=${user.id})}">刪除</a></li>
    </ul>
</div>
</body>
</html>

login

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<div id="bigbox">
<form class="form-horizontal" method="post" th:action="@{login}" th:object="${user}">
    <fieldset>
        <div id="legend" class="">
            <legend class="">登入</legend>
        </div>
        <div class="control-group">

            <label class="control-label" >使用者名稱</label>
            <div class="controls">
                <input type="text" placeholder="username" class="input-xlarge" th:field="*{username}"/>
                <p class="help-block"></p>
            </div>
        </div><div class="control-group">

        <!-- Text input-->
        <label class="control-label" >密碼</label>
        <div class="controls">
            <input type="text" placeholder="password" class="input-xlarge" th:field="*{password}"/>
            <p class="help-block"></p>
        </div>
    </div>
        <div class="control-group">
            <label class="control-label"></label>

            <!-- Button -->
            <div class="controls">
                <button class="btn btn-success" ><a >登入</a></button>
            </div>
            <div class="controls">
                <button class="" ><a href="/user/add">註冊</a></button>
            </div>
        </div>
    </fieldset>
</form>
</div>
</body>
</html>

10. 最後新建一個application.properties

spring.thymeleaf.cache=false
#連結資料庫
spring.datasource.url=jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=你的密碼
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#指定bean所在包
mybatis.type-aliases-package=com.wencui.demo.model
#指定對映檔案
mybatis.mapperLocations=classpath:mapper/*.xml
#列印mybatis的sql語句
logging.level.org.springframework=WARN
logging.level.org.mybatis=info
logging.file=logs/spring-boot-logging.log
server.port=8080

注意:在導包是要注意包的路徑,路徑會錯了會出現一些錯