1. 程式人生 > >使用<bind>元素創建變量

使用<bind>元素創建變量

efault pid ron 防止 packaging oid r文件 env 屬性

在使用模糊查詢sql時,如果使用${}進行字符拼接,無法防止sql諸如問題,如果使用concat函數則只對mysql有效果,用Oracle則需要用連接符||,這樣在數據庫變的時候需要修改,不利於移植。mybatis提供元素<bind>很好能解決這個問題。

項目結構:

技術分享圖片

廢話不說,使用maven管理jar,如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>maven</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>maven</name> <url>http://maven.apache.org</url>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</
version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> </dependencies> </project>

mybatis配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="resoures/db.properties" />
    <!--1.配置環境 ,默認的環境id為mysql -->
    <environments default="mysql">
        <!--1.2.配置id為mysql的數據庫環境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事務管理 -->
            <transactionManager type="JDBC" />
            <!--數據庫連接池 -->
            <dataSource type="POOLED">
                <!-- 數據庫驅動 -->
                <property name="driver" value="${jdbc.driver}" />
                <!-- 連接數據庫的url -->
                <property name="url" value="${jdbc.url}" />
                <!-- 連接數據庫的用戶名 -->
                <property name="username" value="${jdbc.username}" />
                <!-- 連接數據庫的密碼 -->
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!--2.配置Mapper的位置 -->
    <mappers>
        <mapper resource="com/example/test/mybatis/mapper/UserMapper.xml" />
    </mappers>
</configuration>

數據庫配置:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

PS:註意配置文件的位置!

三種方法實現:

數據庫表格結構

技術分享圖片

javabean

package com.example.test.mybatis;

public class User {
    
    private String name;
    private String sex;
    private int age;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", sex=" + sex + ", age=" + age + "]";
    }
    
}

session工具類:

package com.example.test.mybatis;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
    
    private static SqlSessionFactory sqlSessionFactory = null;
    // 初始化SqlSessionFactory對象
    static {
        try {
            // 使用MyBatis提供的Resources類加載mybatis的配置文件
            Reader reader = 
                    Resources.getResourceAsReader("resoures/mybatis-config.xml");
            // 構建sqlSession的工廠
            sqlSessionFactory = 
                    new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 獲取SqlSession對象的靜態方法
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }

}

mapper文件

方法一:_parameter.getName()傳參,註意參數類型為javabean User

<?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.example.test.mybatis.mapper.UserMapper">

   <select id="findUserByName" parameterType="com.example.test.mybatis.User"
        resultType="com.example.test.mybatis.User">
        <!--_parameter.getUsername()也可直接寫成傳入的字段屬性名,即username -->
        <bind name="pattern" value="‘%‘+_parameter.getName()+‘%‘" />
        select * from user
        where
        name like #{pattern}
    </select>

</mapper>

測試方式:

package com.example.test.mybatis;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

public class MybatisTest {
    public static void main(String[] args) {
        SqlSession session = MybatisUtils.getSession();
        User user = new User();
        user.setName("s");
        
        List<User> list = session.selectList("com.example.test.mybatis.mapper.UserMapper.findUserByName",user);
        for (User u : list) {
            System.out.println(u);
        }
        session.close();
    }

}

測試結果:User [name=as, sex=男, age=1]

方法二:直接使用_parameter傳參,註意傳入的參數類型是String name

<?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.example.test.mybatis.mapper.UserMapper">

    <select id="findUserByStrName" parameterType="String"
        resultType="com.example.test.mybatis.User">
        <!--_parameter.getUsername()也可直接寫成傳入的字段屬性名,即username -->
        <bind name="username" value="‘%‘+_parameter+‘%‘" />
        select * from user
        where
        name like #{username}
    </select>
   
</mapper>

對應測試方法:

package com.example.test.mybatis;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

public class MybatisTest {
    public static void main(String[] args) {
        SqlSession session = MybatisUtils.getSession();  
        String name = "aa";  
        
        List<User> list = session.selectList("com.example.test.mybatis.mapper.UserMapper.findUserByStrName",name);
        for (User u : list) {
            System.out.println(u);
        }
        session.close();
    }

}
測試結果:

User [name=aa, sex=男, age=10]
User [name=aaad, sex=男, age=11]



方法三:直接用javabean的屬性傳參,註意參數類型是javabean User

<?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.example.test.mybatis.mapper.UserMapper">

   <select id="findUserByParameterName" parameterType="com.example.test.mybatis.User"
        resultType="com.example.test.mybatis.User">
        <!--_parameter.getUsername()也可直接寫成傳入的字段屬性名,即name -->
        <bind name="username" value="‘%‘+name+‘%‘" />
        select * from user
        where
        name like #{username}
    </select>
    
</mapper>
package com.example.test.mybatis;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

public class MybatisTest {
    public static void main(String[] args) {
        SqlSession session = MybatisUtils.getSession();
        User user = new User();
        user.setName("aa");
        List<User> list = session.selectList("com.example.test.mybatis.mapper.UserMapper.findUserByParameterName",user);
        for (User u : list) {
            System.out.println(u);
        }
        session.close();
    }
    

}

測試結果:

User [name=aa, sex=男, age=10]
User [name=aaad, sex=男, age=11]

 

使用<bind>元素創建變量