spring boot 整合mybatis
1、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.1.0.6.0</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
2、配置数据库信息
在application.properties中添加如下代码:
spring.datasource.url=jdbc:oracle:thin:@ip:port:SERVICE_NAME spring.datasource.username= spring.datasource.password= spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
3、创建实体类POJO
public class DefaultUdfUser { private String id; private String password_; private String username_; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername_() { return username_; } public void setUsername_(String username_) { this.username_ = username_; } public String getPassword_() { return password_; } public void setPassword_(String password_) { this.password_ = password_; } }
4、在src/main/resources下建立mybatis文件夹,并在此文件夹下建立UserMapper.xml,具体代码如下:
<?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.htkeystone.dcg.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.htkeystone.dcg.entity.DefaultUdfUser" > <id column="ID" property="id" jdbcType="VARCHAR" /> <result column="USERNAME_" property="username_" jdbcType="VARCHAR" /> <result column="PASSWORD_" property="password_" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > ID,USERNAME_,PASSWORD_ </sql> <select id="selectByUsername" resultMap="BaseResultMap" parameterType="java.lang.String"> select <include refid="Base_Column_List" /> from UDF_USER where USERNAME_=#{username_} </select> </mapper>
5、写UserMapper.java接口
import org.apache.ibatis.annotations.Mapper; import com.htkeystone.dcg.entity.DefaultUdfUser; @Mapper public interface UserMapper { DefaultUdfUser selectByUsername(String username_); }
注意要加上@Mapper注解,要不然会报错
6、在Dao层写如下代码
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.htkeystone.dcg.dao.DemoDao; import com.htkeystone.dcg.mapper.UserMapper; @Service public class DemoDaoImpl implements DemoDao{ @Autowired private UserMapper userMapper; @Override public String hello() { return userMapper.selectByUsername("000000266").getPassword_(); } }
7、启动报错,如下图:
找不到UserMapper的id selectByUsername
原因是没有指定UserMapper.xml的路径
解决方法:在application.properties加入如下代码
mybatis.mapper-locations: classpath:mybatis/*.xml
再启动就好了