1. 输入映射
1.1 parameterType(输入类型)
1.1.1 传递简单类型
参见Mybatis-1
1.1.2 传递pojo对象
Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称。
开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
Pojo类中包含pojo。
需求:根据用户名查询用户信息,查询条件放到QueryVo的user属性中。
1)创建QueryVo类
public class QueryVo {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
2)在UserMapper.xml中加入代码:
<select id="findUserbyVo" parameterType="cn.itheima.pojo.QueryVo" resultType="cn.itheima.pojo.User">
select *from user where username like '%${user.username}%' and sex=#{user.sex}
</select>
public interface UserMapper {
public List<User> findUserbyVo(QueryVo vo);
}
4)编写测试类UserMapperTest
public class UserMapperTest {
private SqlSessionFactory factory;
//作用:在测试方法前执行这个方法
@Before
public void setUp() throws Exception{
String resource="SqlMapConfig.xml";
//通过流将核心文件读取进来
InputStream inputStream=Resources.getResourceAsStream(resource);
//通过核心配置文件输入流来创建会话工厂
factory=new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserByVo() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
QueryVo vo=new QueryVo();
User user=new User();
user.setUsername("王");
user.setSex("1");
vo.setUser(user);
List<User> list = mapper.findUserbyVo(vo);
System.out.println(list);
}
}
2. 输出映射
2.1 在UserMapper.xml中加入代码:
<!-- 只有返回结果为一行一列的时候,那么返回值类型才可以指定成基本类型 -->
<select id="findUserCount" resultType="java.lang.Integer">
select count(*) from user
</select>
2.2 在UserMapper接口中加入代码:
public Integer findUserCount();
2.3 在测试类UserMapperTest中加入代码测试:
@Test
public void testFindUserCount() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
Integer count = mapper.findUserCount();
System.out.println(count);
}
3.动态sql
3.1 if,where,sql
3.1.1 UserMapper.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">
<mapper namespace="cn.itheima.mapper.UserMapper">
<!-- 封装SQL条件,封装后可以重用
id:是这个SQL条件的唯一标识
-->
<sql id="user_Where">
<!-- where标签作用:
会自动向SQL语句中添加where关键字
会去掉第一个条件的and关键字
-->
<where>
<if test="username != null and username !=''">
and username like '%${username}%'
</if>
<if test="sex != null and sex !=''">
and sex=#{sex}
</if>
</where>
</sql>
<select id="findUserNameAndSex" parameterType="cn.itheima.pojo.User" resultType="cn.itheima.pojo.User">
select * from user where 1=1
<!-- 如果不用include调用SQL条件,就直接这样写
<where>
<if test="username != null and username !=''">
and username like '%${username}%'
</if>
<if test="sex != null and sex !=''">
and sex=#{sex}
</if>
</where> -->
<!-- 调用SQL条件 -->
<include refid="user_Where"></include>
</select>
</mapper>
3.1.2 在UserMapper接口中加入代码:
public List<User> findUserNameAndSex(User user);
3.1.3 在测试类UserMapperTest中加入代码测试:
@Test
public void testFindUserByUserNameAndSex() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
User user=new User();
user.setUsername("王");
user.setSex("1");
List<User> list = mapper.findUserNameAndSex(user);
System.out.println(list);
}
3.2 foreach用法
3.2.1 在UserMapper.xml中加入代码:
<select id="findUserByIds" parameterType="cn.itheima.pojo.QueryVo" resultType="cn.itheima.pojo.User">
select * from user
<where>
<if test="ids !=null">
<!--
foreach:循环传入的集合参数
collection:传入的集合变量名称
item:每此循环将循环出的数据放入这个变量
open:循环开始拼接的字符串
close:循环结束拼接的字符串
separator:循环中拼接的分隔符
-->
<foreach collection="ids" item="id" open="id in (" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
3.2.2 在UserMapper接口中加入代码:
public List<User> findUserByIds(QueryVo vo);
3.2.3 在QueryVo类中加入代码:
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
3.2.4 在测试类UserMapperTest中加入代码测试:
@Test
public void testFindUserByIds() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
QueryVo vo=new QueryVo();
List<Integer> ids=new ArrayList<Integer>();
ids.add(1);
ids.add(16);
ids.add(29);
ids.add(22);
vo.setIds(ids);
List<User> list = mapper.findUserByIds(vo);
System.out.println(list);
}
4. 单个对象映射关系(从订单对用户)
4.1 编写Orders类
package cn.itheima.pojo;
import java.util.Date;
public class Orders {
private Integer id;
private Integer userId;
private String number;
private Date createtime;
private String note;
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number == null ? null : number.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note == null ? null : note.trim();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
4.2 编写CustomOrders类(说明:手动映射不需要CustomOrders类)
package cn.itheima.pojo;
import java.util.Date;
public class CustomOrders extends Orders{
private int uid;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
4.3 在UserMapper.xml中加入代码:
<!-- 一对一:自动映射 -->
<select id="findOrderAndUser1" resultType="cn.itheima.pojo.CustomOrders">
select a.*, b.id uid, username, birthday, sex, address
from orders a, user b
where a.user_id = b.id
</select>
<!-- 一对一:手动映射 -->
<!--
id:resultMap的唯一标识
type:将查询出的数据放入这个指定的对象中
注意:手动映射要指定是数据库中表的字段与java中pojo类的属性名称的对应关系
-->
<resultMap type="cn.itheima.pojo.Orders" id="orderAndUserResultMap">
<!-- id标签指定主键对应关系
column:数据库中字段名称
property:java中pojo类的属性
-->
<id column="id" property="id"/>
<!-- result:指定非主键对应关系 -->
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
<result column="note" property="note"/>
<!-- 这个标签指定单个对象的对应关系
property:指定将数据放入Order中的user属性中
javaType:usetr属性的类型
-->
<association property="user" javaType="cn.itheima.pojo.User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findOrderAndUser2" resultMap="orderAndUserResultMap">
select a.*, b.id uid, username, birthday, sex, address
from orders a, user b
where a.user_id = b.id
</select>
4.4 在UserMapper接口中加入代码:
public List<CustomOrders> findOrderAndUser1();
public List<Orders> findOrderAndUser2();
4.5 在测试类UserMapperTest中加入代码测试:
@Test
public void testFindOrderAndUser1() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
List<CustomOrders> list = mapper.findOrderAndUser1();
System.out.println(list);
}
@Test
public void testFindOrderAndUser2() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
List<Orders> list = mapper.findOrderAndUser2();
System.out.println(list);
}
5.集合对象映射(从用户对订单)
5.0 Orders类不变
5.1 在User类中加入代码:
private List<Orders> orderList;
public List<Orders> getOrderList() {
return orderList;
}
public void setOrderList(List<Orders> orderList) {
this.orderList = orderList;
}
5.2 在UserMapper.xml中加入代码:
<!-- 一对多 -->
<resultMap type="cn.itheima.pojo.User" id="userAndOrdersResultMap">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="sex" property="sex"/>
<result column="address" property="address"/>
<!-- collection:指定对应的集合关系映射
property:将数据放入User对象中的orderList属性中
ofType:指定orderList属性的泛型类型
-->
<collection property="orderList" ofType="cn.itheima.pojo.Orders">
<id column="oid" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<result column="createtime" property="createtime"/>
</collection>
</resultMap>
<select id="findOrderAndUsers" resultMap="userAndOrdersResultMap">
select a.*,b.id oid ,user_id, number, createtime
from user a,orders b
where a.id=b.user_id
</select>
5.3在UserMapper接口中加入代码:
public List<User> findOrderAndUsers();
5.4 在测试类UserMapperTest中加入代码测试:
@Test
public void testfindOrderAndUsers() throws Exception{
SqlSession openSession = factory.openSession();
//通过getMapper方法实例化接口
UserMapper mapper = openSession.getMapper(UserMapper.class);
List<User> list = mapper.findOrderAndUsers();
System.out.println(list);
}
附:
6. Mybatis整合Spring
整合思路:
1、SqlSessionFactory对象应该放到spring容器中作为单例存在。
2、传统dao的开发方式中,应该从spring容器中获得sqlsession对象。
3、Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。
4、数据库的连接以及数据库连接池事务管理都交给spring容器来完成。
6.0.0 db.properties和log4j.properties以及、User.xml、UserDao、不做改变(参见Mybatis-1)
UserMapper、UserMapper.xml、User不做改变
6.0.1 修改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>
<!-- typeAlias:定义单个pojo类别名
type:类的全路径名称
alias:别名
-->
<!-- <typeAlias type="cn.itheima.pojo.User" alias="user"/> -->
<!-- package:使用包扫描的方式批量定义别名
定以后别名等于类名,不区分大小写,但是建议按照java命名规则来,首字母小写,以后每个单词的首字母大写
-->
<package name="cn.itheima.pojo"/>
</typeAliases>
<mappers>
<mapper resource="User.xml"/>
<!--
使用class属性引入接口的全路径名称:
使用规则:
1. 接口的名称和映射文件名称除扩展名外要完全相同
2. 接口和映射文件要放在同一个目录下
-->
<!-- <mapper class="cn.itheima.mapper.UserMapper"/> -->
<!-- 使用包扫描的方式批量引入Mapper接口
使用规则:
1. 接口的名称和映射文件名称除扩展名外要完全相同
2. 接口和映射文件要放在同一个目录下
-->
<!-- <package name="cn.itheima.mapper"/> -->
</mappers>
</configuration>
6.0.2 添加ApplicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- 整合Sql会话工厂归spring管理 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定mybatis核心配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
<!-- 指定会话工厂使用的数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
6.1 整合后原生Dao
6.1.1 在ApplicationContext.xml添加代码
<!--
配置原生Dao实现
注意:class必须指定Dao实现类的全路径名称
-->
<bean id="userDao" class="cn.itheima.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
6.1.2 修改UserDaoImpl为:
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User findUserById(Integer id) {
//openSession是线程不安全的,所以它的最佳使用范围在方法体内
SqlSession openSession = this.getSqlSession();
User user = openSession.selectOne("test.findUserById", id);
//整合后会话由spring来管理,所以不要手动关闭
//openSession.close();
return user;
}
@Override
public List<User> findUserByUserName(String userName) {
SqlSession openSession = this.getSqlSession();
List<User> list = openSession.selectList("test.findUserByUserName", userName);
return list;
}
}
6.1.3 修改测试类为:
public class UserDaoTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception{
String configLocation="ApplicationContext.xml";
applicationContext=new ClassPathXmlApplicationContext(configLocation);
}
@Test
public void testFindUserById() throws Exception{
//获取UserDao对象,getBean中的字符串是在ApplicationContext.xml声明的
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
User user = userDao.findUserById(1);
System.out.println(user);
}
}
6.2 整合后Mapper接口代理
6.2.1 在ApplicationContext.xml添加代码
<!-- Mapper接口代理实现 -->
<!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> -->
<!-- 配置mapper接口的全路径名称 -->
<!-- <property name="mapperInterface" value="cn.itheima.mapper.UserMapper"></property> -->
<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> -->
<!-- </bean> -->
<!-- 使用包扫描的方式批量引入Mapper
扫描后引用的时候可以使用类名,首字母小写.
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定要扫描的包的全路径名称,如果有多个包用英文状态下的逗号分隔 -->
<property name="basePackage" value="cn.itheima.mapper"></property>
</bean>
6.2.1修改测试类为:
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception{
String configLocation="ApplicationContext.xml";
applicationContext=new ClassPathXmlApplicationContext(configLocation);
}
@Test
public void testFindUserById() throws Exception{
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
}
附:
7.逆向工程
7.0 创建数据库和表
7.1 导入所需jar
7.2 编写配置文件genarator.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"
password="root">
</jdbcConnection>
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
userId="yycg"
password="yycg">
</jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="cn.itheima.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="cn.itheima.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="cn.itheima.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<!-- <table tableName="items"></table> -->
<table tableName="orders"></table>
<!-- <table tableName="orderdetail"></table> -->
<table tableName="user"></table>
<!-- <table schema="" tableName="sys_user"></table>
<table schema="" tableName="sys_role"></table>
<table schema="" tableName="sys_permission"></table>
<table schema="" tableName="sys_user_role"></table>
<table schema="" tableName="sys_role_permission"></table> -->
<!-- 有些表的字段需要指定java类型
<table schema="" tableName="">
<columnOverride column="" javaType="" />
</table> -->
</context>
</generatorConfiguration>
7.3 运行特定程序
public class StartServer {
public void generator() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("genarator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
callback, warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) throws Exception {
try {
StartServer startServer = new StartServer();
startServer.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
7.4 运行完特定程序后可以看到会自动创建好指定的pojo类和对应的Mapper接口、Mapper.xml
7.5 用自动生成的pojo类、Mapper接口、Mapper.xml替换调之前手动编写的进行测试
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception{
String configLocation="ApplicationContext.xml";
applicationContext=new ClassPathXmlApplicationContext(configLocation);
}
// @Test
// public void testFindUserById() throws Exception{
// UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
// User user = userMapper.findUserById(1);
// System.out.println(user);
// }
@Test
public void testFindUserById() throws Exception{
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user);
}
@Test
public void testFindUserAndSex() throws Exception{
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
//创建UserExample对象
UserExample userExample=new UserExample();
//通过UserExample对象创建查询条件封装对象(Criteria中是封装的查询条件)
Criteria criteria = userExample.createCriteria();
//加入查询条件
criteria.andUsernameLike("%王%");
criteria.andSexEqualTo("1");
List<User> list = userMapper.selectByExample(userExample);
System.out.println(list);
}
}
8.总结
8.1. 输入映射(就是映射文件中可以传入哪些参数类型)
1)基本类型
2)pojo类型
3)Vo类型
8.2. 输出映射(返回的结果集可以有哪些类型)
1)基本类型
2)pojo类型
3)List类型
8.3. 动态sql:动态的拼接sql语句,因为sql中where条件有可能多也有可能少
1)where:可以自动添加where关键字,还可以去掉第一个条件的and关键字
2)if:判断传入的参数是否为空
3)foreach:循环遍历传入的集合参数
4)sql:封装查询条件,以达到重用的目的
8.4. 对单个对象的映射关系:
1)自动关联(偷懒的办法):可以自定义一个大而全的pojo类,然后自动映射其实是根据数据库总的字段名称和
pojo中的属性名称对应.
2)手动关联: 需要指定数据库中表的字段名称和java的pojo类中的属性名称的对应关系.
使用association标签
8.5. 对集合对象的映射关系
只能使用手动映射:指定表中字段名称和pojo中属性名称的对应关系
使用collection标签
8.6. spring和mybatis整合
整合后会话工厂都归spring管理
1)原生Dao实现:
需要在spring配置文件中指定dao实现类
dao实现类需要继承SqlSessionDaoSupport超类
在dao实现类中不要手动关闭会话,不要自己提交事务.
2)Mapper接口代理实现:
在spring配置文件中可以使用包扫描的方式,一次性的将所有mapper加载
8.7. 逆向工程:自动生成Pojo类,还可以自动生成Mapper接口和映射文件
注意:生成的方式是追加而不是覆盖,所以不可以重复生成,重复生成的文件有问题.
如果想重复生成将原来生成的文件删除