Spring整合MyBatis,与整合JUnit

目录

 Spring整合MyBatis

1.文件的大致格式(与JavaWeb时期相对比):

2.JdbcConfig(jdbc配置类,加载druid的properties文件)

3.MybatisConfig(MyBatis配置类,加载JdbcConfig中的dataSource配置信息)

4.SpringConfig(主配置类)

5.AccountDao(数据连接层,持久层)

6.domain(实体类)

7.AccountServiceImpl(Service业务层,组装Dao的操作)

8.AccountService(业务层接口)

9.App2(main方法  没有控制层)

10.jdbc.properties(druid的配置信息,被SpringConfig加载,被JdbcConfig所引用)

11.pom.xml(这个也比较重要,在总结里面会讲,自己看也能明白,我写注释了)

12.自我总结(理清大致思路):

Spring整合JUnit

1.文件的大致格式(与整合Mybatis相比增加了一个类,与pom文件里面的依赖)

2.AccountServiceTest类

3.pom.xml文件,增加了JUnit,与Spring-test

4.总结:


 

 Spring整合MyBatis


1.文件的大致格式(与JavaWeb时期相对比):

Spring整合的格式

 

 JavaWeb的格式

2.JdbcConfig(jdbc配置类,加载druid的properties文件)

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

    //1.定义一个方法获取响应的bean
    //2.添加@Bean,表示当前方法的返回值是一个bean
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

3.MybatisConfig(MyBatis配置类,加载JdbcConfig中的dataSource配置信息)

package com.itheima.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,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.itheima.domain");//问实体类的位置
        ssfb.setDataSource(dataSource);//替代的是jdbcConfig中的DataSource,也就是详细配置信息
        return ssfb;
    }
    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");//问映射在什么位置,由于注解完成了执行语句,所以不需要有映射文件
        return msc;
    }
}



4.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;

@Configuration                       //代表了这是个配置类,以此与applicationContext.xml基础配置文件相当
@ComponentScan("com.itheima")
@PropertySource("jdbc.properties")   //加载properties配置文件
@Import({JdbcConfig.class,MybatisConfig.class})            //加载JdbcConfig,MybatisConfig配置类
public class SpringConfig {

}

5.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;

public interface AccountDao {

    @Insert("insert into account(username,password)values(#{username},#{password})")
    void save(Account account);

    @Delete("delete from account where id = #{id} ")
    void delete(Integer id);

    @Update("update account set username = #{username} , password = #{password} where id = #{id} ")
    void update(Account account);

    @Select("select * from account")
    List<Account> findAll();

    @Select("select * from account where id = #{id} ")
    Account findById(Integer id);
}

6.domain(实体类)

package com.itheima.domain;

import java.io.Serializable;

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double 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 Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

7.AccountServiceImpl(Service业务层,组装Dao的操作)

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;
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

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

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

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

    public List<Account> findAll() {
        return accountDao.findAll();
    }
}

8.AccountService(业务层接口)

package com.itheima.service;

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

}

9.App2(main方法  没有控制层)

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;

import java.util.List;

public class App2 {
    public static void main(String[] args) {
        //加载配置类
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        //获取bean
        AccountService accountService = ctx.getBean(AccountService.class);

        //获取方法
        List<Account> all = accountService.findAll();

        //输出值1
        System.out.println(all);
    }
}

10.jdbc.properties(druid的配置信息,被SpringConfig加载,被JdbcConfig所引用)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/db1
jdbc.username=root
jdbc.password=root

11.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>org.example</groupId>
    <artifactId>Spring-demo1-lifeCycle</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
    </properties>

    <dependencies>
        <!--springFramework依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.23</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
<!--        Spring操作数据库有关的都要导这个包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>
<!--        Spring 整合mybtis的包,这个包是和mybatis的包版本是相对应的-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>
</project>

