基本使用
1.基本使用
本篇主要内容如下:
- hello world
- 接口注解(了解)
- 接口与 xml 结合使用
- 表的基本操作
- 优化连接配置文件
- 别名管理器(了解)
- mybatisX 插件
- 插入数据后获取自增 id
- 全 map 操作
hello world1.环境搭建
创建 maven web 项目 mybatis01 并添加 maven 依赖如下。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>2.数据准备
为了方便学习,执行以下创表命令和插入数据命令。
CREATE TABLE `pet` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`weight` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
insert into `pet`(`id`,`name`,`weight`) values (1,'花花',4.5);
insert into `pet`(`id`,`name`,`weight`) values (2,'白白',5.6);
insert into `pet`(`id`,`name`,`weight`) values (3,'黑黑',7.8);
insert into `pet`(`id`,`name`,`weight`) values (4,'红红',9);3.配置核心配置文件
配置 mybatis 核心配置文件:mybatis-conf.xml,在 resource 目录下创建此文件,内容如下:
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
</configuration>
注意:
dataSource 的类型可以配置成其内置类型之一, UNPOOLED、POOLED 、JNDI。
- UNPOOLED,MyBatis 会为每一个数据库操作创建一个新的连接,并关闭它。该方式适用于只有小规模数量并发用户的简单应用程序上。
- POOLED,MyBatis 会创建一个数据库连接池,连接池中的一个连接将会被用作数据库操作。一旦数据库操作完成,MyBatis 会将此连接返回给连接池。在开发或测试环境中,经常使用此种方式。
- JNDI,MyBatis 从在应用服务器向配置好的 JNDI 数据源 dataSource 获取数据库连接。在生产环境中,优先考虑这种方式。
4.日志配置(可不配置)
为了监控 mybatis 执行情况,我们通过 logback 打印相关程序运行情况。在 resource 下添加日志配置文件 logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p --- [%t] %-40.40logger{39} : %m%n</pattern>
</encoder>
</appender>
<!--根logger-->
<root level="DEBUG" additivity="false">
<appender-ref ref="console"/>
</root>
</configuration>加入该文件后,mybatis 运行情况、发送的 SQL、SQL 填充的数据和返回的数据条数都打印显示到控制台。
5.创建实体
创建对应实体,并添加对应的 getter 与 setter 方法。因为 mybatis 会使用反射完成对象的封装,所以实体一定需要无参构造方法。如果需要输出对象,还需要重写它的 toString 方法
public class Pet{
private Integer id;
private String name;
private Double weight
}6.创建 Mapper 文件
mybatis 的所有数据库操作都是通过 mapper 文件完成的。mapper 文件一般存放在 resource/mapper/ 目录下。
创建实体类对应的映射文件 *Mapper.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.hxzy.mapper.petMapper">
<select id="getById" parameterType="int" resultType="cn.hxzy.entity.Pet">
select * from pet where id=#{id}
</select>
</mapper>注意:
parameterType:参数类型
resultType:方法返回类型(如果返回是集合,则返回类型添集合存放对象的类型的全路径)
不论是参数类型还是返回类型,自定义类都需要写类的全路径名。
7.注册 mapper 文件
在 mybatis 核心配置文件 mybatis-conf.xml 中注册上面的 *Mapper.xml
<mappers>
<mapper resource="mapper/PetMapper.xml"/>
</mappers>下面是对这几个配置文件一点解释说明:
1、配置文件 mybatis-conf.xml 是 mybatis 用来建立 sessionFactory,里面主要包含了数据库连接相关内容。
2、mybatis-conf.xml 里面的 <mapper resource="mapper/*Mapper.xml"/> 是包含要映射的类的 xml 配置文件。
3、在 *Mapper.xml 文件里面主要是定义各种 SQL 语句,以及这些语句的参数,以及要返回的类型等等。
8.运行测试
创建 main 方法并完成相关测试
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 java.io.IOException;
import java.io.Reader;
public class MainTest {
public static void main(String[] args) throws IOException {
//加载 mybatis 的核心配置文件(它也加载关联的映射文件)
Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
//构建 sqlSession 的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中 sql 的 sqlSession
SqlSession session = sessionFactory.openSession();
Object o = session.selectOne("cn.hxzy.mapper.petMapper.getById",3);
System.out.println(o);
}
}
注意:
1.selectOne 设计的初衷是查询单个,当查询时出现多个结果会报下面的错误:如果查询出来是集合用 selectList 方法。
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 32.SqlSessionFactory 线程安全性,可以设计成单例
3.SqlSession 线程非安全,不能做类的公用变量
练习:
1.创建项目 fruit01,并在项目中创建 fruit(id,name,color)实体和对应的数据库表,并完成根据 id 查询水果和查询全部水果功能。
参考代码:
<?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.hxzy.mapper.fruitMapper">
<select id="getById" parameterType="int" resultType="cn.hxzy.entity.Fruit">
select * from fruit where id=#{id}
</select><select id="findAll" resultType="cn.hxzy.entity.Fruit"> select * from fruit where id=#{id} </select>
</mapper>
接口注解(了解)
在上一节中实现了 mybatis 的一个简单的查询,还有更简单的方法,使用合理描述参数和 SQL 语句返回值的接口(比如:IUserMapper.java),这样现在就可以不使用类似 UserMapper.xml 配置文件,至此更简单,代码更安全,不容易发生的字符串文字和转换的错误,下面是项目创建的详细过程:
创建一个接口:PetMapper,并在其中声明对应的操作方法
public interface PetMapper {
@Insert("insert into pet(name,weight) values (#{name},#{weight})")
int add(Pet pet);@Select("select * from pet where id=#{id}") Pet getById(int id);
}
在 mybatis-conf.xml 里面注册 mapper 接口
<mapper class="cn.hxzy.mybatis.mapper.PetMapper"/>测试类修改下面的位置完成测试
public static void main(String[] args) throws IOException {
//加载mybatis的配置文件(它也加载关联的映射文件)
Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
//构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
//映射sql的标识字符串
//执行查询返回一个唯一user对象的sql
Pet pet = session.getMapper(PetMapper.class ).getById( 1 );
//根据 mapper 的 namespace 和 id 调用方法
System.out.println(pet);
}至此,基于接口注解的查询方式完成,使用注解时 SQL 很难动态,所以最常用的是接口与 xml 结合使用。
注意:在执行数据库增删改操作时 session 默认是不自动提交的。需要手动调用 session.commit();提交操作。
练习:
1.创建项目 pet01 并使用注解完成宠物的基本操作 pet(添加、根据 id 修改、根据 id 删除、查询全部),并使用单元测试检测方法的可用性。
2.在项目 pet01 中使用全注解的方式完成水果 fruit(id,name,color)的基本操作并测试。
参考答案:
PetMapper
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;public interface PetMapper {
@Insert("insert into pet(name,weight) values (#{name},#{weight})")
int add(Pet pet);@Update("update pet set name=#{name},weight=#{weight} where id=#{id}") int update(Pet pet); @Delete("delete from pet where id =#{id}") int deleteById(int id); @Select("select * from pet") List<Pet> findAll();
}
单元测试
import cn.hxzy.entity.Pet;
import cn.hxzy.mapper.PetMapper;
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.IOException;
import java.io.Reader;
import java.util.List;public class MainTest {
SqlSession session;@Before public void before() throws IOException { Reader reader = Resources.getResourceAsReader("mybatis-conf.xml"); //构建 sqlSession 的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //创建能执行映射文件中 sql 的 sqlSession session = sessionFactory.openSession(true); reader.close(); } @Test public void add() throws IOException { PetMapper mapper = session.getMapper(PetMapper.class); Pet pet = new Pet(); pet.setName("花花"); pet.setWeight(12.5); mapper.add(pet); } @Test public void update() throws IOException { PetMapper mapper = session.getMapper(PetMapper.class); Pet pet = new Pet(); pet.setId(6); pet.setName("花花"); pet.setWeight(12.5); mapper.update(pet); } @Test public void delete() throws IOException { PetMapper mapper = session.getMapper(PetMapper.class); mapper.delete(2); } @Test public void findAll() throws IOException { PetMapper mapper = session.getMapper(PetMapper.class); List<Pet> all = mapper.findAll(); System.out.println(all); } @After public void close() { session.close(); }
}
接口与 xml 结合使用
在实际开发中使用比较多的是接口与 xml 结合使用,这样既可以降低编写 statement 时使用字符串容易出错的概率,同时 xml 在编译过后里面的内容还是原样显示,方便后期的 SQL 优化。最后使用接口和 xml 结合的方式也体现 java 程序的高内聚低耦合特性。使用 接口与 xml 结合使用需要在 mybatis-conf.xml 里面注册对应用到的 xml。
<mappers>
<mapper resource="mapper/PetMapper.xml"></mapper>
</mappers>Mapper.xml 里面的<mapper namespace="cn.hxzy.mapper.PetMapper"> 的 namespace 指向接口的类路径,同时接口里面的方法和 xml 里面的 id 对应。
调用时还是通过接口调用,但是接口的注解需要全部去掉。
PetDao mapper = session.getMapper(PetDao.class);
System.out.println(mapper.queryById(87));这样我们就可以使用 mybatis 的动态 SQL,又可以通过接口调用,减少书写错误的可能。
数据表的基本操作
通过接口与 Mapper.xml 结合的方式可以很好的完成数据库的各种操作。在 mapper.xml 里面加入对应的 CRUD 的语句与接口中的方法名对应即可完成相关操作,对应的 mapper.xml 可以使用 insert、delete、update、select 等节点完成相应的操作,同时指定相应的参数类型和返回类型。
<insert id="insert" parameterType="cn.hxzy.entity.Pet">
insert into pet(name,weight) values(#{name},#{weight})
</insert><delete id="delete" parameterType="int">
delete from pet where id=#{id}
</delete><select id="getById" parameterType="int" resultType="cn.hxzy.entity.Pet">
select * from pet where id=#{id}
</select>
<select id="selectAll" resultType="cn.hxzy.entity.Pet">
select * from pet
</select>
注意:SQL 中含有特殊字符使用 <o:p></o:p>CDATA 标签
<if test="ageEnd!=null"><![CDATA[<]]> #{ageEnd}</if>
注意:
- xml 的 id 对应接口的方法名。
- 除了查询方法以外其它方法都必须添加事务
SqlSession session = sessionFactory.openSession();
session.getMapper( UserMapper.class ).insertUser( new User( "222",1 ) );
session.commit();session 有对应的提交与回滚的方法
或者获取 session 时就让 session 自动提交
SqlSession session = sessionFactory.openSession(true);练习:
1.创建项目 fruit02 使用 xml 与接口组合的方式完成 fruit 表的基本操作(添加、根据 id 修改、根据 id 删除、查询全部)并使用单元测试测试方法的可用性。
参考代码:
mapper 接口
public interface FruitMapper {int deleteByPrimaryKey(Integer id); int insert(Fruit record); List<Fruit> selectAll(); int updateByPrimaryKey(Fruit record);
}
mapper 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.hxzy.mapper.FruitMapper">
<resultMap id="BaseResultMap" type="cn.hxzy.entity.Fruit">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="color" jdbcType="VARCHAR" property="color"/>
</resultMap><sql id="Base_Column_List"> id, `name`, color </sql> <select id="selectAll" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from fruit </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from fruit where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="cn.hxzy.entity.Fruit"> insert into fruit (`name`, color) values (#{name,jdbcType=VARCHAR}, #{color,jdbcType=VARCHAR}) </insert> <update id="updateByPrimaryKey" parameterType="cn.hxzy.entity.Fruit"> update fruit set `name` = #{name,jdbcType=VARCHAR}, color = #{color,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update>
</mapper>
单元测试
import cn.hxzy.entity.Fruit;
import cn.hxzy.mapper.FruitMapper;
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.IOException;
import java.io.Reader;
import java.util.List;public class MainTest {
SqlSession session;@Before public void getSession() throws IOException { Reader reader = Resources.getResourceAsReader("mybatis-conf.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); session = sessionFactory.openSession(true); reader.close(); } @Test public void add() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); Fruit fruit = new Fruit(); fruit.setName("apple"); fruit.setColor("red"); mapper.insert(fruit); } @Test public void select() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); List<Fruit> fruits = mapper.selectAll(); System.out.println(fruits); } @Test public void delete() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); int i = mapper.deleteByPrimaryKey(1); System.out.println("数据库影响:" + i); } @Test public void update() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); Fruit fruit = new Fruit(); fruit.setId(1); fruit.setName("apple"); fruit.setColor("white"); mapper.insert(fruit); } @After public void close() { session.close(); }
}
优化连接配置文件
数据库连接信息专门放到一个文件中
resource 下创建 db.properties 文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
jdbc.username=root
jdbc.password=123456修改配置文件
<properties resource="db.properties"/>
<property name="driver" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
别名管理器(了解)
为实体类定义别名,简化 sql 映射 xml 文件中的引用,在 mybatis-conf.xml 文件加入
<typeAliases>
<typeAlias type="cn.hxzy.entity.Pet" alias="pet"/>
</typeAliases>type:指定要起别名的类型全类名,默认别名就是类名(不区分大小写);
alias:指定新的别名
这样,使用时使用别名即可操作数据库
<select id="selectById" parameterType="int" resultType="pet">
select * from pet where id=#{id}
</select>typeAliases 批量起别名
package:为某个包下的所有类批量起别名。
<typeAliases>
<package name="cn.hxzy.ibatis.bean"/>
</typeAliases> name:为当前包以及下面所有的后代包的每一个类都起一个默认别名(与类名相同且不区分大小写)
批量起别名的情况下,使用 @Alias 注解为某个类型指定新的别名。
mybatisX 插件
功能
1.mapper 接口与 xml 来回跳转。
2.mapper 方法自动生成 xml。
3.xml 校验 id 是否与接口方法名一致。
插入数据后获取自增 id
在开发中经常需要获取插入数据的自增 id,mybatis 底层会使用 jdbc 将获取到的 id 设置到参数对象中。配置如下:
<insert id="insert" parameterType="cn.hxzy.entity.Pet" keyProperty="id" useGeneratedKeys="true" >在执行完插入语句后该实体的 id 便不再为空。
keyProperty:表示返回的 id 要保存到对象的那个属性中
useGeneratedKeys:表示主键 id 为自增长模式
练习:
1.创建项目 fruit03,使用循环往数据库中插入 100 条 fruit 数据,并在插入前后输出对象的 id。
参考答案:
mapper xml
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="cn.hxzy.entity.Fruit" useGeneratedKeys="true">
insert into fruit (name, color)
values (#{name,jdbcType=VARCHAR}, #{color,jdbcType=VARCHAR})
</insert>测试:
import cn.hxzy.entity.Fruit;
import cn.hxzy.mapper.FruitMapper;
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.IOException;
import java.io.Reader;
import java.util.List;public class MainTest {
SqlSession session;@Before public void getSession() throws IOException { Reader reader = Resources.getResourceAsReader("mybatis-conf.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); session = sessionFactory.openSession(true); reader.close(); } @Test public void add() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); for (int i = 0; i < 100; i++) { Fruit fruit = new Fruit(); fruit.setName("apple" + i); fruit.setColor("red"); mapper.insert(fruit); System.out.println(fruit.getId()); } } @After public void close() { session.close(); }
}
全 map 操作
有时在开发中,由于数据库结构经常发生变化或开发人员为了图方便不创建实体,也就是在属性全部都使用 map 传输。
在使用 map 时注意将原来的实体位置全部换成 map 即可,一个对象对应一个 map。
接口改造:
import java.util.List;
import java.util.Map;
public interface PetMapper {
int insert(Map map);
List<Map> selectAll();
}
xml 改造:
<insert id="insert" parameterType="map">
insert into pet(name, weight) values(#{name}, #{weight})
</insert>
<select id="selectAll" resultType="map">
select * from pet
</select>
使用 map 极大的影响程序正确率与可读性。虽然这种操作并不是 java 程序设计者建议使用的,但是还是有很多程序员违规使用。
练习:
1.创建项目 fruit04 使用全 map 的方式完成 fruit 的基本操作,并使用单元测试判断方法的可用性。
参考代码:
mapper 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.hxzy.mapper.FruitMapper"><sql id="Base_Column_List"> id, `name`, color </sql> <select id="selectAll" parameterType="java.lang.Integer" resultType="map"> select <include refid="Base_Column_List"/> from fruit </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from fruit where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" keyColumn="id" keyProperty="id" parameterType="map" useGeneratedKeys="true"> insert into fruit (`name`, color) values (#{name,jdbcType=VARCHAR}, #{color,jdbcType=VARCHAR}) </insert> <update id="updateByPrimaryKey" parameterType="map"> update fruit set `name` = #{name,jdbcType=VARCHAR}, color = #{color,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update>
</mapper>
接口:
import java.util.List;
import java.util.Map;
public interface FruitMapper {int deleteByPrimaryKey(Integer id); int insert(Map record); List<Map> selectAll(); int updateByPrimaryKey(Map record);
}
测试:
import cn.hxzy.mapper.FruitMapper;
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.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class MainTest {
SqlSession session;@Before public void getSession() throws IOException { Reader reader = Resources.getResourceAsReader("mybatis-conf.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); session = sessionFactory.openSession(true); reader.close(); } @Test public void add() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); Map fruit = new HashMap(); fruit.put("name", "apple"); fruit.put("color", "red"); mapper.insert(fruit); } @Test public void select() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); List<Map> fruits = mapper.selectAll(); System.out.println(fruits); } @Test public void delete() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); int i = mapper.deleteByPrimaryKey(1); System.out.println("数据库影响:" + i); } @Test public void update() throws IOException { FruitMapper mapper = session.getMapper(FruitMapper.class); Map fruit = new HashMap(); fruit.put("id", 1); fruit.put("name", "apple"); fruit.put("color", "red"); mapper.insert(fruit); } @After public void close() { session.close(); }
}

浙公网安备 33010602011771号