springboot整合mybatis和vue实现增删改查案例
时间: 2023-11-12 07:56:46 浏览: 182
好的,以下是一个Spring Boot整合MyBatis和Vue实现增删改查的案例:
1. 前端Vue部分
首先,我们在前面创建的`vue-mybatis-demo`项目中添加四个组件,分别用于展示用户列表、添加用户、编辑用户和删除用户。以下是这四个组件的代码:
**UserList.vue**
```html
<template>
<div>
<h2>User List</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>
<button @click="editUser(user)">Edit</button>
<button @click="deleteUser(user)">Delete</button>
</td>
</tr>
</tbody>
</table>
<button @click="addUser">Add User</button>
<router-link to="/">Back to Home</router-link>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
users: []
}
},
mounted() {
axios.get('/api/users')
.then(response => {
this.users = response.data;
})
.catch(error => {
console.log(error);
});
},
methods: {
addUser() {
this.$router.push('/add');
},
editUser(user) {
this.$router.push({ name: 'edit', params: { id: user.id } });
},
deleteUser(user) {
axios.delete(`/api/users/${user.id}`)
.then(response => {
this.users = this.users.filter(u => u.id !== user.id);
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
```
**AddUser.vue**
```html
<template>
<div>
<h2>Add User</h2>
<form @submit.prevent="submitForm">
<div>
<label>Name:</label>
<input v-model="user.name">
</div>
<div>
<label>Age:</label>
<input v-model.number="user.age">
</div>
<button type="submit">Save</button>
<router-link to="/users">Cancel</router-link>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
user: {
name: '',
age: ''
}
}
},
methods: {
submitForm() {
axios.post('/api/users', this.user)
.then(response => {
this.$router.push('/users');
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
```
**EditUser.vue**
```html
<template>
<div>
<h2>Edit User - {{ user.name }}</h2>
<form @submit.prevent="submitForm">
<div>
<label>Name:</label>
<input v-model="user.name">
</div>
<div>
<label>Age:</label>
<input v-model.number="user.age">
</div>
<button type="submit">Save</button>
<router-link to="/users">Cancel</router-link>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
user: {}
}
},
created() {
axios.get(`/api/users/${this.$route.params.id}`)
.then(response => {
this.user = response.data;
})
.catch(error => {
console.log(error);
});
},
methods: {
submitForm() {
axios.put(`/api/users/${this.user.id}`, this.user)
.then(response => {
this.$router.push('/users');
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
```
**DeleteUser.vue**
```html
<template>
<div>
<h2>Delete User</h2>
<p>Are you sure you want to delete {{ user.name }}?</p>
<button @click="deleteUser">Yes</button>
<router-link to="/users">No</router-link>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
user: {}
}
},
created() {
axios.get(`/api/users/${this.$route.params.id}`)
.then(response => {
this.user = response.data;
})
.catch(error => {
console.log(error);
});
},
methods: {
deleteUser() {
axios.delete(`/api/users/${this.user.id}`)
.then(response => {
this.$router.push('/users');
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
```
2. 后端Spring Boot部分
我们需要在前面的Spring Boot项目中添加一些代码,以支持从前端发送的HTTP请求。
首先,我们需要修改`UserMapper`接口和对应的XML文件,以支持添加、修改和删除用户:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> findAll();
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void save(User user);
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void deleteById(Long id);
}
```
```xml
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="findAll" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
<insert id="save" parameterType="com.example.demo.entity.User">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
<select id="findById" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
<update id="update" parameterType="com.example.demo.entity.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteById">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
```
然后,我们创建一个`UserController`类,用于处理从前端发送的请求:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users")
public List<User> findAllUsers() {
return userMapper.findAll();
}
@PostMapping("/users")
public void addUser(@RequestBody User user) {
userMapper.save(user);
}
@GetMapping("/users/{id}")
public User findUserById(@PathVariable Long id) {
return userMapper.findById(id);
}
@PutMapping("/users/{id}")
public void updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
userMapper.update(user);
}
@DeleteMapping("/users/{id}")
public void deleteUserById(@PathVariable Long id) {
userMapper.deleteById(id);
}
}
```
3. 整合前后端
现在,我们需要将前端Vue项目打包并将其静态文件放入Spring Boot项目的`resources/static`目录下。在`vue-mybatis-demo`目录下执行以下命令:
```
npm run build
```
这将生成一个`dist`目录,其中包含前端Vue项目的静态文件。将该目录下的所有文件复制到Spring Boot项目的`resources/static`目录下。
最后,我们启动Spring Boot应用程序,并在浏览器中访问`http://localhost:8080`,即可看到从数据库中获取的用户列表。我们可以添加、编辑和删除用户,并且这些操作将自动更新数据库中的数据。
阅读全文