SpringBoot集成MyBatis开发web项目

一、Spring Boot产生的原因

现在大部分企业用的还是Spring+SpringMVC+...框架,所以童鞋们应该也很了解Spring和SpringMVC框架,不管是在搭建还是在开发新模块或者集成第三方插件等等上面都是需要另行手动配置的。主要是框架的好多配置都是一尘不变的,这样徒增了我们的工作量并且在跨平台时刻也容易出错。(当然如果所有的配置你都理解了都是自己亲自配置的,那么即使出错了你也能很快的定位和解决问题)。

由于这些已经存在的问题,那么Spring Boot就应运而生,使用Spring Boot可以让我们快速创建一个基于Spring的项目,并且手动配置很少(蛋疼的地方:如果你是springboot新手,那么搭建项目的时候报错很难定位问题,并且报错信息很可能是框架内部错误)。

优势:

1>Spring Boot可以通过java -jar xx.jar类运行。非常方便。

2>Spring Boot可以内嵌Tomcat,这样我们无需配置和部署项目。

3>简化Spring和SpringMVC之间的依赖-starter

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 有待添加,自动生成springboot项目没有此jar -->
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter</artifactId> -->

<!-- </dependency> -->

二、eclipse搭建SpringBoot+MyBatis

1>项目结构


2>本文基于eclipse4.7.2+sts(springsource-tool-suite)+maven3.5.2搭建的,所以之前eclipse必须安装了sts和配置好了maven仓库,sts安装地址:https://jingyan.baidu.com/article/1612d5005fd087e20f1eee10.html。此处不累述了。

sts插件安装好之后.

<1>打开eclipse-file-new-other-Spring Starter Project,next


<2>输入相应的name、Group、Artifact、package(可以默认),next


<3>选择web,Finish


看看结构。模式:Navigator


<4>打开pom.xml,输入:

<?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.zhiwang.boot</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot-mybatis</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!--引入swagger  -->  
        <dependency>  
           <groupId>io.springfox</groupId>  
           <artifactId>springfox-swagger2</artifactId>  
           <version>2.2.2</version>  

        </dependency>  

        <dependency>  
           <groupId>io.springfox</groupId>  
           <artifactId>springfox-swagger-ui</artifactId>  
           <version>2.2.2</version>  
        </dependency>  

<!--集成mybatis -->
<!-- 与数据库操作相关的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- 使用数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>

<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>

<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

<5>打开项目 src-main-resources-application.properties,输入:

#数据库驱动 -mysql
jdbc.driverClassName = com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://192.168.23.101:3306/hzgdb?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8  
jdbc.username = hzgg 
jdbc.password = 123456  

#mybatis扫描的实体类 
mybatis.typeAliasesPackage=com.zhiwang.boot.entity  
#mybatis扫描的mapper
mybatis.mapperLocations=classpath:mapper/*.xml
#日志配置 

logging.config=classpath:logback-boot.xml

注:其中application.properties输入中文会乱码,所以要把此文件设为UTF-8


<6>在resources下添加logback-boot.xml日志文件,此处不累述。

<7>


package com.zhiwang.boot.common;


import java.util.Properties;


import javax.sql.DataSource;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;


import com.alibaba.druid.pool.DruidDataSourceFactory;
/**  
 * springboot集成mybatis的基本入口  
 * 1)创建数据源  
 * 2)创建SqlSessionFactory  
 */  
//该注解类似于spring配置文件  
@Configuration    
//扫描接口
@MapperScan(basePackages="com.zhiwang.boot.mapper")  
public class MyBatisConfig {
@Autowired
private Environment env;

/**  
     * 创建数据源  
     * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,
     * 默认选择哪一个,而不是让@autowire注解报错   
     */
@Bean
// @Primary
public DataSource getDataSource() throws Exception {
Properties props = new Properties();  
        props.put("driverClassName", env.getProperty("jdbc.driverClassName"));  
        props.put("url", env.getProperty("jdbc.url"));  
        props.put("username", env.getProperty("jdbc.username"));  
        props.put("password", env.getProperty("jdbc.password"));  
        return DruidDataSourceFactory.createDataSource(props);  
}

@Bean
public SqlSessionFactory getSqlSessionFactory(DataSource ds) throws Exception {
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();  
        fb.setDataSource(ds);//指定数据源(这个必须有,否则报错)  
        //下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加  
        fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));//指定基包  
        //指定xml文件位置  
        fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));
        return fb.getObject();  
}
}

