實施前的準備工作:
- 1.準備數據庫表
- 2.創建一個新的springboot工程,選擇引入對應的起步依賴(mybatis、mysql驅動、lombok)
- 3.在application.properties文件中引入數據庫連接信息
- 4.創建對應的實體類Emp(實體類屬性采用駝峰命名)
- 5.準備Mapper接口:EmpMapper
- 6.測試
1.準備數據庫表
-- 員工管理
create table emp
(id int unsigned primary key auto_increment comment 'ID',username varchar(20) not null unique comment '用戶名',password varchar(32) default '123456' comment '密碼',name varchar(10) not null comment '姓名',gender tinyint unsigned not null comment '性別, 說明: 1 男, 2 女',image varchar(300) comment '圖像',job tinyint unsigned comment '職位, 說明: 1 班主任,2 講師, 3 學工主管, 4 教研主管, 5 咨詢師',entrydate date comment '入職時間',dept_id int unsigned comment '部門ID',create_time datetime not null comment '創建時間',update_time datetime not null comment '修改時間'
) comment '員工表';
-- 員工表測試數據
INSERT INTO emp (id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time)
VALUES
(1, 'jinyong', '123456', '金庸', 1, '1.jpg', 4, '2000-01-01', 2, now(), now()),
(2, 'zhangwuji', '123456', '張無忌', 1, '2.jpg', 2, '2015-01-01', 2, now(), now()),
2.創建一個新的springboot工程,選擇引入對應的起步依賴(mybatis、mysql驅動、lombok)
3.在application.properties文件中引入數據庫連接信息
#驅動類名稱
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#數據庫連接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#連接數據庫的用戶名
spring.datasource.username=root
#連接數據庫的密碼
spring.datasource.password=123
#日志輸出
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4.創建對應的實體類Emp(實體類屬性采用駝峰命名)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {private Integer id;private String username;private String password;private String name;private Short gender;private String image;private Short job;private LocalDate entrydate; //LocalDate類型對應數據表中的date類型private Integer deptId;private LocalDateTime createTime;//LocalDateTime類型對應數據表中的datetime類型private LocalDateTime updateTime;
}
5.準備Mapper接口:EmpMapper
/*@Mapper注解:表示當前接口為mybatis中的Mapper接口程序運行時會自動創建接口的實現類對象(代理對象),并交給Spring的IOC容器管理
*/
@Mapper
public interface EmpMapper {//使用#{key}方式獲取方法中的參數值@Delete("delete from emp where id = #{id}")public void delete(Integer id);}
6.測試
在單元測試類中通過@Autowired注解注入EmpMapper類型對象
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {@Autowired //從Spring的IOC容器中,獲取類型是EmpMapper的對象并注入private EmpMapper empMapper;@Testpublic void testDel(){//調用刪除方法empMapper.delete(1);}}