1.导入依赖
这里的数据源我用的是druid
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
<scope>compile</scope>
</dependency>
2.在appllication.yaml/properties配置文件中配置数据源
spring:
datasource:
username: root
password: xxxx
url: jdbc:mysql://localhost:3306/ssm_project
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
3.创建对应的实体类以及Mapper类
public class User {
String username;
String password;
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
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;
}
}
/**
* @Mapper会报红
*/
@Repository
public interface UserMapper {
@Select("select username,password from users")
public List<User> findAll();
}
4.写一个配置类,指定数据源
@Configuration
public class MybatisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
}
并在启动器类中配置MapperScan注解,扫描自己所有的mapper接口
@SpringBootApplication
@MapperScan(value = "springboot_learning.springboot01.Mapper")
public class Springboot01Application {
public static void main(String[] args) {
SpringApplication.run(Springboot01Application.class, args);
}
}
5.测试
创建controller
@RestController
public class LoginController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/user/findAll")
public List<User> findAll(){
List<User> users = userMapper.findAll();
return users;
}
}