mybatis有两种方式,一种是基于XML,一种是基于注解
springboot集成mybatis
首先先创建表,这里都简化了
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'lijia');
然后创建maven项目,在pom.xml中添加
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>true</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
XML形式
目录结构是
application.properties
# jdbc_config
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://172.16.255.69:3306/test?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
# Mybatis
#mybatis.typeAliasesPackage对应的是实体类位置
mybatis.typeAliasesPackage=org.lijia.bean
#mybatis.mapperLocations查找mybatis配置文件位置
mybatis.mapperLocations=classpath:mybatis/*.xml
实体类User
public class User {
private String id; //用户id
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;
}
}
HelloController :
import com.alibaba.fastjson.JSON;
import com.lijia.bean.User;
import com.lijia.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/hello")
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/get")
@ResponseBody
public String get(@RequestParam String username){
User user = helloService.get(username);
if(user!=null){
System.out.println("user.getName():"+user.getUsername());
}
return JSON.toJSONString(user);
}
@RequestMapping("/exception")
@ResponseBody
public String exception(){
throw new RuntimeException();
}
}
HelloService :
import com.lijia.bean.User;
import com.lijia.dao.HelloMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
//@Transactional
public class HelloService {
@Autowired
private HelloMapper helloMapper;
public User get(String username) {
return helloMapper.findUserByName(username);
}
}
接口HelloMapper :
import com.lijia.bean.User;
public interface HelloMapper {
public User findUserByName(String username);
}
mybatis配置文件:
<?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.lijia.dao.HelloMapper" >
<resultMap id="BaseResultMap" type="com.lijia.bean.User">
<result column="id" property="id" />
<result column="username" property="username" />
</resultMap>
<!-- 根据条件查询-->
<select id="findUserByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select * from user where username = #{username}
</select>
</mapper>
最后启动类Application:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.lijia.dao") //扫描接口
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
启动Application,输入成功获取数据
mybatis注解方式
注解方式我感觉太简单了,一般我也是用这个
没有了mybatis那些配置文件
application.properties:去除了mybatis的东西
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://172.16.255.69:3306/test?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
启动类Application:也没有了扫描
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
最主要的是:HelloMapper
import com.lijia.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface HelloMapper {
@Select("select * from user where username = #{username}")
public User findUserByName(String username);
}
在接口上加上@Mapper
在方法上面加上@Select里面跟着sql
然后启动Application,结果一样
全局异常捕获
只要在项目中加上这个类
import com.lijia.common.result.Result;
import com.lijia.common.result.ResultEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* Desc:全局异常捕获并返回
*
*/
@RestController
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(Exception.class)
public Result<String> defaultExceptionHandler(HttpServletRequest request, Exception e)
throws Exception {
return new Result<>(ResultEnum.SERVER_ERROR, e.getMessage());
}
}
这里面的Result是自定义。
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
public class Result<T> {
private int code;
private String desc;
private T data;
public Result(ResultEnum resultEnum) {
this.code = resultEnum.getCode();
this.desc = resultEnum.getDesc();
}
public Result(ResultEnum resultEnum, T data) {
this.code = resultEnum.getCode();
this.desc = resultEnum.getDesc();
this.data = data;
}
}
还有个枚举
public enum ResultEnum {
SUCCESS(200, "success"), SERVER_ERROR(500, "server error");
private int code;
private String desc;
ResultEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
在上面的Controller中已经有异常的方法,启动Application