使用RESTful风格整合springboot+mybatis

说明:
本文是springboot和mybatis的整合,Controller层使用的是RESTful风格,数据连接池使用的是c3p0,通过postman进行测试

项目结构如下:
项目结构.png
1、引入pom.xml依赖
        <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.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--配置文件处理器,可以提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

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

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

        <!-- springloaded热部署依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
            <version>1.2.0.RELEASE</version>
            <scope>provided</scope>
        </dependency>
实体类User
package com.jiangfeixiang.springbootmybatis.entity;

import java.io.Serializable;

/**
 * Created by jiangfeixiang on 2018/8/19
 */
public class User implements Serializable {
    private Integer id;
    private String username;
    private String age;
    private String city;

    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 getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", age='" + age + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}
2、application.propreties配置文件
#服务器
server.port=8080
server.servlet.context-path=/

#热部署
spring.devtools.remote.restart.enabled=true
spring.devtools.restart.additional-paths=src/main

#mybatis
mybatis.type-aliases-package=com.jiangfeixiang.springbootmybatis.entity 
mybatis.config-locations=mybatis-config.xml    #mybatis-config.xml配置文件
mybatis.mapper-locations=mapper/*.xml   #mapper.xml映射文件

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=1234
3、Mybatis配置文件:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="false"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="5"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>
    </settings>

    <!--包别名-->
    <typeAliases>
        <package name="com.jiangfeixiang.springbootmybatis.entity"/>
    </typeAliases>

    <!-- Continue editing here -->

</configuration>
4、UserMapper接口
在com.jiangfeixiang.springbootmybatis.mapper包下创建UserMapper接口
package com.jiangfeixiang.springbootmybatis.mapper;

import com.jiangfeixiang.springbootmybatis.entity.User;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/8/19
 */
public interface UserMapper {
    /**
     * 查询所有用户
     */
    List<User> getAllUser();

    /**
     * 根据id查询
     */
    User getUserById(Integer id);

    /**
     * 添加用户
     */
    Integer addUser(User user);