<8>


package com.zhiwang.boot.mapper;


import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;


import com.zhiwang.boot.entity.User;




public interface UserMapper {
@Insert("INSERT INTO my_user(id, name) VALUES(#{id},#{name})")  
    public int insertUser(@Param("id") String id, @Param("name")  String name);  
      
     /**  
     * 插入用户,并将主键设置到user中  
     * 注意:返回的是数据库影响条数,即1  
     */  
    public int insertUserWithBackId(User user); 
}

<9>


package com.zhiwang.boot.entity;


import java.io.Serializable;


public class User implements Serializable{
/**

*/
private static final long serialVersionUID = 1L;
//id
private String id;
//姓名
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public User(String id, String name) {
super();
this.id = id;
this.name = name;
}

public User() {
super();
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}

}

<10>



package com.zhiwang.boot.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.zhiwang.boot.entity.User;
import com.zhiwang.boot.mapper.UserMapper;


@Service
@Transactional
public class UserService {

@Autowired
private UserMapper userDao;


public boolean addUser(String id, String name) {
return userDao.insertUser(id, name) == 1 ? true : false;
}


public User addUserWithBackId(String id, String name) {
User user = new User();
user.setId(id);
user.setName(name);
userDao.insertUserWithBackId(user);// 该方法后,主键已经设置到user中了
return user;
}

}

<11>


package com.zhiwang.boot.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import com.zhiwang.boot.entity.User;
import com.zhiwang.boot.service.UserService;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;


@RestController
@RequestMapping("/user")
@Api("userController相关api")
public class UserController {
@Autowired
private UserService userService;


@ApiOperation("添加用户")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "id", dataType = "String", required = true, value = "用户的id", defaultValue = "100"),
@ApiImplicitParam(paramType = "query", name = "name", dataType = "String", required = true, value = "用户的姓名", defaultValue = "val") })
@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
@RequestMapping(value = "/addUser", method = RequestMethod.GET)
public boolean addUser(@RequestParam(value="id",required=false) String id, @RequestParam("name") String name) {
return userService.addUser(id, name);
}


@ApiOperation("添加用户且返回已经设置了主键的user实例")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "id", dataType = "String", required = true, value = "用户的id", defaultValue = "100"),
@ApiImplicitParam(paramType = "query", name = "name", dataType = "String", required = true, value = "用户的姓名", defaultValue = "val") })
@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
@RequestMapping(value = "/addUserWithBackId", method = RequestMethod.GET)
public User addUserWithBackId(@RequestParam("id") String id,
@RequestParam("name") String name) {
return userService.addUserWithBackId(id, name);
}

}

<12>


<?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">  
  
<!-- 指定工作空间,要与接口名相同,源代码没有去看,猜测应该是通过"这里的namespace.下边方法的id"来定位方法的 -->  
<mapper namespace="com.zhiwang.boot.mapper.UserMapper">  
      
    <!-- 若不需要自动返回主键,将useGeneratedKeys="true" keyProperty="id"去掉即可(当然如果不需要自动返回主键,直接用注解即可) -->  
    <insert id="insertUserWithBackId" parameterType="User" useGeneratedKeys="true" keyProperty="id" >  
       <![CDATA[ 
       INSERT INTO MY_USER  
       ( 
           id, 
           name 
       ) 
       VALUES 
       ( 
           #{id, jdbcType=VARCHAR}, 
           #{name, jdbcType=VARCHAR} 
       ) 
       ]]>  
   </insert>  
      

</mapper> 

<13>右击项目-Run As-Maven clean,succes之后然后Run As-Maven build-Goals中输入compile


<14>运行SpringbootMybatisApplication.java


<15>浏览器输入:http://localhost:8080/user/addUser?id=5&name=sdfas         返回true,表示成功


<16>数据库显示


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值