说起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>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>mapper 接口 代码,就一个接口声明(通过mybatics动态代理方式产生其实现类)
public List<user> queryUserListByLikeName_SP( Map<string object> params);</string></user>最后看下,存储过程的代码。(也很简单就一个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 ;
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>
service 层java代码。
大家一定在奇怪这句代码 userMapper.addUser_SP(params); 这前面并没有用变量接收方法的返回值,其实这个方法是没有返回值的,即使你定义了要返回某个值(如Map
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>
再看下mapper接口方法的定义(没什么好说的就一个接口方法定义)
public void addUser_SP(Map<string object> params);</string>
最后再看下存储过程代码:
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 ;
存储过程本身也没什么好说的,唯一值得大家关注的是:mysql存储过程中最后有commit和没有commit 是有所不同的。
如果存储过程中没有执行commit,那么spring容器一旦发生了事务回滚,存储过程执行的操作也会回滚。如果存储过程执行了commit,那么数据库自身的事务此时已提交,这时即使在spring容器中托管了事务,并且由于其他原因导致service代码中产生异常而自动回滚,但此存储过程是不会回滚,因为数据自身的事务已在存储过程执行完毕前提交了, 也就是说此时spring回滚对存储过程的操作是无效的了。

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool