您的位置:首页 > 编程语言 > Java开发

springboot整合mybatis

2017-08-02 21:23 507 查看
参考:catoophttp://blog.csdn.net/catoop/article/details/50553714

官方示例:https://github.com/mybatis/spring-boot-starter

基于XML方式整合mybatis

1.添加mybatis依赖

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>

2.创建一个entity包,用来存放实体类Student
public class Student implements Serializable {
private Integer id;

private String name;

private Integer age;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}
3.创建一个mapper包,存放StudentMapper.java,里面包含一个根据ID获取Student的方法
@Mapper
public interface StudentMapper{
public Student getStudentById(int id);
}


4.由于springboot的资源文件或配置文件都在resource中,所以在resource目录下创建StudentMapper.java对应的mapper XML文件StudentMapper.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.springboot.mapper.StudentMapper">

<resultMap id="studentMap" type="Student">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
</resultMap>

<!--id与对应的mapper.java中的方法名要一致-->
<select id="getStudentById" resultType="Student" parameterType="int">
SELECT *
FROM STUDENT
WHERE ID = #{id}
</select>

</mapper>
StudentMapper.xml所在包的路径应与StudentMapper.java的包路径一致



5.resource中创建mybatis的配置文件,添加映射

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.springboot.entity"/>
</typeAliases>
<mappers>
<mapper resource="com/springboot/mapper/StudentMapper.xml"/>
</mappers>
</configuration>然后在application.yml文件中,引用mybatis的配置文件
mybatis.config-location: classpath:mybatis-config.xml

6.单元测试
application.xml数据库配置如下:

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/db_test
username: root
password: root
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {

@Autowired
private StudentMapper studentMapper;

@Test
public void contextLoads() {
Student student=studentMapper.getStudentById(3);
System.out.println(student.getName());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: