foreword
The spring boot project construction of sub-modules has been completed before, and now I start to join the database. The data I use here is mysql, and the dao layer framework is also the more commonly used mybatis.
1. Add dependencies to pom
Add mysql
mybatis
dependencies to the pom, add the following dependencies to the main pom file, and import them in the required sub-pom
<!--数据库及mybatis依赖 begin-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connect-java-version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${spring-mybatis-verison}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>${spring-mybatis-verison}</version>
</dependency>
<!--数据库及mybatis依赖 end-->
2, application.properties add database configuration
application.properties
The configuration file loaded by default for spring boot, the default path is
resources/application.properties
Add mysql related configuration to the configuration file
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=admin
spring.datasource.password=12345
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3. Add mapper scan package configuration to startup class
Add mapper scan package configuration to spring boot startup class
@SpringBootApplication(scanBasePackages = "com.clockbone")
@MapperScan("com.clockbone.dao")
public class ApplicationBoot {
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationBoot.class, args);
}
}
4, mapper class
@Mapper
public interface UserMapper {
@Select("SELECT ID,USER_ID as userId,USER_NAME as userName FROM USER where id=#{id}")
User getUserInfo(long id);
}
5. Test class
@Service(value = "userService")
@Slf4j
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User getUserInfo(Long id) {
return userMapper.getUserInfo(id);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ApplicationBoot.class, //启动类
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class ApplicationBaseBootTest{
@Resource
private UserService userService;
@Test
public void userServiceTest(){
long id = 10;
User user = userService.getUserInfo(id);
System.out.println(user);
}
}