首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

MyBatis 整合 Jersey 實現數據庫讀取與 REST 接口暴露完整實戰

     編輯:Java 相關知識

實戰場景

本文演示如何使用 MyBatis 訪問 MySQL 數據庫,並通過 Jersey 框架將查詢結果以 RESTful JSON 接口對外提供。完整涵蓋:建表腳本、POJO 映射、Mapper XML、MyBatis 配置、REST Resource 類編寫。

1. 數據庫準備

-- 建庫建表腳本 (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);

2. 實體類

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 省略...
}

3. Mapper 映射文件

<?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>

4. MyBatis 核心配置

<?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>

5. REST Resource 類

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(); // 必須關閉會話
        }
    }
}

6. 關鍵點提示

  • SqlSession 非線程安全:每次請求開新會話,用完即關,切勿作為成員變量共享。
  • @XmlRootElement:讓 Jersey 自動將 POJO 序列化為 JSON/XML。
  • 生產環境建議:將 SqlSessionFactory 提取為單例、配置連接池、整合 Spring 管理事務。

源碼下載

完整項目源碼:點擊下載

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved