how2j.cn

下载区
文件名 文件大小
mybatis.rar 2m
步骤 1 : 先运行,看到效果,再学习   
步骤 2 : 模仿和排错   
步骤 3 : 基于前面的教程上进行   
步骤 4 : 执行不同的条件限定,需要准备两条sql语句   
步骤 5 : if标签   
步骤 6 : 可运行项目下载   

步骤 1 :

先运行,看到效果,再学习

edit
老规矩,先下载右上角的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。

推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
步骤 3 :

基于前面的教程上进行

edit
这个知识点要对Product做不少的查询操作,所以基于 多对一 的基础上进行,因为在这个系列教程中,到那一步,才用到了Product这个类。
步骤 4 :

执行不同的条件限定,需要准备两条sql语句

edit
假设需要对Product执行两条sql语句,一个是查询所有,一个是根据名称模糊查询。
那么按照现在的方式,必须提供两条sql语句:listProduct和listProductByName
然后在调用的时候,分别调用它们来执行。
执行不同的条件限定,需要准备两条sql语句
<?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.how2java.pojo"> <select id="listProduct" resultType="Product"> select * from product_ </select> <select id="listProductByName" resultType="Product"> select * from product_ where name like concat('%',#{name},'%') </select> </mapper>
package com.how2java; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; 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.how2java.pojo.Product; public class TestMybatis { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); System.out.println("查询所有的"); List<Product> ps = session.selectList("listProduct"); for (Product p : ps) { System.out.println(p); } System.out.println("模糊查询"); Map<String,Object> params = new HashMap<>(); params.put("name","a"); List<Product> ps2 = session.selectList("listProductByName",params); for (Product p : ps2) { System.out.println(p); } session.commit(); session.close(); } }
如果Product的字段比较多的话,为了应付各个字段的查询,那么就需要写多条sql语句,这样就变得难以维护。
这个时候,就可以使用Mybatis 动态SQL里的if标签

<select id="listProduct" resultType="Product">
select * from product_
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
</select>

如果没有传参数name,那么就查询所有,如果有name参数,那么就进行模糊查询。
这样只需要定义一条sql语句即可应付多种情况了,在测试的时候,也只需要调用这么一条sql语句listProduct 即可。
if标签
<?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.how2java.pojo"> <select id="listProduct" resultType="Product"> select * from product_ <if test="name!=null"> where name like concat('%',#{name},'%') </if> </select> </mapper>
package com.how2java; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; 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.how2java.pojo.Product; public class TestMybatis { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); System.out.println("查询所有的"); List<Product> ps = session.selectList("listProduct"); for (Product p : ps) { System.out.println(p); } System.out.println("模糊查询"); Map<String,Object> params = new HashMap<>(); params.put("name","a"); List<Product> ps2 = session.selectList("listProduct",params); for (Product p : ps2) { System.out.println(p); } session.commit(); session.close(); } }
步骤 6 :

可运行项目下载

edit
在右上角有本知识点对应的可运行项目下载


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2020-10-30 if标签中name!=' '导致的异常
iurac

关于 JAVA 框架-Mybatis-if 的提问



在写if标签中语句时,无意间将<if test="username != '' and username != null">中的name!=''里打多了个空格变成‘ ’,程序运行就会报NumberFormatException异常,想知道下为什么?
加载中
<select id="selectByInfo" resultType="com.iurac.domain.User">
        select * from user
        where id > 0
        <if test="username != ' ' and username != null">
            and username = #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </select>

-------------------------------------------------------------------------------

@Test
    public void testSelectByInfo(){
        SqlSession session = MyBatisUtil.getSqlSession();
        UserDao userDao = session.getMapper(UserDao.class);

        User user = new User();

        user.setUsername("王1");
        user.setSex("男");

        List<User> users = userDao.selectByInfo(user);

        users.forEach( u -> System.out.println(u.toString()));
    }
