Idea搭建springboot+mvc+mybatis超詳細,記錄碰見的坑

new->project->spring Initializr->next->next->選中web下的web及sql下的mybatis->項目名html

1,更改maven爲本身安裝的mavan(file->settings->build,Execution,deployment->build Tools->mavwn,修改爲本身的配置)java

2,默認是springboot 2.0.4-RELEASE版本,建議換成1.5.9-RELEASEweb

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.9.RELEASE</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent>

3.首先我們先能讓項目跑起來,建一個controller來捕獲請求。spring

@Controller
public class MainController {
    @RequestMapping("index")
    @ResponseBody
    public String index(){
        String string="HELLO WORLD";
        return string;
    }
}

這裏注意:sql

1),文件路徑,新建的controller類必定在DomeApplication啓動類的平級或裏面一級,不然沒法註冊mapped數據庫

2),此時會報錯:Cannot determine embedded database driver class for database type NONEspringboot

一看就是database,一開始很蒙,還沒配置怎麼會報錯?查資料瞭解到-----------mybatis

這是由於spring boot默認會加載org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration類,DataSourceAutoConfiguration類使用了@Configuration註解向spring注入了dataSource bean。由於工程中沒有關於dataSource相關的配置信息,當spring建立dataSource bean因缺乏相關的信息就會報錯mvc

由於我僅僅只是使用spring boot來寫一些很簡單的例子來學習它,在Application類上增長@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})oracle

阻止spring boot自動注入dataSource bean

此時再啓動就沒問題了。

4,再配置mybatis

新建文件夾,dao,data,新建類User

package com.example.demo.data;

import org.springframework.stereotype.Component;

@Component
public class User {
    private String id;
    private String userId;
    private String userName;
    private String nickname;
    private String password;
    private String isAdmin;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(String isAdmin) {
        this.isAdmin = isAdmin;
    }

    @Override
    public String toString() {
        return "{"
                + "id: " + id
                + ", userId: " + userId
                + ", userName: " + userName
                + ", nickname: " + nickname
                + ", password: " + password
                + ", isAdmin: " + isAdmin + "}";
    }
}

2,新建一個controller,查詢數據用

public class FinduserController {

    @Autowired
    IUserService userService;

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ResponseBody
    public Map spiderLisSearch() {
        Map map = userService.getUserById("1");
        return map;
    }
}

順利成章的須要建立service,及實現

public interface IUserService {
    Map getUserById(String id);
}
@Service
public class UserServiceImpl  implements IUserService{

    @Override
    public Map<String, Object> getUserById(String id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            Map<String, Object> map = userMapper.getUserById(id);
            sqlSession.commit();
            return map;
        } finally {
            sqlSession.close();
        }
    }
}

這時發現,須要配置mybatis

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
    private MyBatisUtil() {
    }
    static {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

再配置mybatis配置文件

mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties resource="application.properties"></properties>
    <typeAliases>
        <package name="com.example.demo.data"/>
    </typeAliases>
    <environments default="dataSource">
        <environment id="dataSource">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${dataSource.driverClassName}"/>
                <property name="url" value="${dataSource.url}"/>
                <property name="username" value="${dataSource.username}"/>
                <property name="password" value="${dataSource.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.example.demo.dao"/>
    </mappers>
</configuration>

 

還需新建Dao層,之間操做數據庫

@Mapper
public interface UserMapper {
    Map<String, Object> getUserById(String id);
}
<?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.example.demo.dao.UserMapper">
    <resultMap type="com.example.demo.data.User" id="usermap">
        <id column="id" property="id" />
        <result column="user_id" property="userId" />
        <result column="user_name" property="userName" />
        <result column="nickname" property="nickname" />
        <result column="password" property="password" />
        <result column="is_admin" property="isAdmin" />
    </resultMap>
    <select id="getUserById" parameterType="String" resultType="map">
        SELECT
        id,
        user_id,
        user_name,
        nickname,
        password,
        is_admin
        FROM
        demo_user
        WHERE
        id = #{_parameter }
    </select>
</mapper>

結構

測試還需配置數據源,在application.properties

dataSource.url=jdbc:oracle:thin:@localhost:1521:orcl
dataSource.username= scott
dataSource.password=123456
dataSource.driverClassName=oracle.jdbc.driver.OracleDriver

這時oracle.jdbc.driver.OracleDriver會報錯,由於jdbc的問題,springboot沒有提供支持,因此須要手動打入maven包。

<dependency>
   <groupId>com.oracle</groupId>
   <artifactId>ojdbc6</artifactId>
   <version>11.2.0.3</version>
</dependency>

此時啓動項目,訪問查詢數據的controller,發現報錯,

Invalid bound statement (not found): com.example.demo.dao.dao.UserMapper.getUserById

緣由是找不到UserMapping.xml

解決:在pom文件中的<build>下添加

<!--找不到map.xml-->
<resources>
   <resource>
      <directory>src/main/java</directory>
      <includes>
         <include>**/*.properties</include>
         <include>**/*.xml</include>
      </includes>
      <filtering>false</filtering>
   </resource>
   <resource>
      <directory>src/main/resources</directory>
      <includes>
         <include>**/*.properties</include>
         <include>**/*.xml</include>
         <!--坑!!!-->
         <include>**/*.html</include>
      </includes>
      <filtering>false</filtering>
   </resource>
</resources>

OK

 

配置初始頁面

springboot與jsp兼容的很差,因此建議使用thymeleaf,添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

新建測試類:

@Controller
public class SampleController {

    @RequestMapping(value = "/")
    public ModelAndView test(ModelAndView mv) {
        mv.setViewName("hello");
        mv.addObject("title","歡迎使用Thymeleaf!");
        return mv;
    }
}

同時須要新建一樣的名字的html文件,

由於thymeleaf會默認到templates中找對應的模板,

至此,springboot+mvc+mybatis搭建完成,明天整理整理順序,OK

若是報錯,報,找不到網頁文件,就看剛在pom配置的

<resource>
   <directory>src/main/resources</directory>
   <includes>
      <include>**/*.properties</include>
      <include>**/*.xml</include>
      <!--坑!!!-->
      <include>**/*.html</include>
   </includes>
   <filtering>false</filtering>
</resource>

是否配置了html的掃描

相關文章
相關標籤/搜索