springboot+MyBatis 操作SQLServer提供暴露所有接口的说明

 

 

1.springboot简介

       Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解,就是 Spring Boot 其实不是什么新的框架,它默认配置了很多框架的使用方式,就像 Maven 整合了所有的 Jar 包,Spring Boot 整合了所有的框架。

      springboot有四个核心:

       1)自动配置;

       2)起步依赖;

       3)命令行界面;

      4)Actuator:深入运行的SpringBoot应用程序,可以了解整个技术框架的原理。

      对于SpringBoot来说,可以极快开发一个Restful风格的Web服务。因为springboot框架整合了spring样板。但值得说的是:springgboot给你呈现的是优雅的一面的同时,是隐藏着的无尽复杂和冗余;因此,深入学习springboot其实还是很有难度的。

2.MyBatis简介

       MyBatis是一个Java持久化框架,它通过XML描述符或注解把对象与存储过程或SQL语句关联起来,映射成数据库内对应的纪录。与其他对象关系映射框架不同,MyBatis没有将Java对象与数据库表关联起来,而是将Java方法与SQL语句关联。MyBatis允许用户充分利用数据库的各种功能,例如存储过程、视图、各种复杂的查询以及某数据库的专有特性。如果要对遗留数据库、不规范的数据库进行操作,或者要完全控制SQL的执行,MyBatis是一个不错的选择。
       与JDBC相比,MyBatis简化了相关代码:SQL语句在一行代码中就能执行。MyBatis提供了一个映射引擎,声明式的把SQL语句执行结果与对象树映射起来。通过使用一种内建的类XML表达式语言,或者使用Apache Velocity集成的插件,SQL语句可以被动态的生成。

       与Hibernate相比,MyBatis具有如下优势:

       1)MyBatis可以进行更为细致的SQL优化,可以减少查询字段。

       2)MyBatis容易掌握,而Hibernate门槛较高。

       缺点也比较明显:

       1)SQL语句可能不兼容;

       2)DAO层开发比MyBatis简单,Mybatis需要维护SQL和结果映射;

       3)缓存机制不佳。

3.springboot+MyBatis操作SQLServer

       在Eclipse上建立SpringBoot样例,需要如下操作:

1)安装springboot插件。

在Help里选择EclipseMarketplace,然后搜sts,随后安装。

       

2)新建springboot样例。

      当新建工程的时候,能出现SpingBoot的样例时,说明安装成功。

       

(1)新建SpringStarterProject(注意JAVA版本号的选择)

 

(2)选择Web、MyBatis和SQLServer支持。

(3)几种文件类型的定义

本工程会牵涉几个文件:

<1>pom.xml文件:用于定义Maven文件依赖;

<2>application.properties文件(或application.yml文件):用于定义工程属性,关于依赖库的基本定义均可以在这里定义。

<3>controller文件:用于定义网络访问接口;

<4>service文件:用于定义访问的服务具体实现;

<5>entity文件:用于定义访问的实体文件;

<6>dao的JAVA程序接口文件:用于定义访问数据库的程序;

<7>dao的XML文件:用于定义MyBatis的程序与SQL语句的转换。

(4)建立Controller

package com.xxx.springboot.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxx.springboot.dao.UserDao;
import com.xxx.springboot.entity.User;
import com.xxx.springboot.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }

    @Override
    public int addUser(User user) {
        SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setCreatedTime(form.format(new Date()));
        return userDao.addUser( user );
    }

    @Override
    public int deleteUser(User user) {
        return userDao.deleteUser(user);
    }
}

(5)建立service接口

package com.xxx.springboot.service;

import java.util.List;

import com.xxx.springboot.entity.User;

public interface IUserService {
	public List<User> getAllUsers();

    public int addUser(User user);

    public int deleteUser(User user);
}

(6)建立service实现

package com.xxx.springboot.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xxx.springboot.dao.UserDao;
import com.xxx.springboot.entity.User;
import com.xxx.springboot.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }

    @Override
    public int addUser(User user) {
        SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setCreatedTime(form.format(new Date()));
        return userDao.addUser( user );
    }

    @Override
    public int deleteUser(User user) {
        return userDao.deleteUser(user);
    }
}

(7)建立entity接口

package com.xxx.springboot.entity;

public class User {
	private Integer userId;
    private String userName;
    private Boolean sex;
    private String createdTime;
    
    public User(Integer userId, String userName, Boolean sex, String createdTime) {
        this.userId = userId;
        this.userName = userName;
        this.sex = sex;
        this.createdTime = createdTime;
    }
    
