Spring整合Mybatis、Junit

Spring整合Mybatis、Junit

Spring整合Mybatis思路分析

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

Spring整合Junit

在这里插入图片描述

相关项目

在Mysql中新建一个tb_account表,字段如下所示:(id设置为自增)

在这里插入图片描述

插入一些数据:

在这里插入图片描述

项目截图如下:

在这里插入图片描述

整合Mybatis相关代码:

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.itheima.dao</groupId>
    <artifactId>spring_15_spring_mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
<!--        导入此依赖坐标,可在实体类中使用注解,:@Data-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
<!--        此依赖对应DruidDataSource -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
            <scope>compile</scope>
        </dependency>
<!--        导入mybatis-spring依赖坐标  spring整合mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>

<!--        导入此依赖可使用注解@Insert/@Select-->
        <dependency>
            <groupId>org.apache.ibatis</groupId>
            <artifactId>ibatis-core</artifactId>
            <version>3.0</version>
        </dependency>
<!--        导入mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
<!--        导入操作数据库专用的jar包 可以进行事务处理-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>

    </dependencies>



</project>
JdbcConfig配置类:
package com.itheima.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

/**
 * @author :LTY
 * @date :Created in 2023/4/17 16:10
 * @description:jdbc配置类
 * @modified By:
 * @version: $
 */
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的管理模式
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

}

MybatisConfig类:
package com.itheima.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

/**
 * @author :LTY
 * @date :Created in 2023/4/17 17:30
 * @description:mybatis的配置
 * @modified By:
 * @version: $
 * 此类用于替换SqlMapConfig.xml文件
 */
public class MybatisConfig {

//    SqlSessionFactoryBean负责创建SqlSessionFactory
    //数据源对象DataSource通过注入的形式加入的
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sql = new SqlSessionFactoryBean();
//        扫描类型别名的包
        sql.setTypeAliasesPackage("com.itheima.domain");
        sql.setDataSource(dataSource);
        return sql;
    }

//    此方法替代xml中的mappers
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
//        扫描映射的包,即设置基础扫描的包
        msc.setBasePackage("com.itheima.dao");
        return msc;

    }
}

SpringConfig类:
package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

/**
 * @author :LTY
 * @date :Created in 2023/4/17 15:36
 * @description:
 * @modified By:
 * @version: $
 */
@Configuration   //表示当前类为配置类
@ComponentScan("com.itheima")  //用于设定扫描路径,此注解只能添加一次,多个数据要使用数组格式
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MybatisConfig.class})   //使用@Import导入配置类
public class SpringConfig {
}

AccountDao接口:
package com.itheima.dao;

import com.itheima.domain.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;

/**
 * @author :ATO
 * @date :Created in 2023/3/29 19:52
 * @description:数据层的操作接口
 * @modified By:
 * @version: $
 * 此类为数据访问接口
 * 使用注解开发
 */
public interface AccountDao {

    //插入数据
    @Insert("insert into tb_account(name,money) values(#{name},#{money})")
    void save(Account account);

    //删除数据
    @Delete("delete from tb_account where id = #{id}")
    void delete(Integer id);

    //更新数据
    @Update("update tb_account set name = #{name}, money = #{money}  where id = #{id}")
    void update(Account account);

    //查询所有数据
    @Select("select * from tb_account")
    List<Account>  findAll();

    //依据id查询某一条记录
    @Select("select * from tb_account where id = #{id}")
    Account findById(Integer id);
}

Account实体类:
package com.itheima.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author :LTY
 * @date :Created in 2023/3/29 19:53
 * @description:Account实体类
 * @modified By:
 * @version: $
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account implements Serializable {

    private Integer id;

    private String name;

    private Double money;
}

AccountService业务层接口:
package com.itheima.service;

import com.itheima.domain.Account;

import java.util.List;

/**
 * @author :ATO
 * @date :Created in 2023/4/17 15:48
 * @description:业务层接口
 * @modified By:
 * @version: $
 */
public interface AccountService {

//    插入数据
    void save(Account account);
    //更新数据
    void update(Account account);
    //删除数据
    void delete(Integer id);
    //查询数据
    Account findById(Integer id);
    //查询所有数据
    List<Account> findAll();
}

AccountServiceImpl类:
package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author :LTY
 * @date :Created in 2023/4/17 15:57
 * @description:
 * @modified By:
 * @version: $
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public void save(Account account) {
        accountDao.save(account);
    }

    @Override
    public void update(Account account) {
           accountDao.update(account);
    }

    @Override
    public void delete(Integer id) {
        accountDao.delete(id);
    }

    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    @Override
    public List<Account> findAll() {
        return accountDao.findAll();
    }
}
App类:
package com.itheima;

