Mybatis之执行自定义SQL举例

本文说明如何使用Mybatis执行我自定义输入的SQL语句。

需要的mybaits文件包括:配置文件(mybatis-config-dao.xml 和 jdbc.properties)、接口文件(ISqlMapper.class)、xml文件 (sqlMapper.xml)、工具类(MybatisUtils.class)。

依赖包:

 1         <dependency>
 2             <groupId>org.mybatis</groupId>
 3             <artifactId>mybatis</artifactId>
 4             <version>3.4.6</version>
 5         </dependency>
 6
 7         <dependency>
 8             <groupId>mysql</groupId>
 9             <artifactId>mysql-connector-java</artifactId>
10             <version>5.1.47</version>
11         </dependency>

mybatis配置文件:

mybatis-config-dao.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <!--从外部配置文件导入jdbc信息-->
 7     <properties resource="config/jdbc.properties"></properties>
 8
 9     <environments default="development">
10         <environment id="development">
11             <transactionManager type="JDBC"/>
12             <dataSource type="POOLED">
13                 <property name="driver" value="${driver}"/>
14                 <property name="url" value="${url}"/>
15                 <property name="username" value="${username}"/>
16                 <property name="password" value="${password}"/>
17             </dataSource>
18         </environment>
19     </environments>
20
21     <!--指定映射资源文件-->
22     <mappers>
23         <mapper resource="mapper/shelby/userMapper.xml"/>
24         <mapper resource="mapper/shelby/sqlMapper.xml"/>
25     </mappers>
26
27 </configuration>

jdbc.properties

# jdbc连接信息
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://10.15.1.232:3306/maserati_x??zeroDateTimeBehavior=convertToNull&amp;useUnicode=true&amp;characterEncoding=utf-8
username=root
password=

接口文件 ISqlMapper.class

 1 package testTraffic.mapper.shelby;
 2
 3 import java.util.List;
 4 import java.util.Map;
 5
 6 public interface ISqlMapper {
 7
 8     Integer insert(String statement);
 9
10     Integer delete(String statement);
11
12     Integer update(String statement);
13
14     List<Map<String, Object>> selectList(String statement);
15
16     String selectOne(String statement);
17 }

sqlMapper.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3
 4 <mapper namespace="testTraffic.mapper.shelby.ISqlMapper">
 5     <insert id="insert" parameterType="java.lang.String">
 6         ${value}
 7     </insert>
 8
 9     <select id="selectList" parameterType="java.lang.String" resultType="java.util.HashMap" useCache="false">
10         ${value}
11     </select>
12
13     <select id="selectOne" parameterType="java.lang.String" resultType="java.lang.String" useCache="false">
14         ${value}
15     </select>
16
17     <delete id="delete" parameterType="java.lang.String">
18         ${value}
19     </delete>
20
21     <update id="update" parameterType="java.lang.String">
22         ${value}
23     </update>
24
25 </mapper>

测试代码:

 1 package testTraffic.testDemo;
 2
 3 import org.apache.ibatis.session.SqlSession;
 4 import org.apache.logging.log4j.LogManager;
 5 import org.apache.logging.log4j.Logger;
 6 import org.junit.Test;
 7 import testTraffic.mapper.shelby.ISqlMapper;
 8 import testTraffic.mapper.shelby.UserMapper;
 9 import testTraffic.utils.MybatisUtils;
10
11 import java.util.List;
12
13 /**
14  * @Auther:GongXingRui
15  * @Date:2019/1/24
16  * @Description:
17  **/
18 public class TestMybatisDemo {
19     private static Logger logger = LogManager.getLogger(TestMybatisDemo.class);
20
21     // 直接执行SQL语句
22     @Test
23     public void testMybatisSelectOne() {
24         String sql = "select user_name from t_admin_user where id = 2";
25         ISqlMapper sqlMapper = MybatisUtils.getMapper(ISqlMapper.class);
26         String name = sqlMapper.selectOne(sql);
27         logger.info(name);
28     }
29
30     // 多个查询
31     @Test
32     public void testMybatisSelectList() {
33         String sql = "select user_name from t_admin_user";
34         ISqlMapper sqlMapper = MybatisUtils.getMapper(ISqlMapper.class);
35         List list = sqlMapper.selectList(sql);
36         logger.info(list);
37     }
38
39     // 删除与插入
40     @Test
41     public void testMybatisDeleteInsert() {
42         ISqlMapper sqlMapper = MybatisUtils.getMapper(ISqlMapper.class);
43
44         String deleteSql = "delete from t_admin_user  WHERE user_name = ‘testuser‘;";
45         String insertSql = "insert into `t_admin_user` (`id`, `user_name`, `user_password`, `del_flag`, `create_time`, `update_time`) VALUES( null,‘testuser‘,‘testuser123‘,‘0‘,‘2019-01-21 19:43:58‘,‘2019-01-22 19:44:03‘);";
46         int n = sqlMapper.delete(deleteSql);
47         logger.info("删除数据:" + n);
48         n = sqlMapper.insert(insertSql);
49         logger.info("插入数据:" + n);
50 //        MybatisUtils.getSession().commit();
51     }
52
53 }