12.自我总结(理清大致思路):

      和JavaWeb中写MyBatis有很大不同,首先就是之前的mybatis-config.xml文件变成了MybatisConfig配置类,mapper文件还是存在的,但是由于注解完成了crud,所以没有必要在进行mapper的建立,另外很好的是,在Service里面也不用写很多代码了,例如SqlSession,在配置文件里面写过之后,只需要在Service实现类里面,引用一下Dao即可,然后在控制层写入Service的代码即可,高效,简单,易懂。

      另外,在pom文件里面也有一个值得注意的问题,就是Spring整合的Mybatis的包与MyBatis的包版本是相对应的,要变一起变,并且只有一对才能使用。否则报错。

Spring整合JUnit


1.文件的大致格式(与整合Mybatis相比增加了一个类,与pom文件里面的依赖)

2.AccountServiceTest类

package com.itheima.service;

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

@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());
    }
}

3.pom.xml文件,增加了JUnit,与Spring-test

<?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>org.example</groupId>
    <artifactId>Spring-demo1-lifeCycle</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
    </properties>

    <dependencies>
        <!--springFramework依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.23</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
<!--        Spring操作数据库有关的都要导这个包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.0.RELEASE</version>
        </dependency>
<!--        Spring 整合mybtis的包,这个包是和mybatis的包版本是相对应的-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
<!--        junit包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
<!--        Spring 操作test的 包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
    </dependencies>
</project>

4.总结:

在设置号依赖于相关的测试类之后,实际上要写的代码并不复杂

 此外

自动装配下AccountService(实际上这个测试类,就是为了测试Service,也可以是Dao层的东西)

想测试谁,就给谁自动给装配

1.junit 常用注解 @Before 初始化方法,每次测试方法调用前都执行一次。 @After 释放资源:每次测试方法调用后都执行一次 @Test 测试方法:在这里可以测试期望异常和超时时间 @ignore 忽略的测试方法 @BeforeClass 针对所有测试,只执行一次,且必须为static void @AfterClass 针对所有测试,只执行一次,且必须为static void @RunWith 指定测试类使用的某个运行器参数SpringJUnit4ClassRunner.class @Parameters 指定参数类的参数数据集合 @Rule 允许灵活添加或重新定义测试类中的每个测试方法的行为 @FixMethodOrder 指定测试方法的执行顺序 @ContextConfiguration 参数locations="classpath:spring-mybatis.xml" 指向src下的该文件 执行顺序: @BeforeClass---@Before---@Test---@After---@Before ---@Test---@After---@AfterClass junit与main方法相比的优势:代码量少、结构清晰、灵活性更好 main:一个类中只能有一个main方0法 层次结构方面不够清晰 运行具体某一个方法时,要将其他的方法注释掉 2.mybatis的基本配置 1.dao层接口 2.mapper.xml:编辑需要执行的sql语句 (1)mapper标签的namespace属性:指定该xml对应的dao层接口的路径 3.spring-mybatis.xml:spring集成mybatils的配置文件 (1)配置sqlSessionFactory指定要操作的数据库,以及mapper.xml的所在目录 (2)配置指定的dao层接口的目录 3.mybatis的注意事项 1.xml中的sql不得有分号 2.sql语句操作的表明和列名 3.xml中的小于号:$lt;大于号¥> 4.取变量时,如果dao层接口使用的是@param("别名")注解,则根据别名取值 5.mapper.xml中$和#取值的区别 4.mybatis的xml中如何设置返回值 resultType返回的数据类型 5.$和#区别 1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #{user_id},如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id". 2. $将传入的数据直接显示生成在sql中。如:order by ${user_id}, 如果传入 的值是id,则解析成的sql为order by id. 3. #方式能够很大程度防止sql注入。 4. $方式无法防止Sql注入。 5. $方式一般用于传入数据库对象,例如传入表名. 6. 一般能用#的就别用$ MyBatis排序时使用order by 动态参数时需要注意,用$而不是#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想给世界留下 1bite 的印象

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值