mybatis有兩種方式年扩,一種是基于XML,一種是基于注解
springboot集成mybatis
首先先創(chuàng)建表,這里都簡化了
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');
然后創(chuàng)建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形式
目錄結(jié)構(gòu)是
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對應(yīng)的是實體類位置
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" >
<!--完全對應(yīng)接口,不然報錯-->
<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>
<!-- 根據(jù)條件查詢-->
<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,輸入成功獲取數(shù)據(jù)
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俭令,結(jié)果一樣
全局異常捕獲
只要在項目中加上這個類
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中已經(jīng)有異常的方法部宿,啟動Application