使用spring boot做爲後端框架與Android端配合mysql進行基本的交互,包含了最基本的增刪查改功能.html
參考這裏.java
新建User類做爲實體類:mysql
@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; } }
用的實際上是3.1連接中的代碼,裏面有詳細的解釋.git
新建UserRepository實現增刪查改:github
@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很簡單,官方文檔在這裏.spring
save
便可,參數爲實體類deleteById
,經過主鍵刪除,若不想經過主鍵刪除能夠本身編寫sql,像上面同樣findAll
或findById
,自定義查找的話須要本身編寫SQLsave
,注意須要設置主鍵@Query
用於設置SQL語句,nativeQuery
表示使用原生SQL.sql
新建一個MainService.java:數據庫
@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了.json
modify
使用了id與name做爲參數,新建一個user,將其做爲setter的參數,而後交給savedeleteByName
使用了自定義的刪除函數,返回的是int,在UserRepository中這個int表明SQL影響的行數,刪除成功則行數不爲0,刪除失敗,或者沒有這行數據則行數爲0.所以將返回值與0進行比較@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中設置便可.
後端的話到這裏就基本完成了,剩下的打包部署操做就不說了,須要的能夠參考這裏.後端
什麼新建工程之類的就不說了.
貼上部分MainActivity,完整代碼見文末:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { 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(); } //... }).start();}); 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(); } //... }).start();}); 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(); } //... }).start();}); 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(); } //... }).start();}); } }
下面分別進行CRUD操做.
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,而後....而後沒有了....好像很簡單的樣子?2333333
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一個便可,不難.
UI不詳細說了,就幾個簡單的Button,具體能夠看代碼中的xml文件.
注意一下依賴,還有設置java8.
compileOptions{ sourceCompatibility=1.8 targetCompatibility=1.8 } dependencies{ implementation 'com.squareup.okhttp3:okhttp:x.x.x' implementation 'com.alibaba:fastjson:x.x.x' }
這個筆者以前的文章有說,主要就是AndroidManifest.xml
中的權限設置,請看這裏.
原始數據庫:
註冊一個:
看看數據庫:
測試登陸:
試試登陸一個不存在的:
修改:
最後是刪除:
刪除一個不存在的會刪除失敗.
若是以爲文章好看,歡迎點贊。
同時歡迎關注微信公衆號:氷泠之路。