Home Database Mysql Tutorial mybatics 中调用mysql存储过程。

mybatics 中调用mysql存储过程。

Jun 07, 2016 pm 02:50 PM
mysql storage transfer process

说起mybatics 框架,身边的java开发工程师们基本上都是耳熟能详。 mybatics是apache的一个开源项目,前身为ibatics,2010年此项目由apache软件基金会迁移到了google code,mybatics的确是一款十分优秀的开源持久层框架,sql代码隔离封装、自动POJO映射、jdbc


说起mybatics 框架,身边的java开发工程师们基本上都是耳熟能详。 mybatics是apache的一个开源项目,前身为ibatics,2010年此项目由apache软件基金会迁移到了google code,mybatics的确是一款十分优秀的开源持久层框架,sql代码隔离封装、自动POJO映射、jdbc 动态sql———— mybatics的好处可以说出一箩筐,然而mybatics还有一个十分优秀的特性却往往被人忽略 ----那就是mybatics还支持存储过程的调用。

      不熟悉存储过程的人大都觉得存储过程复杂难懂,认为既然有了dao,那么所有的对数据库操作的逻辑(CRUD)都放到dao层就可以了,存储过程是没有必要的。无论如何,在dao中写java代码总比在数据库中写存储过程要舒服容易的多,又何必多花费时间学习一门新的存储过程语言呢?

     的确,对于以下中小型项目而言,基本的增删改查sql操作就足以应付了(再稍微复杂点也就高级查询,也就把dao层改改弄得稍复杂点就行了)。可是做过稍大型点的项目的人(尤其是互联网方面)都知道,大项目尤其是分布式系统的互联网项目对于数据库安全、性能、稳定性都有很高的要求。 当web服务器和数据库服务器分布在不同的机器上,dao层调数据库服务器是需要很大的网络开销,sql语句必须从web服务器发送到数据库服务器再执行。可是存储过程就不同,存储过程的所有sql逻辑到存放在数据库服务器本地且执行效率非常高。而且由于dao层代码是放到本地,存储过程代码是在远程服务器中,故安全性上也比不上存储过程。至于稳定性就更不用谈了。

    幸运的是mybatics是完美支持存储过程调用的,这一点让人感到十分欣慰,也无疑更是增加了我对它的喜爱。

     对于mysql而言,mysql 5.0以后的版本是支持存储过程的 。

    下面我介绍下mybatics中如何调用mysql 存储过程,至于调用oracle 的存储过程也是大同小异的,值得注意的是当程序需要返回List集合数据出来时,Oracle中需要返回游标,而mysql中直接select出去即可 。


  1、 mybatics中调用mysql 存储过程返回LIST 列表数据。

         根据name (模糊)查询用户信息列表,返回用户列表

         UserMapper.xml 中 配置  存储过程调用, 注意  statementType="CALLABLE"  ,select元素配置的ressultType 直接就是User类型。

	<select id="queryUserListByLikeName_SP" parametertype="map" resulttype="User" statementtype="CALLABLE">
	     {call queryUserList_nameSP(
            #{name,jdbcType=VARCHAR,mode=IN}
          )
         }
	</select>
Copy after login
      service 层java代码,调用mapper接口 入参传一个map,返回值是List 类型

    

	public Map<string object> getUserListNameLike(String name) {
       try {
    	     Map<string>  params=AjaxUtil.getMap();
    	     params.put("name", name);
    	     List<user> userList =  userMapper.queryUserListByLikeName_SP(params);
    	     if(userList!=null){
    	    	 Map<string> map= AjaxUtil.messageMap(1, "查询成功");
    	    	 map.put("userList", userList);
    	    	return map;
    	     }
		} catch (Exception e) {
			logger.error(e);
			throw new RuntimeException(e);
		}
	    return AjaxUtil.messageMap(-1, "查询失败");
	}</string></user></string></string>
Copy after login
          mapper 接口 代码,就一个接口声明(通过mybatics动态代理方式产生其实现类)

	public List<user> queryUserListByLikeName_SP( Map<string object> params);</string></user>
Copy after login
     最后看下,存储过程的代码。(也很简单就一个select 模糊查询)

     

DELIMITER $$

USE `easyuidemo`$$

DROP PROCEDURE IF EXISTS `queryUserList_nameSP`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `queryUserList_nameSP`(IN in_name VARCHAR(50))
BEGIN
    SELECT  * FROM t_user t WHERE t.name  LIKE   CONCAT('%',in_name,'%') ;
    END$$

DELIMITER ;
Copy after login

      2、   mybatics中调用mysql 存储过程添加用户。