import com.itheima.dao.AccountDao;
import com.itheima.domain.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;


/**
 * @author :LTY
 * @date :Created in 2023/4/1 21:16
 * @description:
 * @modified By:
 * @version: $
 */
public class App {

    public static void main(String[] args) throws IOException {
        //1.2.3点用于创建SqlSession对象
        //1.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //2.加载SqlMapConfig.xml配置文件
        InputStream inputAsStream = Resources.getResourceAsStream("SqlMapConfig.xml.bak");
        //3.创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputAsStream);
        //4.获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //5.执行SqlSession对象执行查询,获取结果User
        AccountDao mapper = sqlSession.getMapper(AccountDao.class);

        Account byId = mapper.findById(2);
        System.out.println(byId);

        //6.释放资源
        sqlSession.close();
    }
}
App2类:
package com.itheima;

import com.itheima.config.SpringConfig;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author :LTY
 * @date :Created in 2023/4/17 17:53
 * @description:
 * @modified By:
 * @version: $
 */
public class App2 {

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        AccountService accountService = ctx.getBean(AccountService.class);

        Account byId = accountService.findById(1);
        System.out.println(byId);
    }
}

jdbc.properties文件:
#mysql版本为8.0以下的,:com.mysql.jdbc.Driver 8.0以上的,:com.mysql.cj.jdbc.Driver
jdbc.driver= com.mysql.jdbc.Driver
#jdbc:mysql://localhost:3306/数据库名
jdbc.url = jdbc:mysql://localhost:3306/mybatis?SSL=false&characterEncoding=utf-8&userUnicode=true&Timezone=UTC
jdbc.username = root
jdbc.password = 010802
SqlMapConfig.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>

    <!--  引入properties文件,此后就可以在当前文件中使用的方式访问value   -->
    <properties resource="jdbc.properties"/>

    <!--
            typeAliases:设置类型别名,即为某个具体的类型设置一个别名
            在MyBatis的范围中,就可以使用别名表示一个具体的类型
         -->
    <typeAliases>
        <!-- 通过包设置类型别名,指定包下所有的类型将全部拥有默认的别名.即类名且不区分大小写 -->
        <package name="com.itheima.domain"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <!--
              transactionManager: 设置事务管理器
              属性:
              type:设置事务管理的方式
              type的属性值有:JDBC/MANAGED
              JDBC:表示使用JDBC中原生的事务管理方式(如:自动/手动提交事务或回滚事务)
              managed:被管理,如 :Spring整合
              -->
            <transactionManager type="JDBC"/>
            <!--
            连接池配置 数据库连接信息 数据源的配置
            dataSource: 设置数据源
            属性:
             type:设置数据源的类型
                type="POOLED|UNPOOLED|JNDI"
                POOLED:表示使用数据库连接池
                UNPOOLED:表示不使用数据库连接池
                JNDI:表示受用上下文中的数据源
            -->
            <dataSource type="POOLED">
                <!-- 引入外部环境 -->
                <!--              设置跳过jdbc的自动提交  -->
                <!--                <property name="skipSetAutoCommitOnClose" value="true"/>-->
                <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.itheima.dao"/>
    </mappers>
</configuration>

整合Junit

在这里插入图片描述

要想整合Junit的话,需要在pom.xml文件中导入以下两个坐标
<!--        spring整合junit要导入以下两个坐标-->
         <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
AccountServiceTest类:
package com.itheima.service;

import com.itheima.config.SpringConfig;
import com.itheima.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author :LTY
 * @date :Created in 2023/4/23 21:41
 * @description:测试类
 * @modified By:
 * @version: $
 * SpringJUnit4ClassRunner.class 为Spring整合Junit的专用类运行器
 */
@RunWith(SpringJUnit4ClassRunner.class)  //设置类运行器
@ContextConfiguration(classes = SpringConfig.class) //声明Spring的环境
public class AccountServiceTest {

    @Autowired  //自动装配
    private AccountService accountService;

    @Test
    public void testFindById() {
        System.out.println(accountService.findById(2));
    }

    @Test
    public void testFindAll() {
        System.out.println(accountService.findAll());
    }

    @Test
    public void testInsert() {
        Account account = new Account();
        account.setName("wangwu");
        account.setMoney(101.00);
       accountService.save(account);
    }

    @Test
    public void testDelete() {
        accountService.delete(3);
    }

    @Test
    public void testUpdate() {
        Account account = new Account();
        account.setName("里斯");
        account.setMoney(100.09);
        account.setId(4);
        accountService.update(account);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值