Springboot & Mybatis 构建restful 服务一

1 前置条件

  • jdk测试:java -version

  • maven测试:命令行之行mvn -v

  • eclipse及maven插件

2 Springboot

1)创建maven项目:

eclipse:new -> project -> maven project

 选择:Create a simple project(skip archetype selection)

(假设项目名为com.serena.AccountBalance)

2)修改pom:

      <!-- 新增 -->
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
      </parent> 
      <dependencies>
        <!-- 新增spring boot依赖 -->
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
      </dependencies>

3)下载数据库驱动包(此例使用的是 Oracle 数据库,由于 Oracle 版权问题,所以需下载驱动jar包):

去 Oracle 官网下载 jdbc驱动ojdbc6-1.0.1.jar

在终端执行下列命令
    mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=1.0.1 -Dpackaging=jar -Dfile=ojdbc6.jar

在eclipse中选中当前工程

maven -> update project...

4)在项目目录下分别创建:

(此例中为:main/java/com/serena)

 
    — controller      //接口层
    — servcie           //业务层
        — impl
    — mapper          //数据操作层
    — entity            //数据持久化层

5)在项目目录下新建启动类 App.java:

(此例中为:main/java/com/serena)

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;   
    @SpringBootApplication
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
 

6)代码:编写controller和service代码

创建service/ISY.java,内容如下:

package com.serena.service;
import java.util.List;
import com.serena.entity.SettleAccount;
public interface ISY {

    // 通过账户 id(主键)查找账户
    SettleAccount selectByAccountCode(String accountCode);
    // 查找所有账户
    List<SettleAccount> selectAccounts();
}

创建 controller/SY.java,内容如下:

package com.serena.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.serena.entity.SettleAccount;
import com.serena.service.ISY;
@RestController
public class SY {
    @Autowired
    private ISY iSY;
// 通过用户 id 来查找用户余额
// 使用 get 请求传递参数
    @RequestMapping(value="/account/{accountCode}",method = RequestMethod.GET)
    public SettleAccount selectByAccountCode(@PathVariable("accountCode")String accountCode){
    SettleAccount settleAccount  = iSY.selectByAccountCode(accountCode);
            return settleAccount;
    } 
  // 查找所有 account 的余额
    @RequestMapping(value="/accounts",method = RequestMethod.GET)
    public List<SettleAccount> selectAccounts(){
        List<SettleAccount> list = null;
        list = iSY.selectAccounts();
        return list;
    }
}
 

编写service/impl/SYService.java

package com.serena.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.serena.entity.SettleAccount;
import com.serena.mapper.SettleAccountMapper;
import com.serena.service.ISY;
@Service
public class SYService implements ISY{
    @Autowired
    private SettleAccountMapper settleAccountMapper;
    @Override
    public SettleAccount selectByAccountCode(String accountCode) {
        SettleAccount settleAccount = null;
        settleAccount = settleAccountMapper.selectByPrimaryKey(accountCode);
        return settleAccount;
    } 
    @Override
    public List<SettleAccount> selectAccounts() {
        List<SettleAccount> list = null;
        list = settleAccountMapper.selectAccounts();
        return list;
    }
}

3 Mybatis generator

1)修改pom:

新增依赖

    <!-- Spring Boot 集成MyBatis -->
     <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
    </dependency>
<!-- 实体映射 -->
    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-mapping</artifactId>
    </dependency>
   <!-- mysql 数据库连接 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    
  <!-- oracle 数据库连接 -->
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>1.0.1</version>
        <scope>runtime</scope>
    </dependency>
 
新增自动生成 mapper 和 entity 插件 plugin
   <!-- mybatis generator 插件 -->
        <plugin> 
            <groupId>org.mybatis.generator</groupId> 
            <artifactId>mybatis-generator-maven-plugin</artifactId> 
            <version>1.3.5</version> 
            <configuration>  
                <verbose>true</verbose>  
                <overwrite>true</overwrite>  
            </configuration>  
        </plugin> 
 

