Ibatis使用实践 - 1

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS MySQL,高可用系列 2核4GB
简介:

1、定义POJO类:Student.java

package com.alibaba.ibatis.modules;

public  class Student {
   private  int id;
   private String name;
   private String address;
   private  float score;

   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 String getAddress() {
     return address;
  }

   public  void setAddress(String address) {
     this.address = address;
  }

   public  float getScore() {
     return score;
  }

   public  void setScore( float score) {
     this.score = score;
  }

  @Override
   public String toString() {
     return  "id: " + id +  ", name: " + name +  ", address: " + address
        +  ", score: " + score;

  }
}

2、定义使用接口:StudentService.java

package com.alibaba.ibatis.service;

import java.util.List;

import com.alibaba.ibatis.modules.Student;

public  interface StudentService {
   public  void addStudent(Student student);
   public  int updateStudent(Student student);
   public  int deleteStudent(Student student);
   public Student getStudentById( int id);
   public List<Student> getStudentsLike(String likeName);
   public List<Student> getAllStudents(); 
}
增加StudentService的实现类:StudentServiceImpl.java
package com.alibaba.ibatis.service.impl;

import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import com.alibaba.ibatis.modules.Student;
import com.alibaba.ibatis.service.StudentService;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public  class StudentServiceImpl  implements StudentService {

   static SqlMapClient sqlMapClient =  null;
   static {
    String resource =  "SqlMapConfig.xml";
     try {
      Reader reader = Resources.getResourceAsReader(resource);
      sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
    }  catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
   public  void addStudent(Student student) {
     try {
      sqlMapClient.insert( "insertStudent", student);
    }  catch (SQLException e) {
      e.printStackTrace();
    }
  }

  @Override
   public  int deleteStudent(Student student) {
     int effectedRow = 0;
     try {
      effectedRow = sqlMapClient.delete( "deleteStudent", student);
    }  catch (SQLException e) {
      e.printStackTrace();
    }
     return effectedRow;
  }

  @SuppressWarnings( "unchecked")
  @Override
   public List<Student> getAllStudents() {
    List<Student> students =  null;
     try {
      students = sqlMapClient.queryForList( "getAllStudents");
    }  catch (SQLException e) {
      e.printStackTrace();
    }
     return students;
  }

  @Override
   public Student getStudentById( int id) {
    Student student =  null;
     try {
      student = (Student) sqlMapClient.queryForObject( "getStudentById",
          id);
    }  catch (SQLException e) {
      e.printStackTrace();
    }
     return student;
  }

  @Override
   public  int updateStudent(Student student) {
     int effectedRow = 0;
     try {
      effectedRow = sqlMapClient.update( "updateStudent", student);
    }  catch (SQLException e) {
      e.printStackTrace();
    }
     return effectedRow;
  }

  @SuppressWarnings( "unchecked")
  @Override
   public List<Student> getStudentsLike(String likeName) {
    List<Student> students =  null;
     try {
      students = sqlMapClient.queryForList( "getStudentsLike", likeName);
    }  catch (SQLException e) {
      e.printStackTrace();
    }
     return students;
  }

}

3、Ibatis的三个配置文件:

(1)与数据连接相关的配置文件jdbc.properties, 
(2)操作具体POJO的增删改查的配置文件
(3)总控文件
 
(1)与数据连接相关的配置文件:jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ibatis
username=ibatis
password=ibatis
Pool.MaximumActiveConnections=10
Pool.MaximumIdleConnections=5
Pool.MaximumCheckoutTime=120000
Pool.TimeToWait=500
(2)操作具体POJO的增删改查的配置文件:student.xml, 其中对模糊查询的情况需要特别的注意:必须使用$来做占位符,如: SELECT * FROM student where name like '%$name$%'
<? xml  version ="1.0"  encoding ="UTF-8"  ?>

<!DOCTYPE sqlMap                        
                PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"                        
                "http://ibatis.apache.org/dtd/sql-map-2.dtd">

< sqlMap  namespace ="modules.student" >
   < typeAlias  alias ="Student"  type ="com.alibaba.ibatis.modules.Student"  />

   < insert  id ="insertStudent"  parameterClass ="Student" >
    INSERT INTO
    student(id, name, address, score)
    VALUES(#id#,#name#,#address#,#score#)
   </ insert >

   < select  id ="getStudentById"  parameterClass ="int"  resultClass ="Student" >
    SELECT * FROM student where id = #id#
   </ select >

   < select  id ="getAllStudents"  resultClass ="Student" >
    SELECT * FROM student
   </ select >
  
   < select  id ="getStudentsLike"  resultClass ="Student"  parameterClass ="String" >
    SELECT * FROM student where name like  '%$name$%'
   </ select >

   < update  id ="updateStudent"  parameterClass ="Student" >
    UPDATE student set
    name = #name#, address = #address#, score = #score# where id = #id#
   </ update >

   < delete  id ="deleteStudent"  parameterClass ="Student" >
    DELETE FROM
    student where id = #id# and name = #name# and address = #address# and
    score = #score#
   </ delete >

</ sqlMap >        
 
(3)总控文件:SqlMapConfig.xml
<? xml  version ="1.0"  encoding ="UTF-8"  ?>

<!DOCTYPE sqlMapConfig                        
                PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"                        
                "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

< sqlMapConfig >
   < properties  resource ="jdbc.properties"  />
   < transactionManager  type ="JDBC" >
     < dataSource  type ="SIMPLE" >
       < property  name ="JDBC.Driver"  value ="${driver}"  />
       < property  name ="JDBC.ConnectionURL"  value ="${url}"  />
       < property  name ="JDBC.Username"  value ="${username}"  />
       < property  name ="JDBC.Password"  value ="${password}"  />
       < property  name ="Pool.MaximumActiveConnections"  value ="${Pool.MaximumActiveConnections}"  />
       < property  name ="Pool.MaximumIdleConnections"  value ="${Pool.MaximumIdleConnections}"  />
       < property  name ="Pool.MaximumCheckoutTime"  value ="${Pool.MaximumCheckoutTime}"  />
       < property  name ="Pool.TimeToWait"  value ="${Pool.TimeToWait}"  />
     </ dataSource >
   </ transactionManager >

   < sqlMap  resource ="com/alibaba/modules/student.xml"  />
</ sqlMapConfig >        
4、引入相应的依赖包:pom.xml
< dependency >
       < groupId >com.alibaba.external </ groupId >
       < artifactId >sourceforge.ibatis </ artifactId >
       < version >2.3.4 </ version >
     </ dependency >
     < dependency >
       < groupId >com.alibaba.external </ groupId >
       < artifactId >jdbc.mysql.mysql-connector </ artifactId >
       < version >5.1.6 </ version >
     </ dependency >
经测试,service中的各接口方法成功执行
 

本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/384686,如需转载请自行联系原作者
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
8月前
|
存储 安全 iOS开发
内存卡怎么格式化?6个格式化方法供你选
随着使用时间的增加,内存卡可能会因为数据积累、兼容性或是文件系统损坏等原因需要进行格式化。那么怎样正确格式化内存卡呢?格式化内存卡的时候需要注意什么呢?本文会给大家提供详细的步骤,帮助大家轻松完成格式化内存卡的操作。
|
9月前
|
SQL Java 数据库连接
MyBatis-Plus高级用法:最优化持久层开发
MyBatis-Plus 通过简化常见的持久层开发任务,提高了开发效率和代码的可维护性。通过合理使用条件构造器、分页插件、逻辑删除和代码生成器等高级功能,可以进一步优化持久层开发,提升系统性能和稳定性。掌握这些高级用法和最佳实践,有助于开发者构建高效、稳定和可扩展的企业级应用。
548 13
|
11月前
|
Python
【10月更文挑战第6天】「Mac上学Python 12」基础篇6 - 输入输出与格式化详解
本篇将详细介绍Python中的输入和输出函数,包括 `print()` 和 `input()` 函数的使用,涵盖格式化输出、类型转换及常见的字符串格式化方法。通过学习本篇,用户将掌握如何使用Python进行输入输出操作,并能灵活运用格式化输出处理数据。
200 1
【10月更文挑战第6天】「Mac上学Python 12」基础篇6 - 输入输出与格式化详解
|
人工智能
[做初中数学题做到打起来了]跟同事为了他小孩的数学题杠上了
4只小鸭子在一个大的圆形水池中,分别随机的出现在圆圈中的任意一点。4只鸭子出现在同一个半圆内的概率是多少?本文将带领大家使用蒙特卡洛方法求解此题。
1167 0
[做初中数学题做到打起来了]跟同事为了他小孩的数学题杠上了
|
6天前
|
人工智能 运维 安全
|
4天前
|
人工智能 异构计算
敬请锁定《C位面对面》,洞察通用计算如何在AI时代持续赋能企业创新,助力业务发展!
敬请锁定《C位面对面》,洞察通用计算如何在AI时代持续赋能企业创新,助力业务发展!
|
5天前
|
机器学习/深度学习 人工智能 自然语言处理
B站开源IndexTTS2,用极致表现力颠覆听觉体验
在语音合成技术不断演进的背景下,早期版本的IndexTTS虽然在多场景应用中展现出良好的表现,但在情感表达的细腻度与时长控制的精准性方面仍存在提升空间。为了解决这些问题,并进一步推动零样本语音合成在实际场景中的落地能力,B站语音团队对模型架构与训练策略进行了深度优化,推出了全新一代语音合成模型——IndexTTS2 。
529 14
|
11天前
|
人工智能 JavaScript 测试技术
Qwen3-Coder入门教程|10分钟搞定安装配置
Qwen3-Coder 挑战赛简介:无论你是编程小白还是办公达人,都能通过本教程快速上手 Qwen-Code CLI,利用 AI 轻松实现代码编写、文档处理等任务。内容涵盖 API 配置、CLI 安装及多种实用案例,助你提升效率,体验智能编码的乐趣。
896 109