使用spring boot做爲後端框架與Android端配合mysql進行基本的交互,包含了最基本的增刪查改功能.html
能夠看這裏前端
新建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
新建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
@Query用於設置sql,nativeQuery表示使用原生sql.github
新建一個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; } }
return userRepository.save(user) != null;
可是文檔說了不會爲null,因此只能強制返回true了.spring
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
什麼新建工程之類的就不說了. 直接上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(); } ); } }
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.
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,而後....而後沒有了....好像很簡單的樣子?
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便可.
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一個便可,不難.
<?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>
界面不詳細說了,不難.
注意一下依賴,還有設置java8.
這個做者以前的文章有說.
這是"本來的"數據庫. 沒辦法爲了測試.
註冊一個.
看看數據庫:
試試登陸一個不存在的.
修改:
最後是刪除:
刪除一個不存在的會刪除失敗.