MyBatis参数详解与SqlMapConfig.xml核心配置
一、parameterType参数类型1.1 简单数据类型int、double、String、long等。框架提供了简写方式例如 java.lang.Integer 可以简写为 int、integer、Int、Integer 等。select idfindById parameterTypeint resultTypeUser select * from user where id #{id} /select1.2 POJO对象类型直接使用实体类的全路径或别名insert idinsert parameterTypecom.qcbyjy.domain.User insert into user (username) values (#{username}) /insert1.3 POJO包装对象类型当需要传递多个实体类参数时可以创建包装类public class QueryVo implements Serializable { private String name; private User user; private Role role; // getter/setter省略 } select idfindByVo parameterTypecom.qcbyjy.domain.QueryVo resultTypeUser select * from user where username #{user.username} /select二、resultType结果类型2.1 返回简单数据类型int、double、long、String等select idfindByCount resultTypeint select count(*) from user /select2.2 返回POJO数据类型直接返回实体类对象select idfindById resultTypeUser select * from user where id #{id} /select三、resultMap结果映射当SQL查询字段名和POJO的属性名不一致时可以通过 resultMap 建立映射关系!-- 使用resultMap -- select idfindUsers resultMapuserMap select id _id, username _username, birthday _birthday, sex _sex, address _address from user /select !-- 配置resultMap -- resultMap iduserMap typecom.qcbyjy.domain.User result propertyid column_id/ result propertyusername column_username/ result propertybirthday column_birthday/ result propertysex column_sex/ result propertyaddress column_address/ /resultMapresultMap配置说明propertyJavaBean中的属性名column数据库表中的字段名四、SqlMapConfig.xml核心配置4.1 properties标签管理数据库信息方式一直接在配置文件中定义property标签properties property namejdbc.driver valuecom.mysql.jdbc.Driver/ property namejdbc.url valuejdbc:mysql:///mybatis_db/ property namejdbc.username valueroot/ property namejdbc.password valueroot/ /properties方式二推荐读取外部jdbc.properties文件创建 jdbc.properties 文件jdbc.drivercom.mysql.jdbc.Driver jdbc.urljdbc:mysql:///mybatis_db jdbc.usernameroot jdbc.passwordroot在 SqlMapConfig.xml 中引入properties resourcejdbc.properties/然后使用 ${} 引用dataSource typePOOLED property namedriver value${jdbc.driver}/ property nameurl value${jdbc.url}/ property nameusername value${jdbc.username}/ property namepassword value${jdbc.password}/ /dataSource4.2 typeAliases类型别名MyBatis内置了类型别名注册我们自己也可以注册别名typeAliases !-- 针对com.qcbyjy.domain包下的所有类使用类名做为别名 -- package namecom.qcbyjy.domain/ /typeAliases配置后在Mapper.xml中可以直接使用类名不区分大小写select idfindAll resultTypeuser select * from user /select