2)创建配置文件: src/main/resources/generatorConfig.xml

中文标注的地方需自定义!!!

 
<!DOCTYPE generatorConfiguration 
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <classPathEntry location="安装的 Oracle 驱动包的仓库jar文件位置" />
            <context id="OracleTables" targetRuntime="MyBatis3">
    <commentGenerator>
        <property name="suppressAllComments" value="true"/>
    </commentGenerator>
     <jdbcConnection driverClass="驱动类"
        connectionURL="数据库URL地址"
        userId="用户名"        password="密码">
    </jdbcConnection>
  <javaTypeResolver>
     <property name="forceBigDecimals" value="false"/>
  </javaTypeResolver>
  <javaModelGenerator targetPackage="com.serena.entity" targetProject="src/main/java">
      <property name="enableSubPackages" value="false"/>
      <property name="trimStrings" value="true"/>
  </javaModelGenerator>
  <sqlMapGenerator targetPackage="com.serena.mapper" targetProject="src/main/java">
       <property name="enableSubPackages" value="false"/>
  </sqlMapGenerator>
  <javaClientGenerator type="XMLMAPPER" targetPackage="com.serena.mapper" targetProject="src/main/java">
    <property name="enableSubPackages" value="false"/>
  </javaClientGenerator>
  <!-- 例: 查询的表名:SETTLEACCOUNT
           自定义的实体类名称:SettleAccount
        -->
  <table  tableName="SETTLEACCOUNT" domainObjectName="自定义的实体类名称"  enableCountByExample="false" enableSelectByExample="false" enableUpdateByExample="false" enableDeleteByExample="false">
  </table>
</context>
</generatorConfiguration>
 

3) 执行:maven build: mybatis-generator:generate

4. Mybatis

1) 在所有mapper类中的接口声明前增加 @Mapper

添加@Mapper​

@Mapper
public interface SettleAccountMapper {
  //some code
}

2)删除entity 里SettleAccount多余的属性和 setter,getter 方法,只保留 ACCOUNTCODE, CUSTOMERCODE, ACCOUNTNAME, SMSNUM

3)在SettleAccountMapper.xml中执行下列操作:

// 添加
<select id="selectAccounts"  resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from SETTLEACCOUNT
  </select>
// 修改 id为BaseResultMap的resultMap
 <resultMap id="BaseResultMap" type="com.serena.entity.SettleAccount">
    <id column="ACCOUNTCODE" jdbcType="VARCHAR" property="accountcode" />
    <result column="CUSTOMERCODE" jdbcType="VARCHAR" property="customercode" />
    <result column="ACCOUNTNAME" jdbcType="VARCHAR" property="accountname" />
    <result column="SMSNUM" jdbcType="DECIMAL" property="smsnum" />
  </resultMap>
// 修改id 为Base_Column_List的 sql
 <sql id="Base_Column_List">
    ACCOUNTCODE, CUSTOMERCODE, ACCOUNTNAME,  SMSNUM
  </sql>
 

修改SettleAccountMapper:

package com.serena.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.serena.entity.SettleAccount;
@Mapper
public interface SettleAccountMapper {
    // 抽象方法:通过账户编号查找账户
    SettleAccount selectByPrimaryKey(String accountcode);
    // 抽象方法:查找所有账户
    List<SettleAccount> selectAccounts();
}

4)编译:maven build: clean compile

5)创建配置文件:src/main/java/resources/application.properties

// 服务器端口号
    server.port=8101
//  mapper映射地址
    mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
//  数据库URL地址
 spring.datasource.url=
// 登录数据库的用户名
    spring.datasource.username=
//  密码
    spring.datasource.password=
 

6)运行启动类App.class

7)在iterm 中输入如下指令测试:

 http localhost:8101/accounts
  
 http localhost:8101/account/U0001
 

