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(); } }
爱生活,爱码字
我是匆匆、我曾喂自己半年酒。
好好生活吧,有缘或许相见。