mybatis使用小贴士
分享了以下tips: 一、事务管理 二、xml配置sql代码段 三、#和$的区别 四、注意对、做转义 五、依据字符串是否为空,动态组织sql语句 六、使用自定义的类型转换器 七、resultMap的复用 一、事务管理 用户执行一个动作,后台需依次更新多个表,如果其中有一个
分享了以下tips:
一、事务管理
二、xml配置sql代码段
三、#和$的区别
四、注意对做转义
五、依据字符串是否为空,动态组织sql语句
六、使用自定义的类型转换器
七、resultMap的复用
一、事务管理
用户执行一个动作,后台需依次更新多个表,如果其中有一个更新失败,则要回滚之前的更新。这种情况,就是事务回滚。 要支持事务操作,需要:1、确保数据库表的类型是InnoDB,而不是MyISAM
(MyISAM不支持事务,这是一个坑,之前总结过 http://blog.csdn.net/lizeyang/article/details/9280253)2、所有更新操作完成后,再执行commit
例如:SqlSession session = getSqlSession(); int sqlResult = session.insert("insert a table", po); int sqlResult = session.update("update b table", po); //这时,前面的insert和update还没真正执行 session.commit(); //commit后,db才真正更新 session.close();
二、xml配置sql代码段
mybatis需要通过xml配置每次db操作的sql语句。如果多个sql语句中,包含了相同的sql语段,怎么办呢?复制粘贴?这显然不是一个好习惯。建议配置代码段,然后每个sql直接引用这个代码段。 语法:1、在xml中先用这个标签,包装代码段,配置id
<sql id="getFeedBackList_fragment"> from t_comment where refer_type = #{type} and refer_id = #{referId} </sql>
2、在需要这个代码段的地方,通过 语句,引入这个sql
例如
<select id='getFeedBackList' parameterType='map' resultMap='feeback'> select id <include refid="getFeedBackList_fragment"/> order by create_time desc </select>
三、#和$的区别
当sql中有一些参数,需要调用时动态传入时,就需要在sql中写变量,调用时再传入变量。mybatis中,#和$,都是变量的修饰符。一般推荐用#。 #相当于jdbc中,对prepareStatement做set参数的操作,而$则相当于拼接了sql语句,再执行statament。prepareStatement、statament的区别,具体可以在网上搜下,这里就不赘述了。四、注意对<、>做转义
其实,写xml文件,都得注意这个问题,要将>转义成> 要将<转义成< 。我们在写sql时,经常要用到<、>来筛选sql结果,更要牢记这个注意项。五、依据字符串是否为空,动态组织sql语句
mabatis xml配置sql,对字符串的处理能力不够强大,对于判空这样常见的需求,还是得通过para!= null and para != ''来完成,没有相关的内建函数。六、使用自定义的类型转换器
假设有一个字段,数据库字段类型,是timestamp,当赋值到javabean时,希望变成对应的long值。怎么做呢?最原生态的一种选择,赋值给bean时,就是timestamp类型,之后再重新遍历数据,改成long值。这种做法,显然很搓,增加了业务逻辑的代码量,不利于转化逻辑复用。 其实,mybatis本身就支持自定义类型转换器,可以很好地支持这种需求。这里主要想告诉你,mybatis是有这种能力的,更详细的内容,可以再看官方教程。这里简单贴下我的示例。1、configuration xml文件配置
<configuration> …… <typeHandlers> <typeHandler handler="test.TimeTypeHandler" javaType="Long" jdbcType="TIME" /> </typeHandlers> …… </configuration>
2、自定义类型转换器
上面的handle为test.TimeTypeHandler,因此工程中,要写对应的test.TimeTypeHandler.java。转换逻辑,就在这个java文件中package test; public class TimeTypeHandler implements TypeHandler<Long> { private final String TIME_TYPE = "yyyy-MM-dd HH:mm:ss"; public long strToLongTime(String dateStr) { if (null == dateStr) return 0L; SimpleDateFormat sdf = new SimpleDateFormat(TIME_TYPE); Date date = new Date(); try { date = sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } if (date == null) return 0L; System.out.println(date); return date.getTime(); } public Long getResult(ResultSet arg0, String arg1) throws SQLException { String datestr = arg0.getString(arg1); return strToLongTime(datestr); } public Long getResult(ResultSet arg0, int arg1) throws SQLException { String datestr = arg0.getString(arg1); return strToLongTime(datestr); } public Long getResult(CallableStatement arg0, int arg1) throws SQLException { String datestr = arg0.getString(arg1); return strToLongTime(datestr); } public void setParameter(PreparedStatement arg0, int arg1, Long arg2, JdbcType arg3) throws SQLException { if (arg2 == null) { arg2 = 0L; } Date date = new Date(arg2); SimpleDateFormat sdf = new SimpleDateFormat(TIME_TYPE); String datetime = sdf.format(date); arg0.setString(arg1, datetime); } }
3、mapper xml配置
<mapper namespace="xxxx"> …… //这里定义了ExpDownloadPo这个sql查询结果,要映射到java bean :test.ExpDownloadPo <resultMap id="ExpDownloadPo" type="test.ExpDownloadPo"> <id property="id" column="id" /> //first_download_time这个数据,在赋值到firstDownloadTime时,要转转换,从jdbc的time型,转换成javaType的long型,具体怎么转换,因为前面第一点,定义了<typeHandlers><typeHandler handler="test.TimeTypeHandler" javaType="Long" jdbcType="TIME" /></typeHandlers>,因此会自动使用test.TimeTypeHandler这个转换器 <result property="firstDownloadTime" column="first_download_time" javaType="Long" jdbcType="TIME"/> <result property="lastDownloadTime" column="last_download_time" javaType="Long" jdbcType="TIME"/> </resultMap> …… </mapper >
七、resultMap的复用
我们一般会定义多个mapper.xml文件,将不同的功能,放到不同的xml中。如果mapper文件A需要使用mapper文件B中所定义的resultmap时,是可以直接使用的,请勿在文件B中重复定义resultmap。 具体使用方法是: 例如mapper A的namespace是com.blog.test,其中定义的resultmapid是testbean,那么,在文件B中,如果要用到这个resultmap,则用它的全名即可,也就是com.blog.test.testbean(namespace+resultmapid)mapper文件A
<mapper namespace="com.blog.test"> …… <resultMap id="testbean" ></resultMap> </mapper>
mapper文件B
<mapper namespace="B"> <select id="mysql" parameterType="map" resultMap="com.blog.test.testbean"> </mapper>

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











Quark Netdisk and Baidu Netdisk are very convenient storage tools. Many users are asking whether these two softwares are interoperable? How to share Quark Netdisk to Baidu Netdisk? Let this site introduce to users in detail how to save Quark network disk files to Baidu network disk. How to save files from Quark Network Disk to Baidu Network Disk Method 1. If you want to know how to transfer files from Quark Network Disk to Baidu Network Disk, first download the files that need to be saved on Quark Network Disk, and then open the Baidu Network Disk client. , select the folder where the compressed file is to be saved, and double-click to open the folder. 2. After opening the folder, click "Upload" in the upper left corner of the window. 3. Find the compressed file that needs to be uploaded on your computer and click to select it.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

1. First, we enter NetEase Cloud Music, and then click on the software homepage interface to enter the song playback interface. 2. Then in the song playback interface, find the sharing function button in the upper right corner, as shown in the red box in the figure below, click to select the sharing channel; in the sharing channel, click the "Share to" option at the bottom, and then select the first "WeChat Moments" allows you to share content to WeChat Moments.
