思路

  1. 引入 mybatis-spring-boot-startermysqldruid 相关依赖。
  2. 在入口类上加上 @mapperScan 注解,作用是扫描 DAO 接口(即数据访问接口)所在包。
  3. 建表
  4. 开发实体对象
  5. 开发 DAO 接口和 mapper 配置文件开发
  6. 开发 Service 和 ServiceImpl
  7. 开发 Controller
  8. 开发页面测试

步骤

  1. 新建 web-app 项目,导入相关依赖

  2. 修改配置文件

    server.port=8989
    server.servlet.context-path=/springboot_day6
    
    spring.thymeleaf.prefix=classpath:/templates
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.encoding=UTF-8
    spring.thymeleaf.cache=false
    spring.thymeleaf.servlet.content-type=text/html
    spring.resources.static-locations=classpath:/templates/,classpath:/static/
    
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test
    spring.datasource.username=root
    spring.datasource.password=1234
    
    mybatis.mapper-locations=classpath:/com/rennen/mapper/*.xml
    # Mapper 映射文件的存放地址
    mybatis.type-aliases-package=com.rennen.entity
    # 别名
    
  3. 入口类加上注解,用来做 Mapper 扫描

    @SpringBootApplication
    @MapperScan("com.rennen.dao")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    
  4. 建表和构建实体类

    package com.rennen.entity;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.ToString;
    
    import java.util.Date;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public class User {
        private String id;
        private String name;
        private Integer age;
        private Date bir;
    }
    
  5. 开发 DAO 接口

    package com.rennen.dao;
    
    import com.rennen.entity.User;
    
    import java.util.List;
    
    public interface UserDAO {
        void save(User user);
        List<User> findAll();
    }
    
  6. 编写 Mapper 文件(IDEA 中添加模板

    <?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.baizhi.dao.ClazzDAO">
        <select id="findAll" resultType="Clazz">
            select * from t_clazz 
        </select>
    </mapper>
    
  7. 开发 Service

    //接口
    public interface ClazzService {
        List<Clazz> findAll();
    }
    //实现
    @Service
    @Transactional
    public class ClazzServiceImpl implements  ClazzService {
        @Autowired
        private ClazzDAO clazzDAO;
        
        @Transactional(propagation = Propagation.SUPPORTS)
        @Override
        public List<Clazz> findAll() {
            return clazzDAO.findAll();
        }
    }