    public User() {
        super();
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public String getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(String createdTime) {
        this.createdTime = createdTime;
    }
}

(8)建立Dao接口

package com.xxx.springboot.dao;

import java.util.List;

import com.xxx.springboot.entity.User;

public interface UserDao {
	List<User> getAllUsers();
    int addUser(User user);
    int deleteUser(User user);
}

(9)建立DAO的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.xxx.springboot.dao.UserDao">

	<resultMap id="UserMap" type="com.xxx.springboot.entity.User">
        <id property="userId" column="user_id" javaType="java.lang.Integer"></id>
        <result property="userName" column="user_name" javaType="java.lang.String"></result>
        <result property="sex" column="sex" javaType="java.lang.Boolean"></result>
        <result property="createdTime" column="created_time" javaType="java.lang.String"></result>
    </resultMap>

    <select id="getAllUsers" resultMap="UserMap">
        select * from user_test order by user_id;
    </select>

    <insert id="addUser" parameterType="com.xxx.springboot.entity.User">
        insert into user_test ( user_id, user_name, sex, created_time ) values ( #{userId}, #{userName}, #{sex}, #{createdTime} )
    </insert>

    <delete id="deleteUser" parameterType="com.xxx.springboot.entity.User">
        delete from user_test where user_name = #{userName}
    </delete>
</mapper>

(10)配置Application.properties

server.port=服务器端口配置

# mybatis 配置
mybatis.type-aliases-package=com.xxx.springboot.entity
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.config-locations=classpath:mybatis-config.xml
mybatis.configuration.map-underscore-to-camel-case=true

## -------------------------------------------------

## SqlServer 配置
spring.datasource.url=jdbc:sqlserver://127.0.0.1:端口;databasename=数据库名
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=数据用户名
spring.datasource.password=数据库密码

(11)配置MyBatis的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>
        <setting name="useGeneratedKeys" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
	<typeAliases>
        <package name="com.xxx.springboot.dao"></package>
    </typeAliases>
</configuration>

4.暴露接口

          但此文件的去点是,无法获得所有可以访问的URL,本程序提供的URL访问程序如下。

   

package com.xxx.springboot.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.google.gson.Gson;


@RestController
public class getAllURL {
	@Autowired
	WebApplicationContext applicationContext;
 
	@RequestMapping(value = "v2/getAllUrl", method = RequestMethod.GET)
	public Object getAllUrl() {		
		RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
		
		// 获取url与类和方法的对应信息
		Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
 
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();		

		System.out.print("At beginning, List is: ");
		System.out.println(list);
		
		for (Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
			Map<String, String> map1 = new HashMap<String, String>();
			RequestMappingInfo info = m.getKey();  
            HandlerMethod method = m.getValue();  
            PatternsRequestCondition p = info.getPatternsCondition();  
            for (String url : p.getPatterns()) {  
            	map1.put("url", url);
            }  
            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名  
            map1.put("method", method.getMethod().getName()); // 方法名 
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
            	map1.put("type", requestMethod.toString());
			}
			
            list.add(map1);
		}		

		Gson gson = new Gson();
		String str = gson.toJson(list);  
 
		return str;
	}
}

在以上程序完成以后,右击该程序,采用Spring Boot App程序运行即可。

5.注意可能存在的问题

1) 如果其他程序文件在SpringBootStarter.java同级,会造成运行不成功;

2)Maven是联合编译工具,但有可能会因为服务器在国外而被GFW墙掉,注意设置本地资源,我的设置为:

<mirrors>
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>

      <mirror>
          <id>alimaven</id>
          <mirrorOf>aliyun maven</mirrorOf>
          <name>http://maven.aliyun.com/nexus/content/groups/public/</name>
          <url>central</url>
    </mirror>
    
    <mirror> 
        <id>uk</id>  
        <mirrorOf>central</mirrorOf>  
        <name>Human Readable Name for this Mirror.</name>  
        <url>http://uk.maven.org/maven2/</url> 
    </mirror>

   <mirror>
        <id>CN</id>
        <name>OSChina Central</name>
        <url>http://maven.oschina.net/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>
  </mirror>

  <mirror>
        <id>nexus</id>
        <name>internal nexus repository</name>
        <url>http://repo.maven.apache.org/maven2</url>
        <mirrorOf>central</mirrorOf>
  </mirror>

  </mirrors>

 

3)第一写程序的时候,由于MAVEN在联合编译下载JAR包,会造成程序有确实。

4)还可能hui有JAR包确实,这个时候需要添加MAVEN的依赖。

 

附:本程序样例上传到GitHub地址:

https://github.com/diziqian/springBootExample

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值