一、创建Spring Boot 项目
在IntelliJ IDEA新建一个Spring Boot项目:
然后在pom.xml可以看到已经有Mybatis和MySql Connector的依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
二、application.properties添加配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
大致上配置完成,接下来有两种开发方式:
1.注解
三、添加注解
在启动类添加MapperScan注解指定mapper包:
@MapperScan("com.null01.mapper")
@SpringBootApplication
public class MybatistestApplication {
public static void main(String[] args) {
SpringApplication.run(MybatistestApplication.class, args);
}
}
四、编写实体类
public class Hotel {
private Long id;
private String hotelName;
private String address;
public Long getId() {
return id;
}
public String getHotelName() {
return hotelName;
}
public String getAddress() {
return address;
}
public void setId(Long id) {
this.id = id;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public void setAddress(String address) {
this.address = address;
}
}
五、编写Mapper接口
public interface SalariesMapper {
@Select("SELECT * FROM hotel")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "hotelName", column = "hotel_name"),
@Result(property = "address", column = "address"),
})
List<Hotel> getAll();
}
六、编写测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatistestApplicationTests {
@Autowired
private HotelMapper hotelMapper;
@Test
public void contextLoads() {
List<Hotel> hotelList = hotelMapper.getAll();
for(Hotel hotel:hotelList){
System.out.println(hotel);
}
}
}
2.xml配置
三、application.properties增加两项配置
指定两种xml配置文件的存放地址
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml
四、mybatis-config.xml
总配置文件,用于配置数据源、事务管理器和mapper配置文件的地址,由于基本上都在application.properties里配了,现在暂时没什么用
<?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></configuration>
五、/mapper/*.xml
mapper配置,sql和映射关系就是写在里面的
<?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.null01.mapper.HotelMapper">
<resultMap id="Hotel" type="com.null01.entity.Hotel" >
<id column="id" property="id"/>
<result column="hotel_name" property="hotelName"/>
<result column="address" property="address"/>
</resultMap>
<select id="getAll" resultMap="Hotel" >
SELECT * FROM hotel
</select>
</mapper>
六、实体类和mapper接口
这两个还是需要,实体类和注解方式的一样,mapper去掉注解
@Mapper
public interface HotelMapper {
List<Hotel> getAll();
}
七、测试类
可以沿用注解方式的测试类。至此,两种方式都搭通了。