Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of judgment problem in mybatis if test conditional judgment sentence

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail the "case analysis of judgment problems in mybatis if test conditional judgment sentences", with detailed contents, clear steps and proper handling of details. I hope that this article "case analysis of judgment problems in mybatis if test conditional judgment sentences" can help you solve your doubts.

Judgment problems in if test conditional judgment sentences

The main purpose of writing this is to describe the problems that should be paid attention to in mybatis. Unfortunately, I didn't notice it and jumped into the pit.

The sql statement I defined in mybatis is as follows: and z.serviceCount = 1 and z.serviceCount = 0

You can see that this is just a simple judgment of the incoming parameters.

The controller layer passes in a facilityOccupied parameter of type Integer.

On the face of it, there is no problem. When facilityOccupied = 1 is passed in, the test result is unexpected. It queries all the results, that is, it does not conform to the judgment facilityOccupied = = 1.

To put it another way, change the incoming parameter facilityOccupied to type String in the controller layer, and the query results show that it meets the judgment condition of facilityOccupied = = 1.

Or use equals () and z.serviceCount = 1 and z.serviceCount = 0

So, to sum up, what is compared in this place is not the numerical size, but the physical address. The 1 in this double quotation mark is not an int type or an integer type, but a String string type. Ah, what a painful insight.

To add, eq has the same effect as = = in test, comparing addresses, so it's best to use equals () for comparison values.

If test judges Tai Keng in mybatis

[] if judgment of mybatis

A single character should be written in double quotation marks, changed or changed to

Part of the code of the .xml file

Insert cx_customer_deliverypreference.... WORKDAY is omitted here,. .... # {workday, jdbcType=VARCHAR},....

An error occurred at takeWay = "1", resulting in not executing the sql in the if judgment, running the program without reporting an error, without any hint. Removing takeWay = "1" and can be performed. I am puzzled by this.

Because I have written the following code, it is right.

.

Put

Change to

Or just change it.

The reason is: mybatis is parsed by OGNL expression, in OGNL expression,'1' will be parsed into characters, java is strongly typed, char and a string will lead to differences, so the sql in the if tag will not be parsed.

To summarize how to use it: write a single character in double quotes or use .toString ()!

When using Mybatis, it is often used to determine whether the property is empty

POJO

Private Integer status;// status, which may be 0, 1, 2, 3.

Mapper XML

/ /... Omit other and status = # {status}

When the value of status is 0, the where SQL and status = 0 is not spliced properly, that is, the expression in test is false, resulting in an error in the query result. However, obviously this value (Integer: 0)! = null too! ='', it should be true.

When status is of type Integer and the status value is 0, the if judgment is false.

When status is 0, Mybatis parses to an empty string.

In order to avoid this problem, the problem is solved by writing it as follows and removing the judgment of null characters.

Cause Analysis of and status = # {status}

Through the Debug MyBatis source code to find the IfSqlNode class, this class is used to deal with dynamic SQL nodes, the method public boolean apply (DynamicContext context) is used to construct the SQL statement within the node. If (evaluator.evaluateBoolean (test, context.getBindings ()) this code is the key to parsing expressions within test. Concatenate SQL if the expression is true, otherwise ignore it.

Public class IfSqlNode implements SqlNode {private ExpressionEvaluator evaluator; private String test; private SqlNode contents; public IfSqlNode (SqlNode contents, String test) {this.test = test; this.contents = contents; this.evaluator = new ExpressionEvaluator ();} public boolean apply (DynamicContext context) {if (evaluator.evaluateBoolean (test, context.getBindings () {contents.apply (context); return true;} return false;}}

Open the ExpressionEvaluator class and find that parsing expressions use OGNL, which you should be familiar with if you have used the old Struts framework. Through OgnlCache.getValue (expression, parameterObject); you can see that the value of the expression is obtained from the cache, which shows that MyBatis actually caches the expression to improve performance.

Public class ExpressionEvaluator {public boolean evaluateBoolean (String expression, Object parameterObject) {Object value = OgnlCache.getValue (expression, parameterObject); if (value instanceof Boolean) return (Boolean) value; if (value instanceof Number) return! new BigDecimal (String.valueOf (value)) .equals (BigDecimal.ZERO); return value! = null;}

After going in, I finally found the method private static Object parse_Expression (String expression) that parses the expression, which takes the value from the cache first, parses it and puts it in the cache if it doesn't have it, and then calls Ognl.getValue (parse_Expression (expression), root) to get the value of the expression.

Public class OgnlCache {private static final Map expressionCache = new ConcurrentHashMap (); public static Object getValue (String expression, Object root) throws OgnlException {return Ognl.getValue (parse_Expression (expression), root);} private static Object parse_Expression (String expression) throws OgnlException {try {Node node = expressionCache.get (expression); if (node = = null) {node = new OgnlParser (new StringReader (expression). TopLevel_Expression (); expressionCache.put (expression, node) } return node;} catch (ParseException e) {throw new ExpressionSyntaxException (expression, e);} catch (TokenMgrError e) {throw new ExpressionSyntaxException (expression, e);}}

As for how Ognl.getValue (parse_Expression (expression), root) works, you can follow it yourself if you are interested, so I won't repeat it in this article. At this point, we already know that the expression of MyBatis is processed with OGNL, which is enough. Let's go to the OGNL website to see if there is something wrong with our expression syntax that leads to the problem.

Interpreting Objects as Booleans

Any object can be used where a boolean is required. OGNL interprets objects as booleans like this:

If the object is a Boolean, its value is extracted and returned

If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false

If the object is a Character, its boolean value is true if and only if its char value is non-zero

Otherwise, its boolean value is true if and only if it is non-null.

Sure enough, if the object is of type Number, a value of 0 will be resolved to false, otherwise it will be true, and the same is true for floating-point 0.00. OGNL's definition of boolean is somewhat similar to that of JavaScript, that is,''= 0 = = false. It's not difficult to understand the problem with and status= # {status} when status=0, obviously 0! =''is not valid, causing the expression to have a value of false.

The problem is solved by changing the expression to and status = # {status}. The root of the problem still comes from the non-standard coding, only the String type needs to determine whether or not! Other types are not necessary at all. The problem may be caused by the developer copying the previous line directly to change it, or because the MyBatis generation tool used is not rigorous.

It is necessary to mention another "pit" here, if you have something similar to String str = "A"; you should be careful when writing like this. Because if there is a single character in single quotation marks, OGNL will be recognized as the char type in Java. Obviously, the = = operation between the String type and the char type will return false, resulting in an invalid expression. The solution is simple and can be changed to.

After reading this, the article "case Analysis of judgment problems in mybatis if test conditional judgment sentences" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report