Mybatis概述
Mybatis是一个实现了数据持久化的开源框架,简单理解就是对JDBC进行封装,
ORMapping: Object Relationship Mapping 对象关系映射 ;
对象指⾯向对象 ;
关系指关系型数据库;
Java 到 MySQL 的映射,开发者可以以⾯向对象的思想来管理数据库。
Mybatis相当灵活,不会对应用程序或者数据库的现有设计强加任何影响,SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,并可重用。
如何使用
·新建 Maven ⼯程,pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
MySQL里新建数据表
use mybatis;
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
新建数据表对应的实体类 Account
package com.southwind.entity;
import lombok.Data;
@Data
public class Account {
private long id;
private String username;
private String password;
private int age;
}
创建 MyBatis 的配置⽂件 config.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>
<!-- 配置MyBatis运行环境 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED配置JDBC数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</dataSource>
</environment>
</environments>
</configuration>
使用原生接口
1、MyBatis 框架需要开发者⾃定义 SQL 语句,写在 Mapper.xml ⽂件中,实际开发中,会为每个实体类创建对应的 Mapper.xml ,定义管理该对象数据的 SQL。
新建XML文件:AccountMapper.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="com.mengru.mapper.AccoutMapper">
<insert id="save" parameterType="com.mengru.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
</mapper>
namespace 通常设置为⽂件所在包+⽂件名的形式。
insert 标签表示执⾏添加操作。
select 标签表示执⾏查询操作。
update 标签表示执⾏更新操作。
delete 标签表示执⾏删除操作。
id 是实际调⽤ MyBatis ⽅法时需要⽤到的参数。
parameterType 是调⽤对应⽅法时参数的数据类型。
2、在全局配置⽂件 config.xml 中注册 AccountMapper.xml
<!-- 注册AccountMapper.xml -->
<mappers>
<mapper resource="com/mengru/mapper/AccountMapper.xml"></mapper>
<mapper resource="com/mengru/repository/AccountRepository.xml"></mapper>
<mapper resource="com/mengru/repository/StudentRepository.xml"></mapper>
<mapper resource="com/mengru/repository/ClassesRepository.xml"/>
<mapper resource="com/mengru/repository/CustomerRepository.xml"/>
<mapper resource="com/mengru/repository/GoodsRepository.xml"/>
</mappers>
3、调⽤ MyBatis 的原⽣接⼝执⾏添加操作。
package com.mengru.test;
import com.mengru.entity.Account;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class Test {
public static void main(String[] args) {
//加载MyBatis配置文件
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//namespace结合id找到对应的SQL语句
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.mengru.mapper.AccoutMapper.save";
Account account = new Account(1L,"张三","123123",22);
sqlSession.insert(statement,account);
sqlSession.commit();
sqlSession.close();
}
}
这个时候运行可能会出错,因为idea默认从resources里读取xml文件,我得xml文件放到了mapper目录下。
解决办法:pom文件里新加以下build
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
通过 Mapper 代理实现⾃定义接⼝--该方式更加方便,推荐该方式。
1.⾃定义接⼝,定义相关业务⽅法。
2.编写与⽅法相对应的 Mapper.xml。
会根据mapper自动生成实现类。
面向对象的思想。
1、⾃定义接⼝
package com.mengru.repository;
import com.mengru.entity.Account;
import java.util.List;
public interface AccountRepository {
public int save(Account account);
public int update(Account account);
public int deleteById(long id);
public List<Account> findAll();
public Account findById(long id);
public Account findByName(String name);
public Account findById2(Long id);
public Account findByNameAndAge(String name,int age);
public int count();
public Integer count2();
public String findNameById(long id);
public Account findByAccount(Account account);
public List<Account> findByIds(Account account);
}
2、创建接⼝对应的 Mapper.xml(AccountRepository.xml),定义接⼝⽅法对应的 SQL 语句。
statement 标签可根据 SQL 执⾏的业务选择 insert、delete、update、select。
MyBatis 框架会根据规则⾃动创建接⼝实现类的代理对象。
规则:
Mapper.xml 中 namespace 为接⼝的全类名。
Mapper.xml 中 statement 的 id 为接⼝中对应的⽅法名。
Mapper.xml 中 statement 的 parameterType 和接⼝中对应⽅法的参数类型⼀致。
Mapper.xml 中 statement 的 resultType 和接⼝中对应⽅法的返回值类型⼀致。
<?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.mengru.repository.AccountRepository">
<insert id="save" parameterType="com.mengru.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
<!--<update id="update" parameterType="com.mengrutity.Account">-->
<!--update t_account set username = #{username},password = #{password},age = #{age} where id = #{id}-->
<!--</update>-->
<update id="update" parameterType="com.mengru.entity.Account">
update t_account
<set>
<if test="username!=null">
username = #{username},
</if>
<if test="password!=null">
password = #{password},
</if>
<if test="age!=0">
age = #{age}
</if>
</set>
where id = #{id}
</update>
<delete id="deleteById" parameterType="long">
delete from t_account where id = #{id}
</delete>
<select id="findAll" resultType="com.mengru.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.mengru.entity.Account">
select * from t_account where id = #{id}
</select>
<select id="findByName" parameterType="java.lang.String" resultType="com.mengru.entity.Account">
select * from t_account where username = #{username}
</select>
<select id="findById2" parameterType="java.lang.Long" resultType="com.mengru.entity.Account">
select * from t_account where id = #{id}
</select>
<select id="findByNameAndAge" resultType="com.mengru.entity.Account">
select * from t_account where username = #{arg0} and age = #{arg1}
</select>
<select id="count" resultType="int">
select count(id) from t_account
</select>
<select id="count2" resultType="java.lang.Integer">
select count(id) from t_account
</select>
<select id="findNameById" resultType="java.lang.String">
select username from t_account where id = #{id}
</select>
<select id="findByAccount" parameterType="com.mengru.entity.Account" resultType="com.mengru.entity.Account">
select * from t_account
<trim prefix="where" prefixOverrides="and">
<if test="id!=0">
id = #{id}
</if>
<if test="username!=null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="age!=0">
and age = #{age}
</if>
</trim>
</select>
<select id="findByIds" parameterType="com.mengru.entity.Account" resultType="com.mengru.entity.Account">
select * from t_account
<where>
<foreach collection="ids" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
</mapper>
3、在 config.xml 中注册 AccountRepository.xml
<!-- 注册AccountMapper.xml -->
<mappers>
<mapper resource="com/mengru/mapper/AccountMapper.xml"></mapper>
<mapper resource="com/mengru/repository/AccountRepository.xml"></mapper>
</mappers>
4、调⽤接⼝的代理对象完成相关的业务操作
package com.mengru.test;
import com.mengru.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class Test2 {
public static void main(String[] args) {
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取实现接口的代理对象
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
//添加对象
// Account account = new Account(3L,"王五","111111",24);
// int result = accountRepository.save(account);
// sqlSession.commit();
//查询全部对象
// List<Account> list = accountRepository.findAll();
// for (Account account:list){
// System.out.println(account);
// }
// sqlSession.close();
//通过id查询对象
// Account account = accountRepository.findById(3L);
// System.out.println(account);
// sqlSession.close();
//修改对象
// Account account = accountRepository.findById(3L);
// account.setUsername("小明");
// account.setPassword("000");
// account.setAge(18);
// int result = accountRepository.update(account);
// sqlSession.commit();
// System.out.println(result);
// sqlSession.close();
//通过id删除对象
// int result = accountRepository.deleteById(3L);
// System.out.println(result);
// sqlSession.commit();
// System.out.println(accountRepository.findByName("张三"));
// Long id = Long.parseLong("1");
// System.out.println(accountRepository.findById2(id));
// System.out.println(accountRepository.findByNameAndAge("张三",22));
// System.out.println(accountRepository.count());
// System.out.println(accountRepository.count2());
System.out.println(accountRepository.findNameById(1L));
sqlSession.close();
}
}
相比第一种方式:
//namespace结合id找到对应的SQL语句
String statement = "com.mengru.mapper.AccoutMapper.save";
//调用insert方法
Account account = new Account(1L,"张三","123123",22);
sqlSession.insert(statement,account);
第一种方式较为麻烦。