页面表单ajax上传的用户信息,通过存储过程完成用户添加。要求添加成功时,存储过程中要返回rc(reponseCode结果码)、msg(结果消息)、userId(新添加的用户id)

        UserMapper.xml 中的配置。

       值得注意的是,这里的存储过程配置既可以配置为select节点元素,也可以配置为其它insert、update、delete元素,且无须配置resultType 或resultMap,如果是select元素,请一定要设置userCache=“false”  。入参我这里设置为了map。(这里的map其实就是java.util.Map, mybatics中内置了许多java中类型到jdbc类型的别名映射,比如java中int对应为jdbc中integer,而map就是java.util.Map的在mybatics中的别名 ),大家可能会注意我这入参并没有用User  这个bean对象,用bean来传字段属性岂不是更合乎情理吗? 这个稍候再跟大家解释下。。。

<select id="addUser_SP" parametertype="map" statementtype="CALLABLE" usecache="false">
	 {call addUser_SP(
            #{name,jdbcType=VARCHAR,mode=IN},
            #{age,jdbcType=INTEGER,mode=IN},
            #{email,jdbcType=VARCHAR,mode=IN},
            #{address,jdbcType=VARCHAR,mode=IN},
            #{phone,jdbcType=VARCHAR,mode=IN},
            #{rc,jdbcType=VARCHAR,mode=OUT},
            #{msg,jdbcType=VARCHAR,mode=OUT},
            #{userId,jdbcType=VARCHAR,mode=OUT}
          )
         }
	</select>
Copy after login

    service 层java代码。

    大家一定在奇怪这句代码  userMapper.addUser_SP(params); 这前面并没有用变量接收方法的返回值,其实这个方法是没有返回值的,即使你定义了要返回某个值(如Map),你会发现无论你得到的永远是null。所以这里根本就不需要接收返回值。那么调用存储过程返回的out参数到要如何接收呢?细心的你可能已经发现了,没错,就是在入参param中!!调用存储过程成功后,你会发现,存储返回的rc、 msg和userId 三个out参数都被放到了你传入的参数params中————也就是说params会在调用存储成功后多出三个字段值rc、msg、userId。

	public Map<string object> addUser_SP(User user) {
		try {
			Map<string>  params=AjaxUtil.getMap();
			params.put("name", user.getName());
			params.put("address", user.getAddress());
			params.put("age", user.getAge());
			params.put("email", user.getEmail());
			params.put("phone", user.getPhone());
		   userMapper.addUser_SP(params);
		   Map<string object> map=new HashMap<string>();
		   map.put("rc", params.get("rc"));
		   map.put("msg", params.get("msg"));
		   map.put("userId", params.get("userId"));
		   return map;
		} catch (Exception e) {
			logger.error(e);
			throw new RuntimeException(e);
	    }
	}</string></string></string></string>
Copy after login
   

再看下mapper接口方法的定义(没什么好说的就一个接口方法定义)

public void addUser_SP(Map<string object> params);</string>
Copy after login

最后再看下存储过程代码:

DELIMITER $$

USE `easyuidemo`$$

DROP PROCEDURE IF EXISTS `addUser_SP`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `addUser_SP`(
  IN in_name VARCHAR (50),
  IN in_age INTEGER,
  IN in_email VARCHAR (50),
  IN in_address VARCHAR (200),
  IN in_phone VARCHAR (20),
  OUT rc INTEGER,
  OUT msg VARCHAR (50),
  OUT userId VARCHAR (50)
)
BEGIN
  DECLARE v_userId VARCHAR (50) DEFAULT ROUND(RAND() * 9000000+10000000) ;
  DECLARE v_ucount INTEGER DEFAULT 0 ;
  SELECT 
    COUNT(*) INTO v_ucount 
  FROM
    t_user 
  WHERE t_user.`id` = v_userId ;
  IF v_ucount > 0 
  THEN SET rc = - 1 ;
  SET msg = '生成userId重复,插入失败' ;
  SET userId='-00000000';
  ELSE 
  INSERT INTO t_user (id, `name`, age, email, address, phone) 
  VALUES
    (
      v_userId,
      in_name,
      in_age,
      in_email,
      in_address,
      in_phone
    ) ;
  SET userId = v_userId ;
  SET rc=1;
  SET msg='添加成功';
 #commit ;
  END IF ;
END$$

DELIMITER ;
Copy after login


存储过程本身也没什么好说的,唯一值得大家关注的是:mysql存储过程中最后有commit和没有commit 是有所不同的。

如果存储过程中没有执行commit,那么spring容器一旦发生了事务回滚,存储过程执行的操作也会回滚。如果存储过程执行了commit,那么数据库自身的事务此时已提交,这时即使在spring容器中托管了事务,并且由于其他原因导致service代码中产生异常而自动回滚,但此存储过程是不会回滚,因为数据自身的事务已在存储过程执行完毕前提交了,  也就是说此时spring回滚对存储过程的操作是无效的了。




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to view database password in Navicat for MariaDB? How to view database password in Navicat for MariaDB? Apr 08, 2025 pm 09:18 PM

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

See all articles