首先创建maven项目
pom.xml
<!-- web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 模板引擎--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- mysql驱动 默认8.0--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- yaml使用有提示--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- mybatis plus整合(不用导入mybatis了里面自带)--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency>
创建application.yaml
#配置数据源 spring: datasource: url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver
1.创建pojo类
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "user")
public class tUser {
private int id;
private String name;
private int age;
private String email;
}
2.创建mapper类继承BaseMapper就可以获得封装好的CRUD加上@mapper注解不然扫描不到
@Mapper
public interface UserMapper extends BaseMapper<tUser> {
}
3.创建service业务层(继承IService<tUser>获取CRUD)
* Mybatis plus CRUD
*/
public interface Userservice extends IService<tUser> {
}
4.实现service代码()
继承extends ServiceImpl<T, T>
第一个填使用的Mapper
第二个填实现的实现类pojo
@Service
public class Userserviceimpl extends ServiceImpl<UserMapper, tUser> implements Userservice {
}
源码:
5.控制器调用封装好的底层代码使用就可以了
@Controller
public class CRUDpage {
@Autowired
Userservice userservice;
@GetMapping("/dynamic_table")
public String dynamic_tablePage(Model model) {
List<tUser> list = userservice.list();
model.addAttribute("users",list);
return "table/dynamic_table";
}
@GetMapping("/del/{id}")
public String del(@PathVariable(value = "id",required = false) Integer id) {
userservice.removeById(id);
return "redirect:/dynamic_table";
}
}
遍历数据库的数据这里用的thymeleaf模板引擎
创建html页面
<table class="display table table-bordered table-striped" id="dynamic-table"> <thead> <tr> <th>Rendering engine</th> <th>Browser</th> <th>Platform(s)</th> <th class="hidden-phone">Engine version</th> <th class="hidden-phone">CSS grade</th> </tr> </thead> <tbody> <tr th:each="user,stats:${users}"> <td th:text="${stats.count}"></td> <td th:text="${user.getId()}"></td> <td th:text="${user.getName()}"></td> <td th:text="${user.getAge()}"></td> <td th:text="${user.getEmail()}"></td> <td> <a th:href="@{/del/{id}(id=${user.getId()})}">删除</a> </td> </tr> </tbody> </table>
页面遍历