spring boot 整合mybatis

zhumeilu發表於2017-12-14
  • 新增父專案依賴

      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>1.5.4.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
      </parent>
    
      <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
          <java.version>1.8</java.version>
      </properties>
    複製程式碼
  • 引入mybatis和資料庫以及連線池的依賴

      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.21</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>1.1.1</version>
      </dependency>
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.0.18</version>
      </dependency>
    複製程式碼
  • application.properties

    spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-test spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 非註解版需要新增以下配置,mapper的xml放在resources下的mapper資料夾

    mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.zml.demo.model mybatis.type-handlers-package=com.zml.demo.mapper

  • model 省略getter/setter

      @Alias("User")
      public class User implements Serializable {
    
          private Long id;
          private String username;
          private String password;
          private String name;
         
      }
    複製程式碼
  • controller

      @Controller
      public class UserController {
    
          @Autowired
          private UserMapper userMapper;
    
          @RequestMapping("/users/{id}")
          @ResponseBody
          public User get(@PathVariable Long id){
              User user = userMapper.get(id);
              return user;
          }
          @RequestMapping("/users")
          @ResponseBody
          public List<User> list(){
              List<User> userList = userMapper.listAll();
              return userList;
          }
      }
    複製程式碼
  • mapper 註解版,不用註解和原來的一樣

      @Component  //為了消除Controller裡面的紅線警告
      @Mapper
      public interface UserMapper {
      
          @Select("select * from user")
          @Results({
                  @Result(property = "username",column = "username"),
                  @Result(property = "password",column = "password")
          } )
          List<User> listAll();
      
          @Select("select * from user where id = #{id}")
          User get(Long id);
      
      }
    複製程式碼

相關文章