1.所需技术及作用
(1)spring web
(2)mybatis-plus:你连sql增删改查语句都不用写,人家都写好了,只能说真香。
(3)lombok:简化实体类开发(自动生成get和set方法,toString方法,hashcode方法,equals方法)
(4)mysql driver:mysql驱动
(5)durid:目前最高效的数据库连接池
2.整合SSMP
(1)勾选所需技术(durid不在所选技术中,需要自行引入在pom.xml)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
(2)修改配置文件application.yml
spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/boot_zhaopin?serverTimezone=UTC username: root password: sgf123 server: port: 80 # 设置id的类型为自动,不然当通过id查询或者修改数据时,会报错 mybatis-plus: global-config: db-config: id-type: AUTO
# 设置日志为标准模式,即在控制台输出mybatis执行的所有过程。以后输出就不用print了
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
(3)为数据库添加实体类和接口(@Data为我们自动生成了get/set方法,BaseMapper<User> 自动生成了增删改查。)
// 实体类
import lombok.Data;
// 通过@Data注解,简化get/set操作 @Data public class User { private Integer id; private String username; private String password; }
// 实现接口
// 通过使用MybatisPlus继承BaseMapper<实体类名>,自动生成增删改查以及分页设置。 // 通过@Mapper声明它是一个Mapper @Mapper public interface UserMapper extends BaseMapper<User> { }
(4)掉用接口实现增删改查,以及分页
@SpringBootTest class SbSsmApplicationTests {
// 自动装配UserMapper接口,使得可以调用UserMapper接口内的方法。 @Autowired private UserMapper userMapper;
// 查询所有,注意参数为null @Test void testSelectAll() { System.out.println(userMapper.selectList(null)); }
// 插入数据,需要传入的参数为实体类对象,通过set方法设置需要插入的值。 @Test void testSave() { User user = new User(); user.setUsername("李白"); user.setPassword("11111111"); userMapper.insert(user); System.out.println("插入成功"); } // 数据删除 @Test void textDelete() { userMapper.deleteById(3); System.out.println("删除成功"); }
// 修改数据,所需传入数据为实体类对象,通过set方法设置需要修改的值。 @Test void testUpdate() { User user = new User(); user.setId(4); user.setUsername("杜甫"); userMapper.updateById(user); System.out.println("修改成功"); } // 分页 @Test void testGetPage(){ IPage page =new Page(1,3); userMapper.selectPage(page,null); // System.out.println(page.getRecords()); } }
分页时还需添加拦截器,
@Configuration
public class MPConfig {
@Bean
// 创建拦截器
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加具体的拦截器
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}