### Error querying database.  Cause: java.lang.NumberFormatException: For input string: "王1"
### Cause: java.lang.NumberFormatException: For input string: "王1"

	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
	at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
	at com.sun.proxy.$Proxy3.selectByInfo(Unknown Source)
	at com.iurac.test.MybatisTest.testSelectByInfo(MybatisTest.java:50)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: java.lang.NumberFormatException: For input string: "王1"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.lang.Double.parseDouble(Double.java:538)
	at org.apache.ibatis.ognl.OgnlOps.doubleValue(OgnlOps.java:243)
	at org.apache.ibatis.ognl.OgnlOps.compareWithConversion(OgnlOps.java:100)
	at org.apache.ibatis.ognl.OgnlOps.isEqual(OgnlOps.java:143)
	at org.apache.ibatis.ognl.OgnlOps.equal(OgnlOps.java:802)
	at org.apache.ibatis.ognl.ASTNotEq.getValueBody(ASTNotEq.java:53)
	at org.apache.ibatis.ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
	at org.apache.ibatis.ognl.SimpleNode.getValue(SimpleNode.java:258)
	at org.apache.ibatis.ognl.ASTAnd.getValueBody(ASTAnd.java:61)
	at org.apache.ibatis.ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
	at org.apache.ibatis.ognl.SimpleNode.getValue(SimpleNode.java:258)
	at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:470)
	at org.apache.ibatis.ognl.Ognl.getValue(Ognl.java:434)
	at org.apache.ibatis.scripting.xmltags.OgnlCache.getValue(OgnlCache.java:44)
	at org.apache.ibatis.scripting.xmltags.ExpressionEvaluator.evaluateBoolean(ExpressionEvaluator.java:32)
	at org.apache.ibatis.scripting.xmltags.IfSqlNode.apply(IfSqlNode.java:34)
	at org.apache.ibatis.scripting.xmltags.MixedSqlNode.apply(MixedSqlNode.java:33)
	at org.apache.ibatis.scripting.xmltags.DynamicSqlSource.getBoundSql(DynamicSqlSource.java:41)
	at org.apache.ibatis.mapping.MappedStatement.getBoundSql(MappedStatement.java:292)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
	... 28 more


3 个答案

四方1
答案时间:2023-08-10
太男言之有理也。

齐名太男
答案时间:2020-12-30
mybatis是用OGNL表达式来解析的,在OGNL的表达式中,' '会被解析成字符,java是强类型的,char 和 一个string 会导致不等,所以if标签中的sql不会被解析。 改成<if test="username != ‘ ’.toString() and username != null"> 或者<if test=’username != “ ” and username != null‘> 或者传参的时候,传char类型

齐名太男
答案时间:2020-12-30
mybatis是用OGNL表达式来解析的,在OGNL的表达式中,' '会被解析成字符,java是强类型的,char 和 一个string 会导致不等,所以if标签中的sql不会被解析。 改成<if test="username != ‘ ’.toString() and username != null"> 或者<if test=’username != “ ” and username != null‘>



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2020-05-06 where name like concat('%',#{name},'%')这个模糊查询是啥意思
温一壶月光下酒

关于 JAVA 框架-Mybatis-if 的提问



不懂这个语句,能不能解释一下
 where name like concat('%',#{name},'%')

							


3 个答案

lioubiao123
答案时间:2020-05-14
因为<if test="name!=null">这里用到了name这个参数,所以通过params把name这个参数传进去,至于怎么跟sql匹配:1.session.selectList("DTlistProduct",params);这里其实就表示将这个参数传进去了,底层工作原理别管它,这是mybatis作者考虑的问题,2.其实<select id="listProduct" resultType="Product">里面写了resultType表示查询到的数据需要用Product封装,前面还学过一个paramType的标签,这个标签的作用是表明传进来的参数类型,不过我试了,写不写都可以,<select id="DTlistProduct" parameterType="string" resultType="Product">你写成这样,同样可以成功运行。

DarkADays
答案时间:2020-05-08
整个sql语句相当于如果name不为空:select * from product_ where name like ‘%#{name}%’ 代码中传递的name值为a,即sql语句为 select * from product_ where name like %a%

温一壶月光下酒
答案时间:2020-05-06
params.put("name","a");把这个参数传过来是啥意思?传过来怎么跟sql语句匹配?



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2019-08-01 代码是一样的,结果出来的不对
2018-12-29 关于这个selectList()方法
2018-12-03 parameterType不是必须写的,后面的同学们注意了


提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 6 条以前的提问,请 点击查看

提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 JAVA 框架-Mybatis-if 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图