刚写个springboot的demo就遇到这么个大坑,在此记录一下,顺便贴一下代码,方便新手入门,springboot简单整合mybati详细代码及目录结构如下:
cintroller代码:
package com.yango.controller;
import com.yango.entity.User;
import com.yango.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/showUser")
@ResponseBody
public User toIndex(HttpServletRequest request, Model model){
int userId = Integer.parseInt(request.getParameter("id"));
User user = this.userService.getUserById(userId);
return user;
}
}
dao层:
package com.yango.dao;
import com.yango.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao {
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
}
entity层:
package com.yango.entity;
public class User {
private Integer id;
private String userName;
private String password;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
service接口:
package com.yango.service;
import com.yango.entity.User;
public interface UserService {
public User getUserById(int userId);
boolean addUser(User record);
}
service层:
package com.yango.service.impl;
import com.yango.dao.UserDao;
import com.yango.entity.User;
import com.yango.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserDao userDao;
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
public boolean addUser(User record){
boolean result = false;
try {
userDao.insertSelective(record);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
启动类:
package com.yango;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.yango.dao")
//@ComponentScan({"com.yango"})
public class Entry {
public static void main(String[] args) throws Exception {
SpringApplication.run(Entry.class, args);
}
}
mapper文件:
<?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.yango.dao.UserDao" >
<resultMap id="BaseResultMap" type="com.yango.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from tbl_user
where id = #{id,jdbcType=INTEGER}
</select>
<insert id="insert" parameterType="com.yango.entity.User" >
insert into user_t (id, user_name, password,
age)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.yango.entity.User" >
insert into user_t
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="password != null" >
password,
</if>
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
</mapper>
application.yml文件:
#默认使用配置
spring:
profiles:
active: dev
---
#公共配置与profiles选择无关
mybatis:
type-aliases-package: com.yango.entity
mapper-locations: classpath:com/yango/dao/*.xml
server:
tomcat:
uri-encoding: utf-8
#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
这里需要注意,使用了springboot中提供的环境切换的功能,上面配置的dev,程序会默认加载application-dev.yml,也就是说,程序会加载application-${var}的文件。
application-dev.yml文件:
spring:
# profiles: test
datasource:
url: jdbc:mysql://localhost:3306/demo
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
server:
port: 8081
pom文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yango</groupId>
<artifactId>boot-project</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- 没有该配置,devtools 不生效 -->
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
常见问题:
问题1
注意在application.yml文件中标注蓝色的部分,如果配置这样扫描mybatis的mapper文件程序会报错,如下:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.yango.dao.UserDao.selectByPrimaryKey
at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:225) ~[mybatis-3.4.4.jar:3.4.4]
at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:48) ~[mybatis-3.4.4.jar:3.4.4]
at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65) ~[mybatis-3.4.4.jar:3.4.4]
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) ~[mybatis-3.4.4.jar:3.4.4]
at com.sun.proxy.$Proxy74.selectByPrimaryKey(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.6.RELEASE.jar:4.3.6.RELEASE]
找不到对应的mapper,这时需要将mapper-locations: classpath:com/yango/dao/*.xml改为mapper-locations: classpath:com.yango.dao/*.xml 即可,
问题2
application.yml从别处复制过来之后启动报错,前言中不允许有内容。 则可能是编码的问题,这时候可以将复制的文本放到txt中设置为UTF-8再复制进项目即可。