Springboot中 对数据的实例映射操作的代码
时间: 2023-07-14 07:13:30 浏览: 91
Springboot 示例代码
在Spring Boot中,我们可以使用ORM框架(如Hibernate、Mybatis等)来实现数据实例的映射操作。以下是一个使用Hibernate实现数据映射的例子:
1. 创建实体类
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// getter/setter
}
```
2. 创建DAO层接口
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. 创建Service层
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public User addUser(User user) {
return userRepository.save(user);
}
public void deleteUserById(Long id) {
userRepository.deleteById(id);
}
}
```
4. 创建Controller层
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PostMapping("")
public User addUser(@RequestBody User user) {
return userService.addUser(user);
}
@DeleteMapping("/{id}")
public void deleteUserById(@PathVariable Long id) {
userService.deleteUserById(id);
}
}
```
通过以上代码,我们可以完成对数据实例的增删改查操作。
阅读全文