後端spring boot+前端Android交互+mysql增刪查改

1.概述

使用spring boot做爲後端框架與Android端配合mysql進行基本的交互,包含了最基本的增刪查改功能.html

2.開發環境

  • win10
  • IDEA
  • tomcat9.0.27
  • mysql8.0.17
  • spring boot

3.後端

(1)新建一個spring boot項目

能夠看這裏前端

(2)Entity

新建User類做爲實體類:java

package com.test;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

這裏其實使用的是(1)中的代碼,裏面有詳細的解釋.mysql

(3)Repository

新建UserRepository去實現增刪查改:android

package com.test;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Repository
public interface UserRepository extends CrudRepository<User,Integer>
{
    @Query(value = "select * from user where name = ?1",nativeQuery = true)
    public List<User> findByName(String name);

    @Modifying
    @Query(value = "delete from user where name = ?1",nativeQuery = true)
    public int deleteByName(String name);
}

因爲CrudRepository中已經包含了"增"與"改",因此按須要實現本身的"查"與"刪"便可. CrudRepository的api很簡單,官方文檔在這裏.git

  • "增"使用save便可,參數爲實體類
  • "刪"使用deleteById,經過主鍵刪除,若不想經過主鍵刪除能夠本身編寫sql,像上面同樣
  • "查"使用findAll或findById,自定義查找的話須要本身編寫sql.
  • "改"也可以使用save,注意須要設置主鍵.

@Query用於設置sql,nativeQuery表示使用原生sql.github

(4)Service

新建一個MainService.javaweb

package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Transactional
@Service
public class MainService {
    @Autowired
    private UserRepository userRepository;

    public Iterable<User> getAllUsers()
    {
        return userRepository.findAll();
    }

    public List<User> findByName(String name)
    {
        return userRepository.findByName(name);
    }

    public boolean add(String name)
    {
        User user = new User();
        user.setName(name);
        userRepository.save(user);
		return true;
    }

    public boolean modify(Integer id,String name)
    {
        User user = new User();
        user.setName(name);
        user.setId(id);
        userRepository.save(user);
        return true;
    }

    public boolean deleteByName(String name)
    {
        return userRepository.deleteByName(name) != 0;
    }
}
  • getAllUsers()返回全部行,Iterable<E>類型
  • findByName()根據name返回全部name相同的行.
  • add直接使用了save,因爲save返回的是實體類,本來的代碼是這樣寫的:
return userRepository.save(user) != null;

在這裏插入圖片描述

可是文檔說了不會爲null,因此只能強制返回true了.spring

  • modify使用了id與name做爲參數,新建一個user,將其做爲setter的參數,而後交給save.
  • deleteByName使用了自定義的刪除函數,返回的是int,在UserRepository中這個int表明sql影響的行數,刪除成功則行數不爲0,刪除失敗,或者沒有這行數據則行數爲0.所以將返回值與0進行比較.

(5)Controller

package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping(path = "/demo")
public class MainController {
    @Autowired
    private MainService mainService;

    @GetMapping(path = "/getAll")
    public @ResponseBody Iterable<User> getAllUsers()
    {
        return mainService.getAllUsers();
    }

    @PostMapping(path = "/get")
    public @ResponseBody List<User> findByName(String name)
    {
        return mainService.findByName(name);
    }

    @PostMapping(path = "/add")
    public @ResponseBody boolean add(@RequestParam String name)
    {
        return mainService.add(name);
    }

    @PostMapping(path = "/modify")
    public @ResponseBody boolean modify(@RequestParam Integer id,@RequestParam String name)
    {
        return mainService.modify(id,name);
    }

    @PostMapping(path = "/delete")
    public @ResponseBody boolean deleteByName(@RequestParam String name)
    {
        return mainService.deleteByName(name);
    }
}

Controller主要就是幾個註解,除了getAllUsers使用Get外,其餘的都是用Post.另外就是路徑設置,直接在path中設置便可. 後端的話到這裏就基本完成了,剩下的打包部署操做就.....sql

4.前端

什麼新建工程之類的就不說了. 直接上MainActivity:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.example.myapplication.model.dao.*;
import com.example.myapplication.model.entity.*;

