通过mybatis读取数据库数据并提供rest接口访问
1 mysql 创建数据库脚本
-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: 2016-08-02 18:13:50
-- 服务器版本: 5.6.21
-- PHP Version: 5.6.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */; --
-- Database: `mybatis`
-- -- -------------------------------------------------------- --
-- 表的结构 `Student`
-- CREATE TABLE IF NOT EXISTS `Student` (
`id` int(10) NOT NULL,
`name` varchar(256) NOT NULL,
`age` int(4) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; --
-- 转存表中的数据 `Student`
-- INSERT INTO `Student` (`id`, `name`, `age`) VALUES
(1, 'zhansan', 20); --
-- Indexes for dumped tables
-- --
-- Indexes for table `Student`
--
ALTER TABLE `Student`
ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `Student`
--
ALTER TABLE `Student`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
2 创建与数据库表Student对应的pojo类
package com.mtour.mybatis.demo; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement
public class Student {
int id;
String name;
int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3 创建映射 studentMapper
<?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.mtour.mybatis.demo.studentMapper"> <select id="getStudent" parameterType="int"
resultType="com.mtour.mybatis.demo.Student">
select * from Student where id=#{id}
</select>
</mapper>
4. 创建 conf.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="" />
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/mtour/mybatis/demo/studentMapper.xml"/>
</mappers> </configuration>
5. 创建 rest 资源
package com.mtour.mybatis.demo; import java.io.IOException;
import java.io.InputStream; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType; @Path("/student")
public class demo { static String resource = "conf.xml";
static InputStream is = demo.class.getClassLoader().getResourceAsStream(resource);
static SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); @GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello() {
return "hello jersey , first demo" ;
} @GET
@Path("/{param}")
@Produces("text/plain;charset=UTF-8")
public String sayHelloToUTF8(@PathParam("param") String username) {
return "Hello " + username;
} @GET
@Path("/getstudent/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Student getUserJson(@PathParam("id") String id) { Integer studentId = Integer.valueOf(id); SqlSession session = sessionFactory.openSession(); String statement = "com.mtour.mybatis.demo.studentMapper.getStudent"; Student s = session.selectOne(statement, studentId); session.close(); return s;
} }
6. 启动调试

源码下载: http://download.csdn.net/detail/mtour/9593217
通过mybatis读取数据库数据并提供rest接口访问的更多相关文章
- # spring boot + mybatis 读取数据库
spring boot + mybatis 读取数据库 创建数据库 use testdb; drop table if exists t_city; create table t_city( id i ...
- 读取数据库数据,并将数据整合成3D饼图在jsp中显示
首先我将生成饼图的方法独立写成一个PieChar.java类,详细代码如下:(数据库需要自己建,如有需要的话) import java.io.IOException; import java.sql. ...
- C#使用SqlDataReader读取数据库数据时CommandBehavior.CloseConnection参数的作用
主要用在ExecuteReader(c)中,如果想要返回对象前不关闭数据库连接,须要用CommandBehavior.CloseConnection: CloseConnection解决了流读取数据模 ...
- 利用nodejs读取数据库数据生成树结构的json数据
在做后台管理界面的时候,几乎少不了的一个结构就是树形结构,用来做菜单导航: 那么,最希望的就是树结构的所有数据都是读取的数据库,而不是直接代码当中写死,那我们就一步一步来看: 一,建表 字段通常包括: ...
- pandas.read_sql_query()读取数据库数据用chunksize的坑
最近一项工作需要读取数据库中1500万条数据,考虑到数据量太大,不方便直接一次性读取,不然会内存爆炸.想到用pandas.read_sql_query()里有一个chunksize可以分批返回chun ...
- 在ASP.NET Core 中怎样使用 EF 框架读取数据库数据
添加测试数据 我们首先使用 SQLite Studio 添加三条数据 ID Name 1 李白 2 杜甫 3 白居易 使用 SQLite Studio 打开我们的 blogging.db 数据库,双击 ...
- python读取数据库数据,读取出的中文乱码问题
conn = pymysql.connect( host='127.0.0.1', port=3302, user='username', passwd='password', db=database ...
- ThinkPHP:读取数据库数据 (2)
项目配置文件Conf/config.php中添加数据库连接信息: // 添加数据库配置信息 'DB_TYPE' => 'mysql', // 数据库类型 'DB_HOST' => 'loc ...
- Java MyBatis insert数据库数据后返回主键
<selectKey keyProperty="id" resultType="java.lang.Long" order="AFTER&quo ...
随机推荐
- 【elasticsearch】(1)centos7 使用yum安装elasticsearch 2.X
前言 elasticsearch(下面称为ES)是一个基于Lucene的搜索服务器(By 百度百科:查看).所以他需要java的环境即jdk,这里提供懒人一键安装方式 # yum install ja ...
- SQL70001: This statement is not recognized in this context.
关于错误: SQL70001: This statement is not recognized in this context. 的产生原因以及解决办法. 在SQL Server Databas ...
- WPF提示框效果
WPF提示框效果 1,新建WPF应用程序 2,添加用户控件Message 3,在Message中编写如下代码 <Border x:Name="border" BorderTh ...
- iPhone分辨率
分辨率和像素 1.iPhone5 4" 分辨率320x568,像素640x1136,@2x 2.iPhone6 4.7" 分辨率3 ...
- 2016030202 - github中sshkey信息设置
根据github上面的提示生成ssh秘钥步骤 参考url:https://help.github.com/articles/generating-an-ssh-key/ 1.生成sshkey之前,检查 ...
- System.Reflection.Assembly.GetEntryAssembly()获取的为当前已加载的程序集
今天在使用System.Reflection.Assembly.GetEntryAssembly()获取程序集时,发现获取的程序集不全.原来是因为C#的程序集为延迟加载,此方法只获取当前已加载的,未加 ...
- 领域驱动设计(Domain Driven Design)参考架构详解
摘要 本文将介绍领域驱动设计(Domain Driven Design)的官方参考架构,该架构分成了Interfaces.Applications和Domain三层以及包含各类基础设施的Infrast ...
- Windows窗口样式速查参考,Delphi窗口控件的风格都有它们来决定(附Delphi何时用到它们,并举例说明)good
/* 窗口样式参考列表(都是GetWindowLong的GWL_STYLE风格,都是TCreateParams.Sytle的一部分),详细列表如下:https://msdn.microsoft.com ...
- DragSortListView学习总结
Drag-sort-listview 是一个支持拖拽排序和左右滑动删除功能的自定义ListView,重写了 TouchInterceptor类来提供更加优美的拖拽动画效果. DSLV主要特性: 完美的 ...
- lc面试准备:Regular Expression Matching
1 题目 Implement regular expression matching with support for '.' and '*'. '.' Matches any single char ...