- 一、创建一张数据库表
- 二、创建实体类User
- 三、添加依赖
- 四、在application.yml 文件中添加数据库相关配置
- 五、在spring-boot启动类中添加注解
- 六、编写Mapper接口(userMapper)
- 七、编写service层
- 八、编写Controller
- 九、简单的测试页面(使用themleaf模板引擎)
- 十、测试
CREATE TABLE `user`(
`id` INT(10) AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(30) NOT NULL,
`age` INT(10) NOT NULL,
`email` VARCHAR(50) NOT NULL
);
# 添加数据
INSERT INTO USER(NAME,age,email) VALUES
('Jone',18,'test1@taobao,com'),
('Jack',19,'test2@taobao.com'),
('Tom',28,'test3@baidu.com'),
('Sandy',21,'test4@alibaba.com'),
('Mae',24,'mae814@aliyun.com');
二、创建实体类User
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User(int id, String name, int age, String email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}
@TableField(exist = false)
private String username;
@TableField(exist = false)
private String password;
private int id;
private String name;
private int age;
private String email;
}
三、添加依赖
四、在application.yml 文件中添加数据库相关配置com.baomidou mybatis-plus-boot-starter 3.4.3.4
数据源使用的是德鲁伊
spring:
datasource:
druid:
# 监控页的配置
stat-view-servlet:
enabled: true
login-username: admin
login-password: 123456
reset-enable: false
# 监控web应用
web-stat-filter:
enabled: true
# url-pattern:
# exclusions:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/book?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username: root
password: 123456
# 监控防火墙
# proxy-filters: stat,wall,slf4j
五、在spring-boot启动类中添加注解
扫描 mapper 文件夹
@SpringBootApplication
@MapperScan("com.atmae.springboot_demo2.mapper")
public class SpringbootDemo2Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemo2Application.class, args);
}
}
六、编写Mapper接口(userMapper)
public interface UserMapper extends baseMapper七、编写service层{ }
1、userService接口
public interface UserService extends IService{ }
2、其实现类
注意:一定要添加Service注解
@Service public class UserServiceImpl extends ServiceImpl八、编写Controllerimplements UserService { }
@Controller
public class TestController {
@Resource
private UserService userService;
@GetMapping("/test")
public String testQuery(Model model){
List users=userService.list();
model.addAttribute("users0",users);
return "test";
}
}
九、简单的测试页面(使用themleaf模板引擎)
Test
| # | id | name | age | |
|---|---|---|---|---|
| Trident | Trident |