自己封装的Mybatis工具类(MybatisUtils.class)

 1 package testTraffic.utils;
 2
 3 import org.apache.ibatis.io.Resources;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.apache.ibatis.session.SqlSessionFactory;
 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 7
 8 import java.io.IOException;
 9 import java.io.InputStream;
10
11 /**
12  * @Description: 生成mybatis的session对象
13  **/
14 public class MybatisUtils {
15     private static String resource = "config/mybatis-config-dao.xml";
16     private static SqlSessionFactory sqlSessionFactory = null;
17     private static SqlSession session = null;
18
19
20     private static void init() {
21         try {
22             InputStream inputStream = Resources.getResourceAsStream(resource);
23 //            创建工厂
24             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
25 //            创建session对象
26             session = sqlSessionFactory.openSession(true);
27         } catch (IOException e) {
28             e.printStackTrace();
29         }
30     }
31
32     public static SqlSession getSession() {
33         if (session == null) {
34             init();
35         }
36         return session;
37     }
38
39     public static void close() {
40         if (session != null) {
41             session.close();
42             session = null;
43         }
44     }
45
46     public static <T> T getMapper(Class<T> tClass) {
47         if (session == null) {
48             init();
49         }
50         return session.getMapper(tClass);
51     }
52
53     public static void commit() {
54         if (session != null) {
55             session.commit();
56         }
57     }
58
59
60 }


原文地址:https://www.cnblogs.com/gongxr/p/10313639.html

时间: 2024-10-28 11:58:55

Mybatis之执行自定义SQL举例的相关文章

django不定义model,直接执行自定义SQL

如果不想定义model,直接执行自定义SQL,可如下操作: 1. 通过 connections获取db连接,如果是多个数据库,connections['dbName'] 来选择 2. 获取游标 cursor 3. 执行sql: cursor.execute(sql) 4.获取返回结果:fetchone,fetchall (fetchall返回的是元祖,非字典) from django.db import connections cursor = connections['test_db'].cu

Python Django 之 直接执行自定义SQL语句(一)

一.执行自定义SQL方法 1.Executing custom SQL directly 直接执行自定义SQL,这种方式可以完全避免数据模型,而是直接执行原始的SQL语句. 2.Manager.raw() 执行原始查询并返回模型实例 二.Executing custom SQL directly Manager.raw() 远远不够,可直接执行自定义SQL,directly execute UPDATE , INSERT , or DELETE queries.django.db.connect

MYSQL可调用执行自定义SQL的代码

DELIMITER $$ USE `mysql_wispeed01`$$ DROP PROCEDURE IF EXISTS `sp_execSQL`$$ CREATE DEFINER=`sa`@`%` PROCEDURE `sp_execSQL`(inSql VARCHAR(4000)) BEGIN DECLARE l_sql VARCHAR(4000); SET l_sql=CONCAT_WS(' ',inSql); SET @sql=l_sql; PREPARE s1 FROM @sql;

MyBatis输出执行的SQL到控制台

src\main\resources\application.properties 或者src\main\resources\application.yml 在你的application.properties或application.yml配置文件中加 logging.level.com.hotel3.mapper=debug 其中com.hotel3.mapper=debug为:你的Mapper包=日志等 控制台输出如下: 原文地址:https://www.cnblogs.com/mww-NO

11.Django数据库操作(执行原生SQL)

1.使用extra方法 解释:结果集修改器,一种提供额外查询参数的机制 说明:依赖model模型 用在where后: Book.objects.filter(publisher_id="1").extra(where=["title='python学习1'"]) 用在select后 Book.objects.filter(publisher_id="1").extra(select={"count":"select

django 执行原始SQL

二.知识点总结 When the model query APIs don’t go far enough, you can fall back to writing raw SQL. go far enough:远远不够fall back to:求助 raw:原始的,未加工的 Django提供两种方式执行(performing)原始的SQL查询: (1) . Manager.raw():执行原始查询并返回模型实例 (2) . Executing custom SQL directly :直接执

在django中,执行原始sql语句

extra()方法 结果集修改器,一种提供额外查询参数的机制 使用extra: 1:Book.objects.filter(publisher__name='广东人员出版社').extra(where=['price>50']) Book.objects.filter(publisher__name='广东人员出版社',price__gt=50) 2:Book.objects.extra(select={'count':'select count(*) from hello_Book'}) ra

django执行源生sql

执行源生sql在python中我们可以借助pymysql模块来进行执行源生sql关于pymysql执行源生sql可以看我的另外一篇博文:pymysql应用 本篇博客只介绍django中执行的源生sql 1.使用extra方法 解释:结果集修改器,一种提供额外查询参数的机制 说明:依赖model模型 使用方式: 用在where后: Book.objects.filter(publisher_id="1").extra(where=["title='python学习1'"

【Django】执行原生SQL的三种方法 &#632542;

原文: http://blog.gqylpy.com/gqy/383 "> 如下三种方式 extra:结果集修改器,一种提供额外查询参数的机制 raw:执行原始SQL返回模型实例 connection/connections:直接执行自定义SQL(此方法不依赖model) 1.extra示例: # extra # 在QuerySet的基础上继续执行子语句 # extra(self, select=None, where=None, params=None, tables=None, ord