练习黑马SSM课程中Spring整合Mybatis
目录
简介
Spring整合Mybatis的纯注解开发,注解开发更为方便。
此案例用来加强自己的理解。
一、pom.xml需要引入的坐标:
1. spring-context (Spring的ioc容器)
2. druid (连接池)
3. mybatis (mybatis框架)
4.mysql-connector-java (mysql的驱动)
5.spring-jdbc (Spring操作数据库需要该jar包)
6.mybatis-spring (Spring与Mybatis整合的jar包)
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<!--Spring操作数据库需要该jar包-->
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<!--
Spring与Mybatis整合的jar包
这个jar包mybatis在前面,是Mybatis提供的
-->
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
二、具体步骤:
1. pojo实体类 - Account
在main目录下的java目录下新建com.huayu.pojo,新建出Account类
本类是要与数据库数据相对应的一个实体类。
作用:数据层与业务层交互数据
package com.huayu.pojo;
public class Account{
private Integer id;
private String name;
private Double money;
//省略set、get和toString方法
}
2.mapper以及对应映射的xml文件
在main.java.com.huayu目录下新建mapper包,新建AccountMapper接口
在main.resources下新建com.huayu.mapper与之对应,注意要用 " / "
作用:写sql语句,可以通过注解或xml文件写sql语句
package com.huayu.mapper;
import com.huayu.pojo.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 AccountMapper {
@Insert("insert into tbl_account(name,money) values(#{name},#{money})")
void save(Account account);
@Delete("delete from tbl_account where id = #{id} ")
void delete(Integer id);
@Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
void update(Account account);
@Select("select * from tbl_account")
List<Account> findAll();
@Select("select * from tbl_account where id = #{id} ")
Account findById(Integer id);
}
3. 编写Service层
在main.java.com.huayu目录下新建service包,在此包下新建AccountService接口
在main.java.com.huayu.service目录下新建impl包,在此包下新建AccountServiceImpl实现类
作用:Service层是处理逻辑上的业务,而不去考虑具体的实现。结合Spring后,使用@Service,表明该Service交由Spring管理。使用@Autowired表明自动装配注入成一个bean。
注意:写Service与写Component一样,只是为了方便区分,分层管理。
AccountServiceImpl实现类
package com.huayu.service.impl;
import com.huayu.mapper.AccountMapper;
import com.huayu.pojo.Account;
import com.huayu.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 AccountMapper accountMapper;
// 添加
public void save(Account account) {
accountMapper.save(account);
}
// 删除
public void delete(Integer id) {
accountMapper.delete(id);
}
// 修改
public void update(Account account) {
accountMapper.update(account);
}
// 查询所有
public List<Account> findAll() {
return accountMapper.findAll();
}
// 通过id查
public Account findById(Integer id) {
return accountMapper.findById(id);
}
}
AccountService接口
package com.huayu.service;
import com.huayu.pojo.Account;
import java.util.List;
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
4. 编写配置文件jdbc.properties
在main.resources下新建jdbc.properties,书写下面代码
作用:用来封装duird需要的数据,写到配置文件中,让程序解耦(复用性强)
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///db1?useSSL=false jdbc.username=root jdbc.password=1234
5. 通过编写配置类替代xml配置,实现纯注解开发
在main.java.com.huayu下新建config包
1. 编写SpringConfig配置类
在main.java.com.huayu.config下新建SpringConfig类
@Configurable配置类注解
作用:替换Spring的配置类。此案例按类型,因此不写参数了。
@ComponentScan注解
作用:替换Spring配置中别名扫描的包路径,用来包扫描。
注意:因为我们已经在Service层的实现类中通过@Autowired完成注入Account类,所以扫描的是service层的实现类对象AccountServiceImpl
@PropertySource注解
作用:加载我们书写的jdbc.properties配置文件
@Import注解
作用:因为有一些其他的配置,我们为了方便管理,可以写在其他类中。通过此注解在导进来
package com.huayu.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configurable //配置类注解
@ComponentScan("com.huayu") //包扫描,主要扫描的是项目中的AccountServiceImpl类
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatiesConfig.class})
public class SpringConfig {
}
2. 编写JdbcConfig配置类
在main.java.com.huayu.config下新建JdbcConfig类
@Value注解
作用:获取我们已经在Spring配置类中定义过的jdbc.properties里的值
@Bean
作用:用此注解声明一个bean,此bean用来设置DataSource,用标准的第三方配置文件注入格式,将数据依次写出
package com.huayu.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;
}
}
3. 编写MybatisConfig配置类
在main.java.com.huayu.config下新建MybatiesConfig类
知识点:
1. 这是是配置类替换的mybatis的配置文件
2. 我们需要获取SqlSessionFactory对象来执行sql语句,可以使用一个框架方便我们开发:SqlSessionFactoryBean,里面有很多默认值,我们只要设置一些必要的,比如设置模型类的别名扫描,设置数据源(DataSource)。
3. 我们要设置mapper映射文件,通过MapperScannerConfigurer对象,再告诉它映射的位置即可
package com.huayu.config;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MybatiesConfig {
//定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//设置模型类的别名扫描
ssfb.setTypeAliasesPackage("com.huayu.pojo");
//设置数据源
ssfb.setDataSource(dataSource);
return ssfb;
}
//定义bean,返回MapperScannerConfigurer对象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.huayu.mapper");
return msc;
}
}
6. 编写App类测试
在main.java下新建App类
知识点:我们要做的是获取Spring容器。把bean给get出来,该bean已经交给service管理,直接通过AccountService对象执行方法。我们将查询的结果返回出来。
import com.huayu.config.SpringConfig;
import com.huayu.pojo.Account;
import com.huayu.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.io.IOException;
public class App {
public static void main(String[] args) throws IOException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = ctx.getBean(AccountService.class);//已经交给service管理
Account account = accountService.findById(1);
System.out.println(account);
}
}
7. 所有的目录结构
8. 返回结果
我们返回的数据库中id为1的数据
四月 06, 2023 9:16:13 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited
Account{id=1, name='xzz', money=6000.0}