1、添加依赖
org.springframework.boot spring-boot-starter-jdbc com.oracle ojdbc6 11.1.0.6.0 org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2
2、配置数据库信息
在application.properties中添加如下代码:
spring.datasource.url=jdbc:oracle:thin:@ip:port:SERVICE_NAMEspring.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,具体代码如下:
ID,USERNAME_,PASSWORD_
5、写UserMapper.java接口
import org.apache.ibatis.annotations.Mapper;import com.htkeystone.dcg.entity.DefaultUdfUser;@Mapperpublic 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;@Servicepublic 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
再启动就好了