    /**
     * 修改用户
     */
    Integer updateUser(User user);
    /**
     * 根据id删除用户
     */
    Integer deleteUserById(Integer id);

}
5、UserMapper.xml映射文件
在resources/mapper包下创建UserMapper.xml文件如下:
<?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.jiangfeixiang.springbootmybatis.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.jiangfeixiang.springbootmybatis.entity.User">
        <result column="id" property="id" />
        <result column="username" property="username" />
        <result column="age" property="age" />
        <result column="city" property="city" />
    </resultMap>

    <parameterMap id="User" type="com.jiangfeixiang.springbootmybatis.entity.User"/>

    <sql id="Base_Column_List">
        id, username, age, city
    </sql>

    <!--查询所有用户-->
    <select id="getAllUser" resultMap="BaseResultMap" >
        select
        <include refid="Base_Column_List" />
        from user
    </select>

    <!--根据id查询-->
    <select id="getUserById" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List" />
        from user
        where id = #{id}
    </select>

    <!--添加用户-->
    <insert id="addUser" parameterMap="User" useGeneratedKeys="true" keyProperty="id">
        insert into
        user
        (username,age,city)
        values
        (#{username},#{age},#{city})
    </insert>

    <update id="updateUser" parameterMap="User">
        update
        user
        set
        <if test="username!=null">
            username = #{username},
        </if>
        <if test="age!=null">
            age = #{age},
        </if>
        <if test="city!=null">
            city = #{city}
        </if>
        where
        id = #{id}
    </update>

    <!--根据id删除用户-->
    <delete id="deleteUserById" parameterType="java.lang.Integer">
        delete from
        user
        where
        id = #{id}
    </delete>
</mapper>

下面配置DataSource和SqlSessionFactory

在config/dao包下创建DataSource
package com.jiangfeixiang.springbootmybatis.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyVetoException;

/**
 * Created by jiangfeixiang on 2018/8/20
 */
@Configuration
//配置mybatis mapper的扫描路径
@MapperScan("com.jiangfeixiang.springbootmybatis.mapper")
public class DataSourceConfig {

    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(name = "dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        //关闭连接后不自动commit
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }
}
在config/dao包下创建SessionFactoryConfig
package com.jiangfeixiang.springbootmybatis.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * Created by jiangfeixiang on 2018/8/20
 */
@Configuration
public class SessionFactoryConfig {

    @Value("${mybatis.config-locations}")
    private String mybatisConfigFilePath;
    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;
    @Value("${mybatis.mapper-locations}")
    private String mapperPath;
    @Value("{mybatis.type-aliases-package}")
    private String entityPackage;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 创建SqlSession FactoryBean实例
        sqlSessionFactoryBean.setConfigLocation (new ClassPathResource ( mybatisConfigFilePath )); // 扫描mybatis配置文件;
        // 设置数据库连接信息
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置 mappe r映射器对应的XML文件的扫描路径
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        // 设置实体类扫描路径
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

在config/service包下创建TransactionManager事务管理器

package com.jiangfeixiang.springbootmybatis.config.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * Created by jiangfeixiang on 2018/4/9
 */
@Configuration
@EnableTransactionManagement
public class TransactionManagerConfig implements TransactionManagementConfigurer{

    @Autowired
    private DataSource dataSource;
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
下面开始编写Service层和Controller层

UserService接口

package com.jiangfeixiang.springbootmybatis.service;

import com.jiangfeixiang.springbootmybatis.entity.User;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/8/25
 */
public interface UserService {

    /**
     * 查询所有用户
     */
    List<User> getAllUser();

    /**
     * 根据id查询
     */
    User getUserById(Integer id);

    /**
     * 添加用户
     */
    Integer addUser(User user);

    /**
     * 修改用户
     */
    Integer updateUser(User user);
    /**
     * 根据id删除用户
     */
    Integer deleteUserById(Integer id);
}
UserServiceImpl实现类
package com.jiangfeixiang.springbootmybatis.service.impl;

import com.jiangfeixiang.springbootmybatis.entity.User;
import com.jiangfeixiang.springbootmybatis.mapper.UserMapper;
import com.jiangfeixiang.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/8/25
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     *查询
     * @return
     */
    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    /**
     * 添加
     * @param user
     * @return
     */
    @Override
    public Integer addUser(User user) {
        return userMapper.addUser(user);
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @Override
    public Integer updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public Integer deleteUserById(Integer id) {
        return userMapper.deleteUserById(id);
    }
}
UserController
package com.jiangfeixiang.springbootmybatis.controller;

import com.jiangfeixiang.springbootmybatis.entity.User;
import com.jiangfeixiang.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/8/19
 */
@RestController
//@Controller
//@RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有用户
     * 处理"/users"的GET请求,用来获取用户列表
     *还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
     * @return
     */
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public List<User> getAllUser() {
        List<User> users=userService.getAllUser();
        return users;
    }

    /**
     * 添加用户
     * 处理"/users"的POST请求,用来创建User
     * @param user
     */
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(@ModelAttribute User user) {
        Integer addUser = userService.addUser(user);
        return "success";
    }

    /**
     * 根据id查询
     * 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
     * url中的id可通过@PathVariable绑定到函数的参数中
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public User getUserById(@PathVariable("id") Integer id) {
        User user=userService.getUserById(id);
        return user;
    }



    /**
     * 更新用户
     * 处理"/users/{id}"的PUT请求,用来更新User信息
     * @param user
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public String updateUser(@PathVariable("id") Integer id, @ModelAttribute User user) {
        Integer updateUser = userService.updateUser(user);
        return "success";
    }

    /**
     * 处理"/users/{id}"的DELETE请求,用来删除User
     * @param id
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    public String deleteUserById(@PathVariable("id") Integer id) {
        Integer deleteUserById = userService.deleteUserById(id);
        return "success";
    }
}
最后启动类上添加@MapperScan("com.jiangfeixiang.springbootmybatis.mapper")用了扫描UserMapper接口
package com.jiangfeixiang.springbootmybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.jiangfeixiang.springbootmybatis.mapper")
public class SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343