在映射文件中,<mapper>元素是映射文件的根元素,其他标签都是其子元素。
<?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="com.itheima.mapper.CustomerMapper">
<select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
SELECT * FROM t_customer WHERE id = #{id}
</select>
<select id="findCustomerByName" parameterType="String" resultType="com.itheima.po.Customer">
SELECT * FROM t_customer WHERE username LIKE '%${value}%'
</select>
<insert id="addCustomer" parameterType="com.itheima.po.Customer">
INSERT INTO t_customer(username,jobs,phone) VALUES (#{username}, #{jobs}, #{phone})
</insert>
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
UPDATE t_customer SET username='${username}', jobs='${jobs}',phone='${phone}' WHERE id=${id}
</update>
<delete id="deleteCustomer" parameterType="Integer">
DELETE FROM t_customer WHERE id=#{id}
</delete>
</mapper>
select
用于映射查询语句,从数据库中读出数据,并组装数据给业务开发人员。
<select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
SELECT * FROM t_customer WHERE id = #{id}
</select>
上述语句中唯一标识为findCustomerById,它接受一个Integer类型的参数,并返回一个Customer类型的对象。
其常见属性如下:
属性 | 说明 |
---|---|
id | 表示命名空间中的为标识符,常与命名空间组合起来使用,组合后结果不唯一则MyBatis抛出异常 |
parameterType | 该属性表示传入SQL语句的参数类的全限定名或者别名。可选属性,因为MyBatis可以通过TypeHandler推断出具体传入语句的参数,默认值为unset(依赖于驱动) |
resultType | 从SQL语句返回的类型的类的全限定名或者别名。如果是集合类,那么返回的应该是集合可以包含的类型,而不是集合本身。返回时可以使用resultType或resultMap之一 |
resultMap | 表示外部resultMap的命名引用,返回时可以使用resultType或resultMap之一 |
useCache | 用于控制二级缓存的开启和关闭,其值为布尔类型,默认为true,表示查询结果存入二级缓存 |
flushCache | 表示调用SQL语句之后,是否需要MyBatis情况之前查询的本地缓存和二级缓存。其值为布尔类型,默认值为false。如果设置为true,则任何时候只要SQL语句被调用,都会清空本地缓存和二级缓存 |
timeout | 用于设置超时参数,单位为秒,超时将抛出异常 |
fetchSize | 获取记录的总条数设定,默认值为unset(依赖于驱动) |
statementType | 用于设置MyBatis使用哪个JDBC额Statement工作,其值为STATEMENT,PREPARED(默认值)或CALLABLE,分别对应JDBC中的Statement,PreparedStatement和CallableStatement |
resultSetType | 表示结果集的类型,其值可以设置为FORWARD_ONLY,SCROLL_SENSITIVE或SCROLL_INSENSITIVE,它的默认值是unset(依赖于驱动) |
insert
用于映射插入语句,在执行完语句后,返回一个表示插入记录数的整数。
其常见属性除了包含select的属性外,还有另外三种属性:
属性 | 说明 |
---|---|
id | 表示命名空间中的为标识符,常与命名空间组合起来使用,组合后结果不唯一则MyBatis抛出异常 |
parameterType | 该属性表示传入SQL语句的参数类的全限定名或者别名。可选属性,因为MyBatis可以通过TypeHandler推断出具体传入语句的参数,默认值为unset(依赖于驱动) |
resultType | 从SQL语句返回的类型的类的全限定名或者别名。如果是集合类,那么返回的应该是集合可以包含的类型,而不是集合本身。返回时可以使用resultType或resultMap之一 |
resultMap | 表示外部resultMap的命名引用,返回时可以使用resultType或resultMap之一 |
useCache | 用于控制二级缓存的开启和关闭,其值为布尔类型,默认为true,表示查询结果存入二级缓存 |
flushCache | 表示调用SQL语句之后,是否需要MyBatis情况之前查询的本地缓存和二级缓存。其值为布尔类型,默认值为false。如果设置为true,则任何时候只要SQL语句被调用,都会清空本地缓存和二级缓存 |
timeout | 用于设置超时参数,单位为秒,超时将抛出异常 |
fetchSize | 获取记录的总条数设定,默认值为unset(依赖于驱动) |
statementType | 用于设置MyBatis使用哪个JDBC额Statement工作,其值为STATEMENT,PREPARED(默认值)或CALLABLE,分别对应JDBC中的Statement,PreparedStatement和CallableStatement |
resultSetType | 表示结果集的类型,其值可以设置为FORWARD_ONLY,SCROLL_SENSITIVE或SCROLL_INSENSITIVE,它的默认值是unset(依赖于驱动) |
keyProperty | 此属性的作用是将插入或更新操作时将记录赋值给PO类的某个属性,通常会设置为主键对应的属性。如果时需要设置联合主键,可以在多个值之间用逗号隔开 |
keyColum | 此属性用于设置第几列是主键,当主键列不是表中的第一列是需要设置。在需要主键联合时,值可以用逗号隔开 |
useGeneratedKeys | 此属性会使MyBatis使用JDBC的getGeneratedKeys()方法来获取由数据库内部生产的主键,如MySQL和SQL Server等自动递增的字段,其默认值为false |
实例代码如下:
<insert id="addCustomer" parameterType="com.itheima.po.Customer" keyProperty="id" useGeneratedKeys="true">
INSERT INTO t_customer(username,jobs,phone) VALUES (#{username}, #{jobs}, #{phone})
</insert>
@Test
public void addCustomerTest() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Customer customer = new Customer();
customer.setUsername("keke");
customer.setJobs("student");
customer.setPhone("13553423238");
int rows = sqlSession.insert("com.itheima.mapper.CustomerMapper.addCustomer", customer);
System.out.println(customer.getId());
if(rows > 0) {
System.out.println("您成功插入了"+rows+"条数据");
}else {
System.out.println("执行插入操作失败!!!");
}
sqlSession.commit();
sqlSession.close();
}
insert和update有一个子标签selectKey。下面用selectKey标签来实现主键自动增长,以解释他的作用:
<insert id="addCustomer" parameterType="com.itheima.po.Customer">
<selectKey keyProperty="id" resultType="Integer" order="BEFORE">
select if(max(id) is null, 1, max(id)+1) as new newId from t_customer
</selectKey>
INSERT INTO t_customer(id,username,jobs,phone) VALUES (#{id},#{username}, #{jobs}, #{phone})
</insert>
selectKey元素有keyProperty,resultType,order和statementType。order属性可以设置为BEFORE和AFTER。BEFORE的话会先执行selectKey,再执行插入语句,AFTER的话会先执行插入语句,再执行selectKey。
update和delete
update映射更新语句,执行后返回一个整数,表示更新的条数。delete映射删除语句,执行后返回一个整数,代表删除的条数。其属性基本于select相同。
sql
可以用sql标签定义一段sql语句,然后可以用include标签进行重用。
演示如下:
<sql id="customerId">
FROM t_customer WHERE id = #{id}
</sql>
<select id="findCustomerById" parameterType="Integer" resultType="com.itheima.po.Customer">
SELECT * <include refid="customerId"/>
</select>
resultMap
表示结果映射集,定义映射规则,级联的更新以及定义类型的转换等。
其元素结构如下
<resultMap id="" type="">
<constructor> <!-- 类在实例化时,用来注入结果到构造方法中-->
<idArg></idArg> <!-- ID参数;标记结果作为ID -->
<arg/> <!-- 注入到构造方法的一个普通结果 -->
</constructor>
<id/> <!-- 用来表示哪个列是主键 -->
<result/> <!-- 注入到字段或JavaBean属性的普通结果 -->
<association property="" /> <!-- 用于一对一关联 -->
<discriminator javaType=""> <!-- 使用结果值来决定哪个结果集映射 -->
<case value=""></case> <!-- 基于某些值的结果映射 -->
</discriminator>
</resultMap>
实例代码如下:
<?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="com.itheima.mapper.UserMapper">
<resultMap id="resultMap" type="com.itheima.po.User">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
<result property="age" column="t_age"/>
</resultMap>
<select id="findAllUser" resultMap="resultMap">
SELECT * FROM t_user
</select>
</mapper>
写一个相应的测试方法
@Test
public void findAllUserTest() throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> list = sqlSession.selectList("com.itheima.mapper.UserMapper.findAllUser");
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
运行结果如下:
DEBUG [main] - ==> Preparing: SELECT * FROM t_user
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 3
User [id=1, name=lucy, age=25]
User [id=2, name=lili, age=20]
User [id=3, name=jim, age=20]