1 pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2 application.properties
# Mysql数据库连接配置 : com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.101.111:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true
#配置mybatis的xml映射配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置mybatis映射配置文件中实体类别名
mybatis.type-aliases-package=com.demo.pojo
3mapper
@Mapper
public interface ArticleMapper {
//根据id查询对应的文章
public Article selectArticle(Integer id);
}
此处也可以不用添加@Mapper 注解 在启动类上面添加@MapperScan
@MapperScan("com.demo.mapper")
@SpringBootApplication
public class Springboot03DataApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot03DataApplication.class, args);
}
}
4 mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo.mapper.ArticleMapper">
<select id="selectArticle" parameterType="int" resultType="article">
select * from t_article where id = #{id}
</select>
</mapper>
5 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootApplicationDemoTests {
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle(){
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}