spring boot 集成mybatis

2018-02-03 10:36:13来源:oschina作者:chenbaojun人点击

分享
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
springws
springws
1.0-SNAPSHOT

org.springframework.boot
spring-boot-starter-parent
1.5.3.RELEASE



UTF-8
UTF-8
1.8



org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-devtools
runtime




mysql
mysql-connector-java
runtime



org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1




org.springframework.boot
spring-boot-maven-plugin



创建App.java
package com.ws;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class App {
public static void main(String ... args){
SpringApplication.run(App.class,args);
}
}
创建bean
package com.ws.bean;
public class Course{
//对应的表的字段
private Integer id;

private String name;

private Integer uid;

private String code;

private Long time;
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 getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
@Override
public String toString() {
return "Course [id=" + id + ", name=" + name + ", uid=" + uid + ", code=" + code + ", time=" + time + "]";
}

}创建DAO
package com.ws.repository;
import com.ws.bean.Course;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("courseDao")
@Mapper
public interface CourseDao {
@Select("select * from ccvms_course where id = #{id} ")
List findById(@Param("id") Integer id);
}@Mapper注解必须是1.1.1版本以上的mybatis-spring-boot-starter才有
创建测试的controller
package com.ws.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ws.bean.Course;
import com.ws.repository.CourseDao;@RestController
public class IndexController {

private final CourseDao courseDao;
@Autowired
public IndexController(CourseDao courseDao) {
this.courseDao = courseDao;
}
@GetMapping("/")
public List index(){
return courseDao.findById(10);
}
}

微信扫一扫

第七城市微信公众平台