概述
MyBatis是一个实现了数据持久化的开源框架,简单理解就是对JDBC进行封装。
ORMapping: Object Relationship Mapping 对象关系映射
对象:指面向对象
关系:指关系型数据库
Java 到 MySQL的映射,开发者可以以面向对象的思想来管理数据库。
MyBatis的优点
MyBatis缺点
如何使用?(基本配置)
1 . 新建Maven工程,在pom.xml文件中添加依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
</dependencies>
由于之后创建的Mapper.xml文件是在main/java下而不是放在main/resources下,默认是无法被读出的,所以需要加上build的配置,如下:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
2 . 新建数据库表(t_account)
use mybatis;
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
id为主键并且自增。
3 . 新建数据表对应的实体类(Account)
package com.fw.entity;
import lombok.Data;
@Data
public class Account {
private long id;
private String username;
private String password;
private int age;
}
创建的实体类的属性名要和DB表的字段名一一对应。
4 . 创建MyBatis配置文件,文件名可以自定义
<?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="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</dataSource>
</environment>
</environments>
</configuration>
一. 使用原生接口
1 . Mybatis框架需要开发者自定义SQL语句,写在Mapper.xml文件中,实际开发中会给每一个实体类创建对应的Mapper.xml,定义管理该对象数据的SQL。
<?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.fw.mapper.AccountMapper">
<insert id="save" parameterType="com.fw.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
</mapper>
namespace:通常设置为文件所在包名+文件名的形式。
insert:表示执行添加操作
select:表示执行查询操作
update:表示执行更新操作
delete:表示执行删除操作
id:表示实际调用MyBatis方法是需要的参数
parameterType:是调用对应方法的参数类型
2 . 在全局配置文件mybatis-config.xml文件中注册AccountMapper.xml
<!--注册Mapper-->
<mappers>
<mapper resource="com/fw/mapper/AccountMapper.xml"></mapper>
</mappers>
3 . 调用MyBatis原生接口执行添加操作
package com.fw.test;
import com.fw.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("mybatis-config.xml");
// 创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 通过SqlSessionFactoryBuilder的build方法创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 通过SqlSessionFactory的openSession方法创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// SQL语句的位置
String statement = "com.fw.mapper.AccountMapper.save";
// SQL语句参数
Account account = new Account(1L,"小红","123",20);
// 调用方法
sqlSession.insert(statement,account);
// 提交事务
sqlSession.commit();
// 关闭资源
sqlSession.close();
}
}
☼注:
在执行测试类时出现了下面的错误:
Cause: java.sql.SQLException: The server time zone value ‘������ʱ��’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the ‘serverTimezone’ configuration property) to use a more specifc time zone value if you want to utilize time zone support.
解决方法:
在url最后添加时区的设置
&serverTimezone=GMT
运行结果(DB插入数据):
1 小红 123 20
二 . 通过Mapper代理实现自定义接口
1 . 自定义接口
package com.fw.repository;
import com.fw.entity.Account;
import java.util.List;
public interface AccountRepository {
public int save(Account account);
public int update(Account account);
public int delete(long id);
public List<Account> findAll();
public Account findById(long id);
}
2 .创建接口对应的Mapper.xml,定义接口方法对应的SQL语句
statement标签可根据SQL执行的业务选择insert,delete,update,select。
MyBatis框架会根据规则自动创建接口实现类的代理对象。
规则:
<?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.fw.repository.AccountRepository">
<insert id="save" parameterType="com.fw.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>
<update id="update" parameterType="com.fw.entity.Account">
update t_account set username = #{username},password = #{password},age = #{age} where id = #{id}
</update>
<delete id="delete" parameterType="long">
delete from t_account where id=#{id}
</delete>
<select id="findAll" resultType="com.fw.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.fw.entity.Account">
select * from t_account where id = #{id}
</select>
</mapper>
3 . 注册Mapper.xml
<mapper resource="com/fw/repository/AccountMapper.xml"></mapper>
4 . 测试:调用接口的代理对象执行SQL
package com.fw.test;
import com.fw.entity.Account;
import com.fw.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
// 加载MyBatis配置文件
InputStream inputStream =Test.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
// 创建SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 通过SqlSessionFactoryBuilder的build方法创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 通过SqlSessionFactory的openSession方法创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取实现接口的代理对象
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
// 查询All
findAllTest(accountRepository);
// 查询byId
findByIdTest(accountRepository);
// 添加对象
saveTest(accountRepository,sqlSession);
// 更新对象
updateTest(accountRepository,sqlSession);
// 删除对象
deleteTest(accountRepository,sqlSession);
// 关闭资源
sqlSession.close();
}
public static void findAllTest(AccountRepository accountRepository){
// 查询
List<Account> accountList = accountRepository.findAll();
for (Account account:accountList) {
System.out.println(account);
}
}
public static void findByIdTest(AccountRepository accountRepository){
// 查询
Account account = accountRepository.findById(1L);
System.out.println(account);
}
public static void saveTest(AccountRepository accountRepository, SqlSession sqlSession){
// 添加对象
Account saveAccount = new Account(1L,"小蓝","456",22);
int saveCnt = accountRepository.save(saveAccount);
sqlSession.commit();
System.out.println("添加成功件数:" + saveCnt);
}
public static void updateTest(AccountRepository accountRepository,SqlSession sqlSession){
// 更新对象
Account updAccount = accountRepository.findById(1L);
updAccount.setUsername("花花");
updAccount.setPassword("999");
updAccount.setAge(30);
int updCnt = accountRepository.update(updAccount);
sqlSession.commit();
System.out.println("更新成功件数:" + updCnt);
}
public static void deleteTest(AccountRepository accountRepository,SqlSession sqlSession){
// 删除对象
int delCnt = accountRepository.delete(3L);
sqlSession.commit();
System.out.println("删除成功件数:" + delCnt);
}
}