使用springboot框架,mybatis,maven写一个一对多的crud事例
时间: 2023-02-22 09:55:00 浏览: 105
Spring Boot整合Mybatis并完成CRUD操作的实现示例
好的,我来给你写一个使用 springboot 框架、mybatis、maven 的一对多 CRUD 示例。
首先,需要在 pom.xml 中声明 springboot 和 mybatis 的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
```
然后,可以定义两个实体类,一个是 Department,表示部门,另一个是 Employee,表示员工:
```
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
}
```
接着,创建 DepartmentMapper 和 EmployeeMapper 接口:
```
public interface DepartmentMapper {
@Insert("INSERT INTO department(name) VALUES(#{name})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(Department department);
@Update("UPDATE department SET name = #{name} WHERE id = #{id}")
void update(Department department);
@Delete("DELETE FROM department WHERE id = #{id}")
void delete(Long id);
@Select("SELECT * FROM department WHERE id = #{id}")
Department select(Long id);
@Select("SELECT * FROM department")
List<Department> selectAll();
}
public interface EmployeeMapper {
@Insert("INSERT INTO employee(name, department_id) VALUES(#{name}, #{department.id})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(Employee employee);
@Update("UPDATE employee SET name = #{name}, department_id = #{department.id} WHERE id = #{id}")
void update(Employee employee);
@Delete("DELETE FROM employee WHERE id = #{
阅读全文