文章目录
spring整合Mybatis详细剖析版
一.MyBatis注解方式实现增删改查
1.简介Mybatis
1.1 何为Mybatis?
Mybatis是一个半ORM(对象关系映射)框架,内部封装JDBC,开发时只需关注SQL语句本身,无需额外关注加载驱动,建立连接,创建statement等繁琐过程,基于SQL语句编程,支持动态SQL语句
1.2 Mybatis对应的坐标
<?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>com.ttc</groupId>
<artifactId>springdemo2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!--导入spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--Jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- Druid依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</project>
2.数据库设计
2.1.新建tbl_account
CREATE TABLE `tbl_account` (
`id` int NOT NULL,
`name` varchar(255) DEFAULT NULL,
`money` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
2.2.添加基本数据
INSERT INTO `boot`.`tbl_account` (`id`, `name`, `money`) VALUES ('1', 'Tom', '1000');
INSERT INTO `boot`.`tbl_account` (`id`, `name`, `money`) VALUES ('2', 'Jerry', '500');
3.实体类设计
3.1 建立与之相映射的实体类
package com.ttc.entity;
public class Account {
private Integer id;
private String name;
private Integer money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
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 Integer getMoney() {
return money;
}
public void setMoney(Integer money) {
this.money = money;
}
}
4.dao层设计
4.1创建AccounntDao接口
用注解方法编写简易SQL语句
package com.ttc.dao;
import com.ttc.entity.Account;
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 AccountDao {
/**
* 1.查询单个数据
*/
@Select("select id,name,money from tbl_account where id = #{id}")
Account getById(Integer id);
/**
* 2.添加单个数据
*/
@Insert("insert into tbl_account(id,name,money) values(#{id},#{name},#{money})")
void save(Account account);
/**
* 3.修改单个数据
*/
@Update("update tbl_account set name = #{name},money = #{money} where id = #{id}")
void modify(@Param("name") String name, @Param("money") Integer money, @Param("id") Integer id);
/**
* 4.删除单个数据
*/
@Delete("delete from tbl_account where id = #{id}")
void remove(Integer id);
/**
* 5.查询所有数据
*/
@Select("select id,name,money from tbl_account")
List<Account> getAll();
}
4.2 建立jdbc配置文件
在src/main/resources目录下新建jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/boot
jdbc.username=root
jdbc.password=root
4.3 编写xml读取jdbc配置文件
在src/main/resources目录下新建SqlMapConfig.xml
- 加载数据库对应的外部配置信息
jdbc.properties
- 初始化类型别名
typeAliases
- 配置
dataSource
mapper
映射
<?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>
<!--加载外部properties文件-->
<properties resource="jdbc.properties"></properties>
<!--自定义别名-->
<typeAliases>
<!--批量别名定义,扫描包下的类,别名为类名(首字母大写或者小写都可以)-->
<package name="com.ttc.entity"></package>
</typeAliases>
<!--配置环境与下面对应-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置链接数据库信息:用的是数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--告知mybatis映射配置的位置-->
<mappers>
<package name="com.ttc.dao"></package>
</mappers>
</configuration>
5.启动类
- 初始化SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder()
- 读取xml配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml")
- 获得SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream)
- 获取SqlSession
SqlSeesion sqlSession = sqlSessionFactory.openSession()
- 得到Mapper
AccountDao accountDao = sqlSession.getMapper(AccountDao.class)
- 关闭SqlSession
sqlSession.close()
- sqlSession才是核心对象
- 增删改操作需要提交事务
- sqlSession用完记得关闭
package com.ttc;
import com.ttc.dao.AccountDao;
import com.ttc.entity.Account;
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.InputStream;
import java.util.List;
public class App {
public static void main(String[] args) throws IOException {
// 1.加载SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 2.获取xml配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
// 3.获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 4.获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 5.用SqlSession获取Dao对象
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
// 6.执行Dao里面的方法
// 6.1 查询单个数据
Account ac = accountDao.getById(1);
System.out.println("1.查询单个数据结果:" + ac);
// 6.2 添加单个数据
Account account = new Account();
account.setId(2);
account.setName("jerry");
account.setMoney(3000);
accountDao.save(account);
System.out.println("2.添加单个数据成功");
sqlSession.commit();
// 6.3 修改单个数据
accountDao.modify("小猪佩奇", 6666, 3);
System.out.println("3.修改单个数据成功");
sqlSession.commit();
// 6.4 删除单个数据
accountDao.remove(4);
System.out.println("4.删除单个数据成功");
sqlSession.commit();
// 6.5 查询所有数据
List<Account> accounts = accountDao.getAll();
for (Account k : accounts) {
System.out.println("5.查询所有数据结果:" + k);
}
// 7.释放SqlSession资源
sqlSession.close();
}
}
结果如下:
1.查询单个数据结果:Account{id=1, name='Tom', money=1000}
2.添加单个数据成功
3.修改单个数据成功
4.删除单个数据成功
5.查询所有数据结果:Account{id=1, name='Tom', money=1000}
5.查询所有数据结果:Account{id=3, name='小猪佩奇', money=6666}
5.查询所有数据结果:Account{id=4, name='青青草原一只羊', money=2000}
5.查询所有数据结果:Account{id=5, name='懒羊羊与灰太狼', money=2000}
Process finished with exit code 0
二.spring整合mybtatis进行数据操作
1.maven坐标导入
配置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>com.ttc</groupId>
<artifactId>springdemo2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!--导入Spring依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--Jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- Druid依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<!--导入Spring操作Jdbc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--Spring整合MyBatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
</project>
2.添加Spring的配置类
- SpringConfig
@Import
@Import({JdbcConfig.class,MybatisConfig.class})
@ComponentScan("com.ttc")
@PropertySource("classpath:jdbcConfig.properties")
package com.ttc.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Import;
@Configuration
@ComponentScan("com.ttc")
@Import({JdbcConfig.class,MybatisConfig.class})
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}
- JdbcConfig
- 如果给JdbcConfig加上
@Configuration
,则可被SpringConfig扫描 - 如果不给其加上
@Configuration
,则要在SpringConfig添加@Import(JdbcConfig.class)
- 如果给JdbcConfig加上
package com.ttc.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
- MybatisConfig
- SqlSessionFactoryBean
- MappperScannerConfigurer
package com.ttc.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MybatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasesPackage("com.ttc.dao");
ssfb.setDataSource(dataSource);
return ssfb;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.ttc.dao");
return msc;
}
}
- jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/boot
jdbc.username=root
jdbc.password=root
3.注解方式开发Dao
- 这里的
@Repository
注解也可以不加
package com.ttc.dao;
import com.ttc.entity.Account;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AccountDao {
/**
* 1.查询单个数据
*/
@Select("select id,name,money from tbl_account where id = #{id}")
Account getById(Integer id);
/**
* 2.添加单个数据
*/
@Insert("insert into tbl_account(id,name,money) values(#{id},#{name},#{money})")
void save(Account account);
/**
* 3.修改单个数据
*/
@Update("update tbl_account set name = #{name},money = #{money} where id = #{id}")
void modify(@Param("name") String name, @Param("money") Integer money, @Param("id") Integer id);
/**
* 4.删除单个数据
*/
@Delete("delete from tbl_account where id = #{id}")
void remove(Integer id);
/**
* 5.查询所有数据
*/
@Select("select id,name,money from tbl_account")
List<Account> getAll();
}
4.业务层调用Dao
1.AccountService
package com.ttc.service;
import com.ttc.entity.Account;
import java.util.List;
public interface AccountService {
Account getById(Integer id);
void save(Account account);
void modify(String name, Integer money, Integer id);
void remove(Integer id);
List<Account> getAll();
}
2.AccountServiceImpl
- 添加
@Service
- 添加
@Autowired
package com.ttc.service.impl;
import com.ttc.dao.AccountDao;
import com.ttc.entity.Account;
import com.ttc.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public Account getById(Integer id) {
return accountDao.getById(id);
}
public void save(Account account) {
accountDao.save(account);
}
public void modify(String name, Integer money, Integer id) {
accountDao.modify(name, money, id);
}
public void remove(Integer id) {
accountDao.remove(id);
}
public List<Account> getAll() {
return accountDao.getAll();
}
}
5.启动类
package com.ttc;
import com.ttc.config.SpringConfig;
import com.ttc.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = ctx.getBean(AccountService.class);
System.out.println(accountService.getById(2));
}
}
结果如下:
四月 06, 2023 5:06:11 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited
Account{id=2, name='jerry', money=3000}
Process finished with exit code 0