springboot项目案例
时间: 2023-10-12 19:59:24 浏览: 87
以下是一个简单的Spring Boot项目案例,它可以实现用户的增删改查功能:
1. 创建一个Spring Boot项目,可以使用Spring Initializr或者直接手动创建项目。
2. 在pom.xml文件中添加以下依赖:
```xml
<dependencies>
<!-- Spring Boot Web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot JDBC依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- MySQL数据库驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot Test依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
3. 创建一个用户实体类User.java:
```java
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// getters and setters
}
```
4. 创建一个用户数据访问对象UserDAO.java:
```java
@Repository
public class UserDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> findAll() {
List<User> users = jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
return users;
}
public User findById(Long id) {
User user = jdbcTemplate.queryForObject("select * from user where id=?", new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
return user;
}
public int insert(User user) {
int count = jdbcTemplate.update("insert into user(name, age, email) values(?, ?, ?)", user.getName(), user.getAge(), user.getEmail());
return count;
}
public int update(User user) {
int count = jdbcTemplate.update("update user set name=?, age=?, email=? where id=?", user.getName(), user.getAge(), user.getEmail(), user.getId());
return count;
}
public int deleteById(Long id) {
int count = jdbcTemplate.update("delete from user where id=?", id);
return count;
}
}
```
5. 创建一个用户控制器类UserController.java:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserDAO userDAO;
@GetMapping
public List<User> findAll() {
return userDAO.findAll();
}
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userDAO.findById(id);
}
@PostMapping
public int insert(@RequestBody User user) {
return userDAO.insert(user);
}
@PutMapping("/{id}")
public int update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userDAO.update(user);
}
@DeleteMapping("/{id}")
public int deleteById(@PathVariable Long id) {
return userDAO.deleteById(id);
}
}
```
6. 运行项目,访问http://localhost:8080/user即可查看所有用户信息,也可以使用POST、PUT、DELETE请求来增加、修改、删除用户信息。
阅读全文