<h3>目标</h3>
实现一个restful服务的查询服务,数据来源mysql数据库,使用mybatis查询。参考了一些网上的例子以及wink框架的example.
<h3>正文</h3>
参考了wink的example,在WEB-INF目录下建立了application
com.myhexin.rest.StudentsResource
appliacation
在web.xml中添加restSdkService的声明,以及刚刚建立的application的申明.
<servlet>
<servlet-name>restSdkService</servlet-name>
<servlet-class>org.apache.wink.server.internal.servlet.RestServlet</servlet-class>
<init-param>
<param-name>applicationConfigLocation</param-name>
<param-value>/WEB-INF/application</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>restSdkService</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
web.xml
然后建立一个java文件,
@Path,两个@Path标签的使用,getStudent的路径为”/student/{studentName}“,
@Produces表示返回值的类型
@GET表示,访问的方法是get
@Path("/student")
public class StudentsResource {
@GET
@Path("/{studentName}")
@Produces(MediaType.APPLICATION_JSON)
public String getStudent(
@PathParam("studentName") String studentName
){
StudentDao dao = new StudentDao();
Student stu = dao.getData(studentName);
Gson gson = new Gson();
return gson.toJson(stu);
}
}
简单的restful查询基本完成,后面是用Mybatis连接数据库。
使用mybatis连接数据库,实现简单查询
StudentDao.java
public class StudentDao {
public Student getData(String name){
String resource = "conf.xml";
//使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = StudentDao.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
String statement = "com.myhexin.mapper.studentInfo";//映射sql的标识字符串
//执行查询返回一个唯一user对象的sql
Student stu = session.selectOne(statement, name);
session.close();
return stu;
}
}
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/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentDao.xml" />
</mappers>
</configuration>
StudentDao.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.myhexin.mapper">
<select id="studentInfo" parameterType="String"
resultType="com.myhexin.model.Student" >
SELECT * from student_info where name = #{name}
</select>
</mapper>
<h3>参考目录</h3>
Mybatis学习总结
用 Java 技术创建 RESTful Web 服务
<h3>环境</h3>
Apache Wink 框架:下载此框架来构建 RESTful Web 服务。
gson:gson-2.2.4.jar
Mybatis:mybatis-3.2.8.jar,mysql-connector-java-5.1.6-bin.jar
网友评论