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

1.parameterType 配置參數html

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

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

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

基 本 類 型 和 String 我 們 可 以 直 接 寫 類 型 名 稱 , 也 可 以 使 用 包 名 . 類 名 的 方 式 , 例 如 :
java.lang.String。
究其緣由,是 mybaits 在加載時已經把經常使用的數據類型註冊了別名,從而咱們在使用時能夠不寫包名
若是咱們寫的類也註冊別名的話,也能夠直接寫別名(經過typeAliases標籤)數據庫

起了別名以後不區分大小寫,好比整型能夠寫int,INT,Interger等apache

能夠參考 TypeAliasRegistery.class 的源碼。
session

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

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

 

1.1基本類型app

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

1.2引用類型maven

<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(); } }
相關文章
相關標籤/搜索