import java.io.IOException;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button register = findViewById(R.id.register);
        register.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        FormBody formBody = new FormBody.Builder().add("name", name).build();
                        Request request = new Request.Builder()
                                .url(Constant.ADD)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            Looper.prepare();
                            if (Boolean.parseBoolean(response.body().string()))
                            {
                                Toast.makeText(this, "註冊成功", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "註冊失敗", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );
        Button login = findViewById(R.id.login);
        login.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        FormBody formBody = new FormBody.Builder().add("name", name).build();
                        Request request = new Request.Builder()
                                .url(Constant.GET)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            List<User> users = JSONArray.parseArray(response.body().string(),User.class);
                            Looper.prepare();
                            if(users.size() == 0)
                            {
                                Toast.makeText(this,"登陸失敗",Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this,"登陸成功",Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );

        Button delete = findViewById(R.id.delete);
        delete.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        FormBody formBody = new FormBody.Builder().add("name", name).build();
                        Request request = new Request.Builder()
                                .url(Constant.DELETE)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            Looper.prepare();
                            if (Boolean.parseBoolean(response.body().string()))
                            {
                                Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "刪除失敗", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );

        Button modify = findViewById(R.id.modify);
        modify.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        String id = ((EditText)findViewById(R.id.id)).getText().toString();
                        FormBody formBody = new FormBody.Builder()
                                .add("name", name)
                                .add("id",id)
                                .build();
                        Request request = new Request.Builder()
                                .url(Constant.MODIFY)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            Looper.prepare();
                            if (Boolean.parseBoolean(response.body().string()))
                            {
                                Toast.makeText(this, "修改爲功", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "修改失敗", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );
    }
}

(1)增

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.ADD)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this, "註冊成功", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "註冊失敗", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

使用okhttp,經過FormBody設置參數,而後建立Request經過OkHttpClient發送. 因爲後端"增"的方法返回的是一個true,所以這裏將response.body().string()轉換成boolean判斷是否操做成功. 稍微提一下,

Looper.prepare();
Looper.loop();

這兩行能夠在非UI線程中使用Toast.

(2)刪

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.DELETE)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "刪除失敗", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

刪這部分也是差很少的,就是改一下url,而後....而後沒有了....好像很簡單的樣子?

(3)查

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.GET)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    List<User> users = JSONArray.parseArray(response.body().string(),User.class);
    Looper.prepare();
    if(users.size() == 0)
    {
        Toast.makeText(this,"登陸失敗",Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this,"登陸成功",Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

查這裏注意一下後端返回的是List,這裏藉助阿里的fastjson轉換成List.

List<User> users = JSONArray.parseArray(response.body().string(),User.class);

而後判斷有沒有的話就判斷長度是否爲0便可.

(4)改

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
String id = ((EditText)findViewById(R.id.id)).getText().toString();
FormBody formBody = new FormBody.Builder()
        .add("name", name)
        .add("id",id)
        .build();
Request request = new Request.Builder()
        .url(Constant.MODIFY)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this, "修改爲功", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "修改失敗", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

改的話只需一個額外的ID參數,在FormBody中add一個便可,不難.

(5)界面

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="280dp"
        android:layout_marginTop="404dp"
        android:text="刪除"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="293dp"
        android:text="註冊"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/modify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="404dp"
        android:text="修改"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/name"
        android:layout_width="336dp"
        android:layout_height="50dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="192dp"
        android:layout_marginEnd="43dp"
        android:ems="10"
        android:hint="請輸入姓名"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/id"
        android:layout_width="336dp"
        android:layout_height="50dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="112dp"
        android:layout_marginEnd="43dp"
        android:ems="10"
        android:hint="請輸入id"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="293dp"
        android:layout_marginEnd="43dp"
        android:text="登陸"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

界面不詳細說了,不難.

(6)依賴與其餘

在這裏插入圖片描述

注意一下依賴,還有設置java8.

(7)網絡權限

這個做者以前的文章有說.

請看這裏.

5.測試

這是"本來的"數據庫. 沒辦法爲了測試.

在這裏插入圖片描述

註冊一個.

在這裏插入圖片描述

看看數據庫:

在這裏插入圖片描述

在這裏插入圖片描述

試試登陸一個不存在的.

在這裏插入圖片描述

修改:

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

最後是刪除:

在這裏插入圖片描述

在這裏插入圖片描述

刪除一個不存在的會刪除失敗.

在這裏插入圖片描述

6.源碼

相關文章
相關標籤/搜索