1:配置pom.xml
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
2:datasource 配置
spring.datasource.url=jdbc:mysql://localhost:3306/blog
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3:实体
package com.mybatis.entity; /** * Created by mark on 2017/3/27. * 创建一个User实体类 */ public class User{ private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long 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; } }
4:mapper
package com.mybatis.mapper; import com.mybatis.entity.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; /** * Created by mark on 2017/3/27. * 定义一个DAO的接口 */ @Mapper public interface UserMapper { @Select("select * from user where name=#{name}") User findByName(@Param("name") String name); @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); }
5:controller
package com.mybatis.controller; import com.mybatis.entity.User; import com.mybatis.mapper.UserMapper; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * Created by mark on 2017/3/27. */ @RestController @RequestMapping("/user") public class UserController { @Autowired UserMapper userMapper; @RequestMapping("index") @ResponseBody public String index(){ User user = userMapper.findByName("mark"); return "name:"+user.getName()+" age:"+user.getAge(); } }
6:项目结构
7:编辑器配置
8:启动主程序后 http://localhost:8080/user/index 结果