You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>Este statement proporciona una funcionalidad de búsqueda de texto. Si no se pasa ningún título, entonces se retornan todos los Blogs activos. Pero si se pasa un título se buscará un título como el pasado (para los perspicaces, sí, en este caso tu parámetro debe incluir el carácter de comodín).</p>
51
51
<p>¿Y cómo hacemos si debemos buscar opcionalmente por título o autor? Primeramente, yo cambiaría el nombre del statement para que tenga algo más de sentido. Y luego añadir otra condición.</p>
52
52
<source><![CDATA[<select id="findActiveBlogLike"
53
-
parameterType="Blog" resultType="Blog">
53
+
resultType="Blog">
54
54
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
55
55
<if test="title != null">
56
56
AND title like #{title}
@@ -64,7 +64,7 @@
64
64
<p>En ocasiones no queremos usar una condición sino elegir una de entre varias opciones. De forma similar al switch de Java, MyBatis ofrece el elemento choose.</p>
65
65
<p>Usemos el ejemplo anterior, pero ahora vamos a buscar solamente por título si se ha proporcionado un título y por autor si se ha proporcionado un autor. Si no se proporciona ninguno devolvemos una lista de Blogs destacados (quizá una lista seleccionada por los administradores en lugar de una gran lista de blogs sin sentido).</p>
<p>En los ejemplos anteriores se ha sorteado intencionadamente un notorio problema del SQL dinámico. Imagina lo que sucedería si volvemos a nuestro ejemplo del “if”, pero esta vez, hacemos que “ACTIVE = 1” sea también una condición dinámica.</p>
84
84
<source><![CDATA[<select id="findActiveBlogLike"
85
-
parameterType="Blog" resultType="Blog">
85
+
resultType="Blog">
86
86
SELECT * FROM BLOG
87
87
WHERE
88
88
<if test="state != null">
@@ -105,7 +105,7 @@ AND title like ‘someTitle’]]></source>
105
105
<p>Y eso también fallará. Este problema no se resuelve fácil con condicionales, y si alguna vez tienes que hacerlo, posiblemente no quieras repetirlo nunca más.</p>
106
106
<p>MyBatis tiene una respuesta sencilla que funcionará en el 90% de los casos. Y en los casos en los que no funciona puedes personalizarlo para hacerlo funcionar. Con un cambio simple, todo funciona correctamente:</p>
107
107
<source><![CDATA[<select id="findActiveBlogLike"
108
-
parameterType="Blog" resultType="Blog">
108
+
resultType="Blog">
109
109
SELECT * FROM BLOG
110
110
<where>
111
111
<if test="state != null">
@@ -126,8 +126,7 @@ AND title like ‘someTitle’]]></source>
126
126
</trim>]]></source>
127
127
<p>El atributo prefixOverrides acepta una lista de textos delimitados pro el carácter “| “ donde el espacio en blanco es relevante. El resultado es que se elimina cualquier cosa que se haya especificado en el atributo prefixOverrides, y que se inserta todo lo incluido en el atributo with.</p>
128
128
<p>Hay una solución similar para updates dinámicos llamada set. El elemento set se pude usar para incluir dinámicamente columnas para modificar y dejar fuera las demás. Por ejemplo:</p>
<subsectionname="Soporte de multiples vendedores de base de datos">
172
171
<p>Si se ha configurado un databaseIdProvider la variable "_databaseId" estará disponible en el código dinámico, de esta forma puedes constrir distintas sntencias dependiendo del fabricante de la base de datos. Mira el siguiente ejemplo:</p>
<p>This statement would provide an optional text search type of functionality. If you passed in no title, then all active Blogs would be returned. But if you do pass in a title, it will look for a title like that (for the keen eyed, yes in this case your parameter value would need to include any masking or wildcard characters).</p>
50
50
<p>What if we wanted to optionally search by title and author? First, I’d change the name of the statement to make more sense. Then simply add another condition.</p>
51
51
<source><![CDATA[<select id="findActiveBlogLike"
52
-
parameterType="Blog" resultType="Blog">
52
+
resultType="Blog">
53
53
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
54
54
<if test="title != null">
55
55
AND title like #{title}
@@ -63,7 +63,7 @@
63
63
<p>Sometimes we don’t want all of the conditionals to apply, instead we want to choose only one case among many options. Similar to a switch statement in Java, MyBatis offers a choose element.</p>
64
64
<p>Let’s use the example above, but now let’s search only on title if one is provided, then only by author if one is provided. If neither is provided, let’s only return featured blogs (perhaps a strategically list selected by administrators, instead of returning a huge meaningless list of random blogs).</p>
<p>The previous examples have been conveniently dancing around a notorious dynamic SQL challenge. Consider what would happen if we return to our "if" example, but this time we make "ACTIVE = 1" a dynamic condition as well.</p>
83
83
<source><![CDATA[<select id="findActiveBlogLike"
84
-
parameterType="Blog" resultType="Blog">
84
+
resultType="Blog">
85
85
SELECT * FROM BLOG
86
86
WHERE
87
87
<if test="state != null">
@@ -104,7 +104,7 @@ AND title like ‘someTitle’]]></source>
104
104
<p>This would also fail. This problem is not easily solved with conditionals, and if you’ve ever had to write it, then you likely never want to do so again.</p>
105
105
<p>MyBatis has a simple answer that will likely work in 90% of the cases. And in cases where it doesn’t, you can customize it so that it does. With one simple change, everything works fine:</p>
106
106
<source><![CDATA[<select id="findActiveBlogLike"
107
-
parameterType="Blog" resultType="Blog">
107
+
resultType="Blog">
108
108
SELECT * FROM BLOG
109
109
<where>
110
110
<if test="state != null">
@@ -125,8 +125,7 @@ AND title like ‘someTitle’]]></source>
125
125
</trim>]]></source>
126
126
<p>The <em>prefixOverrides</em> attribute takes a pipe delimited list of text to override, where whitespace <u>is</u> relevant. The result is the removal of anything specified in the <em>prefixOverrides</em> attribute, and the insertion of anything in the <em>prefix</em> attribute.</p>
127
127
<p>There is a similar solution for dynamic update statements called <em>set</em>. The <em>set</em> element can be used to dynamically include columns to update, and leave out others. For example:</p>
<p>If a databaseIdProvider was configured a "_databaseId" variable is available for dynamic code, so you can build different statements depending on database vendor. Have a look at the following example:</p>
0 commit comments