使用spring boot作為后端框架與Android端配合MySQL進(jìn)行基本的交互,包含了最基本的增刪查改功能.
達(dá)孜網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、APP開(kāi)發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開(kāi)發(fā),運(yùn)營(yíng)維護(hù)。創(chuàng)新互聯(lián)公司從2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專(zhuān)注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。
可以看這里
新建User類(lèi)作為實(shí)體類(lèi):
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;
}
}
這里其實(shí)使用的是(1)中的代碼,里面有詳細(xì)的解釋.
新建UserRepository去實(shí)現(xiàn)增刪查改:
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
{
@Query(value = "select * from user where name = ?1",nativeQuery = true)
public List findByName(String name);
@Modifying
@Query(value = "delete from user where name = ?1",nativeQuery = true)
public int deleteByName(String name);
}
由于CrudRepository中已經(jīng)包含了"增"與"改",所以按需要實(shí)現(xiàn)自己的"查"與"刪"即可.
CrudRepository的api很簡(jiǎn)單,官方文檔在這里.
@Query用于設(shè)置sql,nativeQuery表示使用原生sql.
新建一個(gè)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 getAllUsers()
{
return userRepository.findAll();
}
public List 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;
但是文檔說(shuō)了不會(huì)為null,所以只能強(qiáng)制返回true了.
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 getAllUsers()
{
return mainService.getAllUsers();
}
@PostMapping(path = "/get")
public @ResponseBody List 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主要就是幾個(gè)注解,除了getAllUsers使用Get外,其他的都是用Post.另外就是路徑設(shè)置,直接在path中設(shè)置即可.
后端的話到這里就基本完成了,剩下的打包部署操作就.....
什么新建工程之類(lèi)的就不說(shuō)了.
直接上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, "注冊(cè)成功", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "注冊(cè)失敗", 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 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, "注冊(cè)成功", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "注冊(cè)失敗", Toast.LENGTH_SHORT).show();
}
Looper.loop();
} catch (IOException e) {
e.printStackTrace();
}
使用okhttp,通過(guò)FormBody設(shè)置參數(shù),然后創(chuàng)建Request通過(guò)OkHttpClient發(fā)送.
由于后端"增"的方法返回的是一個(gè)true,因此這里將response.body().string()轉(zhuǎn)換成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,然后....然后沒(méi)有了....好像很簡(jiǎn)單的樣子?
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 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轉(zhuǎn)換成List.
List users = JSONArray.parseArray(response.body().string(),User.class);
然后判斷有沒(méi)有的話就判斷長(zhǎng)度是否為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();
}
改的話只需一個(gè)額外的ID參數(shù),在FormBody中add一個(gè)即可,不難.
界面不詳細(xì)說(shuō)了,不難.
注意一下依賴(lài),還有設(shè)置java8.
這個(gè)作者之前的文章有說(shuō).
請(qǐng)看這里.
這是"原本的"數(shù)據(jù)庫(kù).沒(méi)辦法為了測(cè)試.
注冊(cè)一個(gè).
看看數(shù)據(jù)庫(kù):
試試登錄一個(gè)不存在的.
修改:
最后是刪除:
刪除一個(gè)不存在的會(huì)刪除失敗.