Spring通过注解整合MyBatis的步骤,共五步

Spring整合MyBatis

先看图,项目包含什么类

Spring通过注解整合MyBatis的步骤,共五步_第1张图片

共五步

一、导包(简单)

**注意,Mybatis包的版本不能错 !!! 这两个包的版本不要换 。 其他的包应该可以选其他版本 =_= **

MyBatis、Spring、Mysql、Junit 。

MyBatis的包

<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.5.6version>
dependency>
<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>1.3.0version>
dependency>

Spring的包

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.2.10.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.2.10.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.2.10.RELEASEversion>
dependency>

数据库相关的包

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.47version>
dependency>
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.16version>
dependency>

Junit的包

<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
dependency>

第一部分完

二、注解配置类(中等)

1. 三个配置类

Spring通过注解整合MyBatis的步骤,共五步_第2张图片

2. 属性文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/userdb?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=123456

SpringConfig类 - 主配置

这个注解是给JdbcConfig类用的:@PropertySource(“jdbc.properties”)

package com.zrh.config;

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

@Configuration
@ComponentScan("com.zrh")
@PropertySource("jdbc.properties") // 引用属性文件
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}

JdbcConfig类

类的属性上用到了注解:@Value(“${jdbc.driver}”),意思是引用了属性文件中的值

package com.zrh.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 dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

MybatisConfig类

package com.zrh.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.zrh.domain");
        ssfb.setDataSource(dataSource);
        return ssfb; // 注意不要写成 return null;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.zrh.dao");
        return msc;
    }
}

第二部分完

三、创建表和实体类(简单)

创建表 - 图

在MySQL中创建表,并写上一两个记录。

表结构
Spring通过注解整合MyBatis的步骤,共五步_第3张图片

表记录
Spring通过注解整合MyBatis的步骤,共五步_第4张图片

创建实体类 - 图文

实体类属性要对应表的每个字段

package com.zrh.domain;

public class Account {

    Integer id;
    String name;
    Integer 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;
    }

    public Account(Integer id, String name, Integer money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }

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

第三部分完

四、数据层和业务层(中等)

数据层

Dao层只需要一个接口,它的五个方法,通过注解实现

package com.zrh.dao;

import com.zrh.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 table_account(name,money)values(#{name},#{money})")
    void save(Account account);

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

    @Update("update table_account set name = #{name}, money = #{money} where id = #{id}")
    void update(Account account);

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

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

业务层

接口
package com.zrh.service;

import com.zrh.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);
}
接口实现类
package com.zrh.service.impl;

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

import java.util.List;

@Service("accountService") //写不写Bean的名字无所谓
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

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

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

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

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

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

第四部分完

五、APP程序类(简单)

写完这个可以运行了。

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

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

        AccountService accountService = ctx.getBean(AccountService.class);
        Account ac = accountService.findById(2);
        System.out.println(ac);
    }
}

Spring注解整合MyBatis的全部步骤,完成

文章能帮到你就太好了 !!! 请帮我点个赞,谢谢~~~

拓展

测试类(简单)

用来测试业务层方法

package com.zrh.service;

import com.zrh.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)
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

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

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

你可能感兴趣的:(mybatis,spring,java)