Back-end spring boot+front-end Android interaction+mysql add-delete-delete-change

Posted by mooshuligan on Tue, 26 Nov 2019 22:14:26 +0100

1. Overview

Using spring boot as the back-end framework to interact with mysql on Android, including the most basic add-delete and change functions.

2. Development environment

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

3. Backend

(1) Create a new spring boot project

You can see here

(2)Entity

Create a new User class as an entity class:

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;
    }
}

The code in (1) is actually used here, with detailed explanations.

(3)Repository

Create a new UserRepository to add, delete, and delete changes:

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);
}

Since CrudRepository already contains "add" and "change", you can "check" and "delete" as needed. CrudRepository's api is simple, The official documents are here.

  • Add uses save with entity class as parameter
  • Delete uses deleteById to delete by the primary key. If you don't want to delete by the primary key, you can write your own sql, just like above
  • Find uses findAll or findById, and you need to write your own sql if you want to customize your search.
  • save is also available for Change, note that the primary key needs to be set.

@Query is used to set sql, and nativeQuery means using native sql.

(4)Service

Create a new MainService.java

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() returns all rows, Iterable<E>type
  • findByName() returns all rows with the same name based on the name.
  • add uses save directly, since save returns an entity class, the original code is written as follows:
return userRepository.save(user) != null;

But the document says it won't be null, so it's forced to return true.

  • modify takes id and name as parameters, creates a new user, takes it as a setter parameter, and gives it to save.
  • deleteByName uses a custom delete function that returns an int that represents the number of rows affected by sql in the UserRepository. Successful deletion means no zero rows, failed deletion, or 0 rows without this row of data. Therefore, the return value is compared with 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 is mainly a few notes, except getAllUsers use Get, others use Post. The other is the path setting, set directly in the path. The backend is almost finished here, and the rest of the packaged deployment operations are...

4. Front End

Say nothing about new projects. Go directly to 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, "login was successful", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "login has failed", 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,"Logon Failure",Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this,"Login Successful",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, "Delete succeeded", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "Delete failed", 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, "Successful modification", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "Modification failed", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );
    }
}

(1) Increase

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, "login was successful", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "login has failed", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

Use okhttp, set parameters through FormBody, and create Request to send via OkHttpClient. Since the back-end Add method returns a true value, here the response.body().string() is converted to boolean to determine if the operation was successful. To mention a little,

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

These two lines can use Toast in non-UI threads.

(2) Delete

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, "Delete succeeded", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "Delete failed", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

It's almost the same to delete this part, just change the url, and then.... And then no more.... It looks so simple?

(3) Check

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,"Logon Failure",Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this,"Login Successful",Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

Check here to note that the backend returns List, which is converted to List with Ali's fastjson.

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

Then decide if there is one, and then decide if the length is 0.

(4) Change

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, "Successful modification", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "Modification failed", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

If you change it, you only need one additional ID parameter, and it's easy to add one in FormBody.

(5) Interface

<?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="delete"
        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="register"
        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="modify"
        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="Please enter your name"
        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="Please enter 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="Sign in"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The interface is not too detailed, it's not difficult.

(6) Dependency and others

Note the dependencies, and also set up java8.

(7) Network privileges

The author said in his previous article.

Look here.

5. Testing

This is the "original" database. There's no way to test it.

Register one.

Look at the database:

Try logging in to a nonexistent one.

Modify:

Finally, delete:

Deleting a nonexistent will fail.

6. Source Code

Topics: Mobile Android Java SQL Spring