Springboot & Mybatis 构建restful 服务的更多相关文章

  1. Springboot & Mybatis 构建restful 服务五

    Springboot & Mybatis 构建restful 服务五 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务四 2 restful ...

  2. Springboot & Mybatis 构建restful 服务四

    Springboot & Mybatis 构建restful 服务四 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务三 2 restful ...

  3. Springboot & Mybatis 构建restful 服务三

    Springboot & Mybatis 构建restful 服务三 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务二 2 restful ...

  4. Springboot & Mybatis 构建restful 服务二

    Springboot & Mybatis 构建restful 服务二 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务一 2 restful ...

  5. 基于SpringBoot开发一个Restful服务,实现增删改查功能

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  6. jersey+maven构建restful服务

    一.新建一个Maven Web项目 a) 新建一个简单的Maven项目 b) 将简单的Maven项目转成Web项目 (若没出现further configuration available--或里面的 ...

  7. 用Jersey构建RESTful服务7--Jersey+SQLServer+Hibernate4.3+Spring3.2

    一.整体说明 本例执行演示了用 Jersey 构建 RESTful 服务中.怎样集成 Spring3 二.环境 1.上文的项目RestDemo 2.Spring及其它相关的jar ,导入项目 三.配置 ...

  8. JAX-RS(基于Jersey) + Spring 4.x + MyBatis构建REST服务架构

    0. 大背景 众所周知,REST架构已经成为现代服务端的趋势. 很多公司,已经采用REST作为App, H5以及其它客户端的服务端架构. 1. 什么是JAX-RS? JAX-RS是JAVA EE6 引 ...

  9. CXF+Spring+JAXB+Json构建Restful服务

    话不多说,先看详细的样例: 文件文件夹结构: web.xml <?xml version="1.0" encoding="UTF-8"? > < ...

随机推荐

  1. css:伪类和伪元素

    一:伪类 1.   :active   想被激活的元素添加样式 2.   :focus   向拥有键盘输入焦点的元素添加样式 3.   :hover   当鼠标悬浮在元素上方时,向元素添加样式 4.  ...

  2. MySQL 还原

    ## sql 还原:mysql -default-character-set=utf8 -h127.0.0.1 -uroot -pxxxxxx test2 < /data/test/db/201 ...

  3. jQuery横向上下排列鱼骨图形式信息展示代码时光轴样式(转自CSDN,原文链接附于文中)

    原文链接:http://www.jqueryfuns.com/resource/2173 $.fn.fishBone = function(data) { var colors = ['#F89782 ...

  4. 查询当前局域网下所有IP和物理网卡地址

    WIN+R –> 打开cmd 键入 arp -a

  5. html和css问题?

    1.说说你对语义化的理解?答,去掉或者丢失样式的时候能够让页面呈现出清晰的结构方便其他设备解析(如屏幕阅读器.盲人阅读器.移动设备)以意义的方式来渲染网页:便于团队开发和维护,语义化更具可读性,是下一 ...

  6. vuecli3.0安装搭建项目

    1. npm install -g @vue/cli 2. vue create wechat Linter / Formatter 可以不选 检查空格的 //选择less //标准eslint // ...

  7. css,html备忘录

    1.background:url()#000 ;代表当图片不够充满容器时,用黑色填满. 2.height:inherit;继承父级元素的高度. 当子元素给了绝对定位,父元素不给相对定位,子元素也能适配 ...

  8. python基础与docker

    创建虚拟环境python3 -m venv venv (说明:python 2.X 并不支持) 激活虚拟环境macOS/Linux: source venv/bin/activateWindows: ...

  9. 【CPU微架构设计】分布式多端口(4写2读)寄存器堆设计

    寄存器堆(Register File)是微处理的关键部件之一.寄存器堆往往具有多个读写端口,其中写端口往往与多个处理单元相对应.传统的方法是使用集中式寄存器堆,即一个集中式寄存器堆匹配N个处理单元.随 ...

  10. 与python的三天

    #导入海龟图 import turtleturtle.showturtle()turtle.width(20)liebiao = ['red','blue','yellow','green','pur ...