1.为什么要用Mybaits-plus?
你连sql增删改查语句都不用写,人家都写好了,只能说真香。
2.整合Mybaits-plus
(1)勾选Mybaits-plus,以及mysql 驱动
(2)在配置文件中修改数据库配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/boot_zhaopin?serverTimezone=UTC
username: root
password: root
(3)写实体类
public class User { private Integer id; private String username; private String password; private String answer1; private String answer2; @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", answer1='" + answer1 + '\'' + ", answer2='" + answer2 + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAnswer1() { return answer1; } public void setAnswer1(String answer1) { this.answer1 = answer1; } public String getAnswer2() { return answer2; } public void setAnswer2(String answer2) { this.answer2 = answer2; } }
(4)定义数据层接口与映射配置,继承BaseMapper(里面增删改查语句都写好了直接用就行)
@Mapper
public interface UserDao extends BaseMapper<User> {
}
(5)测试一下
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
System.out.println(userDao.selectById(1));
System.out.println(userDao.selectList(null));
}
}
测试结果:
User{id=1, username='admin', password='e10adc3949ba59abbe56e057f20f883e', answer1='12', answer2='12'}
[User{id=1, username='admin', password='e10adc3949ba59abbe56e057f20f883e', answer1='12', answer2='12'}, User{id=3, username='111', password='b0baee9d279d34fa1dfd71aadb908c3f', answer1='', answer2=''}, User{id=6, username='bai', password='b0baee9d279d34fa1dfd71aadb908c3f', answer1='', answer2=''}]