mybatis學習5-參數類型,返回值類型


1.parameterType 配置參數

SQL 語句傳參,使用標簽的 parameterType 屬性來設定。

該屬性的取值可以是基本類型,引用類型(例如:String 類型),

還可以是實體類類型(POJO 類)。同時也可以使用實體類的包裝類 

基 本 類 型 和 String 我 們 可 以 直 接 寫 類 型 名 稱 , 也 可 以 使 用 包 名 . 類 名 的 方 式 , 例 如 :
java.lang.String。
究其原因,是 mybaits 在加載時已經把常用的數據類型注冊了別名,從而我們在使用時可以不寫包名
如果我們寫的類也注冊別名的話,也可以直接寫別名(通過typeAliases標簽)

起了別名之后不區分大小寫,比如整型可以寫int,INT,Interger等

可以參考 TypeAliasRegistery.class 的源碼。

mybatis使用ognl表達式來解析對象字段的值#{}或者${}中的值就是pojo對象屬性名稱

OGNL表達式:
    Object Graphic Navigation Language
     對象    圖         導航     語言
 
    它是通過對象的取值方法來獲取數據。在寫法上把get給省略了。
    比如:我們獲取用戶的名稱
        類中的寫法:user.getUsername();
        OGNL表達式寫法:user.username
    mybatis中為什么能直接寫username,而不用user.呢:
        因為在parameterType中已經提供了屬性所屬的類,所以此時不需要寫對象名

 

1.1基本類型

    <select id="findById" resultType="account">
        select * from account where id = #{id}
    </select>

1.2引用類型

    <select id="findByName" parameterType="string" resultType="account">
        select * from account where name like #{name}
    </select>

1.3實體類型

    <insert id="saveAccount" parameterType="account">
        insert into account(name,money) VALUES (#{name},#{money});
    </insert>

1.4實體類包裝類

開發中通過 pojo 傳遞查詢條件 ,查詢條件是綜合的查詢條件,不僅包括用戶查詢條件還包括其它的查
詢條件,這些條件可以組成一個對象,稱之為查詢對象,這時可以使用包裝對象傳遞輸入參數。

AccountVo類
public class AccountVo {
    private Account account;

    public Account getAccount() {
        return account;
    }
    public void setAccount(Account account) {
        this.account = account;
    }
}


AccountMapper接口中的方法
List<Account> findByVo(AccountVo accountVo);

mapper.xml中的sql語句
    <select id="findByVo" parameterType="accountVo" resultType="account">
        select * from account where name like #{account.name}
    </select>

測試方法
    @Test
    public void findByVo(){
        Account cong= new Account();
        cong.setName("%on%");
        AccountVo accountVo = new AccountVo();
        accountVo.setAccount(cong);
        List<Account> accounts = mapper.findByVo(accountVo);
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }

 2.resultType 結果類型

可以是簡單的數據類型,可以是pojo對象,還可以是pojo集合

返回結果經常遇到的一個問題就是實體類的屬性與數據庫表的屬性名稱不一致

這時候可以用resultMap標簽將它們統一起來,或者通過mysql中as關鍵字起別名

2.1  resultMap

    <resultMap id="accountDiy" type="account">
        <id column="id" property="aid"></id>
        <result column="name" property="aname"></result>
        <result column="money" property="amoney"></result>
    </resultMap>
    <select id="findAll" resultMap="accountDiy">
        select * from account;
    </select>

2.2起別名

    <select id="findById" parameterType="int"  resultType="account">
        select id as aid,name as aname,money as amoney from account where id = #{id}
    </select>

完整項目

1.創建maven項目,導入相關依賴

<?xml version="1.0" encoding="UTF-8"?>
<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.cong</groupId>
    <artifactId>mybatis_para_res_config</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

2.創建com.cong.pojo包,以及兩個類

package com.cong.pojo;

public class Account {
    private int aid;
    private String aname;
    private float amoney;

    @Override
    public String toString() {
        return "Account{" +
                "aid=" + aid +
                ", aname='" + aname + '\'' +
                ", amoney=" + amoney +
                '}';
    }

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public String getAname() {
        return aname;
    }

    public void setAname(String aname) {
        this.aname = aname;
    }

    public float getAmoney() {
        return amoney;
    }

    public void setAmoney(float amoney) {
        this.amoney = amoney;
    }
}




package com.cong.pojo;

public class AccountVo {
    private Account account;

    public Account getAccount() {
        return account;
    }
    public void setAccount(Account account) {
        this.account = account;
    }
}

3.創建com.cong.mapper.AccountMapper接口

package com.cong.mapper;

import com.cong.pojo.Account;
import com.cong.pojo.AccountVo;

import java.util.List;

public interface AccountMapper {
    List<Account> findAll();
    Account findById(int id);
    List<Account> findByVo(AccountVo accountVo);
    List<Account> findByName(String name);
    void saveAccount(Account account);
}

4.在resources下創建log4j.properties和SqlMapConfig.xml文件

下面是配置文件
<?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>
    <typeAliases>
        <!-- 該包下的類全部注冊別名 -->
        <package name="com.cong.pojo"></package>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/cong"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123456"></property>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/cong/mapper/AccountMapper.xml"></mapper>
    </mappers>
</configuration>



下面是log4j

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

5.創建AccountMapper.xml文件

<?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">
    <!--
    namespace用於綁定mapper接口,mapper接口的方法對應此mapper中的sql語名
    引用自:http://www.mybatis.org/mybatis-3/zh/getting-started.html
    -->
<mapper namespace="com.cong.mapper.AccountMapper">
    <resultMap id="accountDiy" type="account">
        <id column="id" property="aid"></id>
        <result column="name" property="aname"></result>
        <result column="money" property="amoney"></result>
    </resultMap>
    <select id="findAll" resultMap="accountDiy">
        select * from account;
    </select>
    <select id="findById" parameterType="int"  resultType="account">
        select id as aid,name as aname,money as amoney from account where id = #{id}
    </select>
    <select id="findByName" parameterType="string"  resultMap="accountDiy">
        select * from account where name like #{name}
    </select>
    <select id="findByVo" parameterType="accountVo"  resultMap="accountDiy">
        select * from account where name like #{account.aname}
    </select>
    <insert id="saveAccount" parameterType="account">
        insert into account(name,money) VALUES (#{aname},#{amoney});
    </insert>
</mapper>

6.測試類

import com.cong.mapper.AccountMapper;
import com.cong.pojo.Account;
import com.cong.pojo.AccountVo;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class TestAccount {
    private InputStream inputStream;
    private SqlSession sqlSession;
    private AccountMapper mapper;
    @Test
    public void findAll(){
        List<Account> accounts = mapper.findAll();
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }
    @Test
    public void findByName(){
        List<Account> accounts = mapper.findByName("%ong%");
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }
    @Test
    public void findById(){
        Account account = mapper.findById(1);
        System.out.println(account.toString());
    }
    @Test
    public void findByVo(){
        Account cong = new Account();
        cong.setAname("%on%");
        AccountVo accountVo = new AccountVo();
        accountVo.setAccount(cong);
        List<Account> accounts = mapper.findByVo(accountVo);
        for (Account account : accounts) {
            System.out.println(account.toString());
        }
    }
    @Test
    public void save(){
        Account account = new Account();
        account.setAname("rainbow");
        account.setAmoney(111111);
        mapper.saveAccount(account);
    }
    @Before
    public void init() throws Exception{
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = factory.openSession();
        mapper = sqlSession.getMapper(AccountMapper.class);
    }
    @After
    public void destroy() throws Exception{
        sqlSession.commit();
        sqlSession.close();
        inputStream.close();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM