本文演示如何使用 MyBatis 訪問 MySQL 數據庫,並通過 Jersey 框架將查詢結果以 RESTful JSON 接口對外提供。完整涵蓋:建表腳本、POJO 映射、Mapper XML、MyBatis 配置、REST Resource 類編寫。
-- 建庫建表腳本 (MySQL)
CREATE DATABASE IF NOT EXISTS mybatis;
USE mybatis;
CREATE TABLE IF NOT EXISTS `Student` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
`age` int(4) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `Student` (`id`, `name`, `age`) VALUES (1, 'zhangsan', 20);
package com.mtour.mybatis.demo;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement // 支援 JAXB 自動轉 JSON/XML
public class Student {
private int id;
private String name;
private int age;
// Getter/Setter 省略...
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://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>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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>
package com.mtour.mybatis.demo;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import org.apache.ibatis.session.*;
@Path("/student")
public class StudentResource {
private static final String CONFIG = "conf.xml";
private static final SqlSessionFactory FACTORY =
new SqlSessionFactoryBuilder().build(
StudentResource.class.getClassLoader().getResourceAsStream(CONFIG)
);
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello jersey, first demo";
}
@GET
@Path("/{name}")
@Produces("text/plain;charset=UTF-8")
public String helloName(@PathParam("name") String name) {
return "Hello " + name;
}
@GET
@Path("/getstudent/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Student getStudent(@PathParam("id") String id) {
SqlSession session = FACTORY.openSession();
try {
return session.selectOne(
"com.mtour.mybatis.demo.studentMapper.getStudent",
Integer.valueOf(id)
);
} finally {
session.close(); // 必須關閉會話
}
}
}
SqlSessionFactory 提取為單例、配置連接池、整合 Spring 管理事務。完整項目源碼:點擊下載