一、环境搭建
??创建 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>
二、数据准备
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);
三、配置核心配置文件
??配置 mybatis 核心配置文件:mybatis-conf.xml,在 resource 目录下创建此文件,内容如下:
<!--?xml version="1.0" encoding="UTF-8"?-->
<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">
</property></property></property></property></datasource>
</transactionmanager></environment>
</environments>
</configuration>
注意:
??dataSource 的类型可以配置成其内置类型之一, UNPOOLED、POOLED 、JNDI。
??UNPOOLED,MyBatis 会为每一个数据库操作创建一个新的连接,并关闭它。该方式适用于只有小规模数量并发用户的简单应用程序上。 ??POOLED,MyBatis 会创建一个数据库连接池,连接池中的一个连接将会被用作数据库操作。一旦数据库操作完成,MyBatis 会将此连接返回给连接池。在开发或测试环境中,经常使用此种方式。 ??JNDI,MyBatis 从在应用服务器向配置好的 JNDI 数据源 dataSource 获取数据库连接。在生产环境中,优先考虑这种方式。
四、日志配置(可不配置)
??为了监控 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">
</appender-ref></root>
</configuration>
??加入该文件后,mybatis 运行情况、发送的 SQL、SQL 填充的数据和返回的数据条数都打印显示到控制台。
五、创建实体
??创建对应实体,并添加对应的 getter 与 setter 方法。因为 mybatis 会使用反射完成对象的封装,所以实体一定需要无参构造方法。如果需要输出对象,还需要重写它的 toString 方法。
public class Pet{
private Integer id;
private String name;
private Double weight
}
六、创建 Mapper 文件
??mybatis 的所有数据库操作都是通过 mapper 文件完成的。mapper 文件一般存放在 resource/mapper/ 目录下。
??创建实体类对应的映射文件 *Mapper.xml,详细如下代码所示:
<code><xmp><!--?xml version="1.0" encoding="UTF-8" ?-->
<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:方法返回类型(如果返回是集合,则返回类型添集合存放对象的类型的全路径)
??不论是参数类型还是返回类型,自定义类都需要写类的全路径名。
七、注册 mapper 文件
??在 mybatis 核心配置文件 mybatis-conf.xml 中注册上面的 *Mapper.xml。
<mappers>
<mapper resource="mapper/PetMapper.xml">
</mapper></mappers>
下面是对这几个配置文件一点解释说明: 1、配置文件 mybatis-conf.xml 是 mybatis 用来建立 sessionFactory,里面主要包含了数据库连接相关内容。 2、mybatis-conf.xml 里面的 是包含要映射的类的 xml 配置文件。 3、在 *Mapper.xml 文件里面主要是定义各种 SQL 语句,以及这些语句的参数,以及要返回的类型等等。
八、运行测试
??创建 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 {
Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
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: 3
2.SqlSessionFactory 线程安全性,可以设计成单例
3.SqlSession 线程非安全,不能做类的公用变量 练习:
1.创建项目 fruit01,并在项目中创建 fruit(id,name,color)实体和对应的数据库表,并完成根据 id 查询水果和查询全部水果功能。
参考代码: pom.xml代码如下:
<?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>org.example</groupId>
<artifactId>mybatis</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>fruit01</module>
</modules>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>8.5.59</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>
<?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">
<parent>
<artifactId>mybatis</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>fruit01</artifactId>
<name>fruit01</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<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.48</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<classpathScope>test</classpathScope>
</configuration>
</plugin>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
App.java代码如下:
package org.example;
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;
import java.util.List;
public class App {
public static void main(String[] args) throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
Fruit o = session.selectOne("com.allen.mapper.getById", 1);
System.out.println(o.toString());
List<Fruit> list = session.selectList("com.allen.mapper.findAll");
System.out.println(list);
session.close();
}
}
Fruit代码内容如下:
package org.example;
public class Fruit {
private Integer id;
private String name;
private String color;
@Override
public String toString() {
return "Fruit{" +
"id=" + id +
", name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
fruitMapper代码如下:
<?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.allen.mapper">
<select id="getById" parameterType="int" resultType="org.example.Fruit">
select * from fruit where id=#{id}
</select>
<select id="findAll" resultType="org.example.Fruit">
select * from fruit
</select>
</mapper>
mybatis-conf.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>
<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>
<mappers>
<mapper resource="mapper/fruitMapper.xml"></mapper>
</mappers>
</configuration>
九、测试结果如下:
|