目录
1. 在mapper文件中配置SQL
这是我在html文件中对于这个select语句进行了定义
<?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.test.cis.dao.accounts.FinanceRefundApplyDao">
<select id="queryById" resultType="FinanceRefundApplyModel" parameterType="String">
select * from FINANCE_REFUND_APPLY where ID = #{id}
</select>
</mapper>
现在我们来研究一下怎么调用这一个sql语句
首先我们想要要在对应的mapper里面,保有对于这个语句的接口
package com.test.cis.dao.accounts;
import com.test.cis.model.FinanceRefundApplyModel;
public interface FinanceRefundApplyDao {
FinanceRefundApplyModel queryById(String id);
}
然后我们仍然得保留好我们需要的MyBatis的配置文件(通常是mybatis-config.xml
)中配置这个Mapper接口的路径,以便MyBatis能够找到它。配置可能如下所示:
<configuration>
<!-- 其他配置 -->
<mappers>
<mapper resource="com/test/cis/dao/accounts/FinanceRefundApplyDao.xml"/>
</mappers>
</configuration>
然后下面这段程序 我们加载了MyBatis的配置文件 mybatis-config.xml
,并创建了一个 SqlSessionFactory
对象。然后,我们使用这个工厂来创建一个 SqlSession
对象。在这个 SqlSession
中,我们获取了 FinanceRefundApplyDao
接口的实例,并调用了其中的 queryById
方法来执行SQL查询语句。
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.test.cis.dao.accounts.FinanceRefundApplyDao;
import com.test.cis.model.FinanceRefundApplyModel;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 打开一个会话
try (SqlSession session = sqlSessionFactory.openSession()) {
// 获取Mapper接口的实例
FinanceRefundApplyDao dao = session.getMapper(FinanceRefundApplyDao.class);
// 调用Mapper接口中的方法执行SQL语句
FinanceRefundApplyModel model = dao.queryById("your_id_here");
System.out.println(model); // 处理查询结果
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 注解式的SQL定义
public interface UserMapper {
@Select("select * from user ")
List<User> AnnotationGetUserList();
}
如果想要的是动态SQL,那么就加上<script>:
public interface UserMapper {
@Select("select * from user ")
List<User> AnnotationGetUserList();
@Select("<script>"
+ "select * from user "
+ "<if test='id!=null'>"
+ "where id=#{id}"
+ "</if>"
+ "</script>")
List<User> AnnotationGetUserById(@Param("id")String id);
}
3.通过@SelectProvider来声明sql提供类
public interface UserMapper {
@SelectProvider(type=SqlProvider.class,method="getUserById")
List<User> AnnotationProviderGetUserById(String id);
}
public class SqlProvider {
public String getUserById(String id) {
String sql = "select * from user ";
if (id!=null) {
sql += " where id="+id;
}
return sql;
}
}