1、pom.xml 添加mybatis和mysql依赖
org.mybatis.spring.boot mybatis-spring-boot-starter 1.2.0 mysql mysql-connector-java 5.1.41
2、application.properties 里面配置数据库信息
#数据库数据源配置spring.datasource.url=jdbc:mysql://localhost/demo?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=truespring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver
3、配置mybatis,有两种方式,一种用注解,一种用xml,一般习惯用XML。
- 用注解
@Mapperpublic interface UserMapper { /** * 查询所有用户 * @return */ @Select("select id,name,age FROM tb_tic_user") ListselectAll();}
public class UserDo implements Serializable{ private static final long serialVersionUID = -7488908967791971359L; private int Id; private String name; private int age; public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "UserDo{" + "Id=" + Id + ", name='" + name + '\'' + ", age=" + age + '}'; }}
@Controllerpublic class IndexController { @Autowired UserMapper userMapper; @RequestMapping("/selectAll") public @ResponseBody ListselectAll(){ return userMapper.selectAll(); }}
启动不报错,用注解配置成功,主要是在Mapper类上增加@Mapper注解,sql语句用注解放在方法上面。配置简单,但是会有重复代码,不推荐。
- 用xml配置,增加配置类用来扫描mapper接口
application.properties 中增加mybatis配置
#mybatis配置mybatis.mapper-locations=classpath:mapper/*.xmlmybatis.type-aliases-package=com.example.demo.domain
@Configuration@MapperScan(value = "com.example.demo.mapper")public class MybatisConfig {}
package com.example.demo.mapper;import com.example.demo.domain.Test;public interface TestMapper { int deleteByPrimaryKey(Integer id); int insert(Test record); int insertSelective(Test record); Test selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Test record); int updateByPrimaryKey(Test record);}
ID, NAME delete from tb_tic_test where ID = #{id,jdbcType=INTEGER} insert into tb_tic_test (ID, NAME) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) insert into tb_tic_test ID, NAME, #{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, update tb_tic_test where ID = #{id,jdbcType=INTEGER} NAME = #{name,jdbcType=VARCHAR}, update tb_tic_test set NAME = #{name,jdbcType=VARCHAR} where ID = #{id,jdbcType=INTEGER}
@Controllerpublic class IndexController { @Autowired TestMapper testMapper; @RequestMapping("/test") public @ResponseBody Test test(){ return testMapper.selectByPrimaryKey(1); }}
习惯用xml,这样方便把基础方法提出来