1. 程式人生 > >SpringBoot + mybatis預設配置與手動配置步驟對比一(預設配置)

SpringBoot + mybatis預設配置與手動配置步驟對比一(預設配置)

前提環境已經搭建完成

Eclipse + SpringBoot + mybatis預設配置:

1.建立工程

File->new->other->Spring Boot -> Spring Starter Project ->選擇jdk等資訊  ->  點選Web,選擇Web,然後點選SQL,選擇JPA、Mybatis、MYSQL,點選next,Finish。

2.開始編碼

2.1修改application.properties

spring.datasource.url=

spring.datasource.username=

spring.datasource.password=

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2.2建立實體類

package com.lele.demo.entity;

import java.util.Date;

public class User {

     private Integer PUB_USER_ID;

     private String LOGIN_NAME;

     private String PASSWORD;

    //...

     public Integer getPubUserId() {

           return PUB_USER_ID;

     }

     public void setPubUserId(Integer PUB_USER_ID) {

           this.PUB_USER_ID = PUB_USER_ID;

     }

//...省略

}

2.3建立Mapper(注意Interface檔案是介面,不是Class--類中方發要有實現內容的, 介面可以只有方法名不用寫方法的具體實現, 具體拉到最後看區別)

package com.lele.demo.DAO;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import org.apache.ibatis.annotations.Param;

import org.apache.ibatis.annotations.Select;

@Mapper

public interface UserMapper {

      /** * 根據主鍵查詢單個 * * @param id * @return */

     @Select("select TEL from pisp_pub_user where PUB_USER_ID=#{id}")

     List<String> selectById(@Param("id") Long id);

}

2.4建立Dao

package com.lele.demo.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.dao.DataAccessException;

import org.springframework.stereotype.Repository;

import com.lele.demo.mapper.UserMapper;

import com.lele.demo.model.User;

@Repository

public class UserDao {

     @Autowired

     private UserMapper userMapper;

     public User selectUserById(Long id) throws DataAccessException {

           return userMapper.selectUserById(id);

     }

}

2.5建立Controller

package com.lele.demo.Controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.EnableTransactionManagement;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.lele.demo.dao.UserDao;

import com.lele.demo.model.User;

@EnableTransactionManagement  // 需要事務的時候加上

@RestController

public class UserController {

     @Autowired

    private UserDao userDao;

     @RequestMapping("/selectUserById/{id}")

    public User selectUserById(@PathVariable("id") Long id) {

        return userDao.selectUserById(id);

     }

}

2.6執行

2.7開啟瀏覽器訪問

http://127.0.0.1:8080/selectUserById/2