【三:Spring整合Mybatis】

目录

  • Spring整合Mybatis(基于xml文件)
    • 1 、项目的大体框架
      • 前期准备
        • 1.2 、使用Navicat在数据库中创建一张表account
        • 1.3、 在pom.xml文件中加入maven(依赖的配置)
        • 1.4、配置相应的数据库连接,以及扫描相应的dao层
      • 编写实体类Account
      • 编写Dao层对应操作
      • 其他文件(没有用到)
        • SpringConfig
        • AccountServiceImpl
      • 测试
  • 2、Spring整合Mybatis(基于注解文件)
    • 1 、项目的大体框架
      • 前期准备(和xml一致的)
        • 配置类(config)
        • 数据层(dao)
        • 实体层(domain)
        • 服务层(service)
        • 测试

Spring整合Mybatis(基于xml文件)

1 、项目的大体框架

【三:Spring整合Mybatis】_第1张图片

前期准备

1.2 、使用Navicat在数据库中创建一张表account

【三:Spring整合Mybatis】_第2张图片

1.3、 在pom.xml文件中加入maven(依赖的配置)

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-contextartifactId>
  <version>5.2.5.RELEASEversion>
dependency>

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-txartifactId>
  <version>5.2.5.RELEASEversion>
dependency>
<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-jdbcartifactId>
  <version>5.2.5.RELEASEversion>
dependency>

<dependency>
  <groupId>org.mybatisgroupId>
  <artifactId>mybatisartifactId>
  <version>3.5.1version>
dependency>

<dependency>
  <groupId>org.mybatisgroupId>
  <artifactId>mybatis-springartifactId>
  <version>1.3.1version>
dependency>

<dependency>
  <groupId>mysqlgroupId>
  <artifactId>mysql-connector-javaartifactId>
  <version>5.1.9version>
dependency>

<dependency>
  <groupId>com.alibabagroupId>
  <artifactId>druidartifactId>
  <version>1.1.12version>
dependency>

<dependency>
  <groupId>junitgroupId>
  <artifactId>junitartifactId>
  <version>4.11version>
  <scope>testscope>
dependency>
<build>
    <resources>
      <resource>
        <directory>src/main/javadirectory> 
        <includes> 
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
    resources>
 build>

1.4、配置相应的数据库连接,以及扫描相应的dao层

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties resource="jdbc.properties">properties>
    <typeAliases>
        <package name="com.xiong.domain"/>
    typeAliases>
    
    <environments default="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>

    
    <mappers>
        <package name="com.xiong.dao"/>
    mappers>
configuration>

配置数据库连接的配置文件:jdbc.properties

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

编写实体类Account

package com.xiong.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 +
                '}';
    }
}

编写Dao层对应操作

package com.xiong.dao;

import com.xiong.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface AccountDao {

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

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

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

其他文件(没有用到)

SpringConfig
package com.xiong.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
 * 如果不配置扫描就行报错  可以使用
 */
@Configuration  //设定当前类为配置类
@ComponentScan({"com.xiong.service.impl"})  //用于设置注解扫描路径,次注解只能添加一次
public class SpringConfig {

    // 表示当前返回值是一个bean
}

AccountServiceImpl
package com.xiong.service.impl;

import com.xiong.service.AccountService;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl implements AccountService {
    @Override
    public void saves() {
        System.out.println("11111");
    }
}

测试

package com.xiong;
import com.xiong.dao.AccountDao;
import com.xiong.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;

public class App {

    public static void main(String[] args) throws IOException {


        //1、创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();

        //2、加载SqlMapConfig.xml配置
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");

        //3、创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory =sqlSessionFactoryBuilder.build(inputStream);

        //4、加载SqlSession
        SqlSession sqlSession=sqlSessionFactory.openSession();

        //5、执行SqlSession对象执行查询,获取结果
        AccountDao accountDao=sqlSession.getMapper(AccountDao.class);
        Account ac=accountDao.findByID(1);
        System.out.println(ac);

        //6、释放资源
        sqlSession.close();

    }
}

结果
【三:Spring整合Mybatis】_第3张图片

2、Spring整合Mybatis(基于注解文件)

1 、项目的大体框架

【三:Spring整合Mybatis】_第4张图片

前期准备(和xml一致的)

配置类(config)

jdbcConfig

package com.xiong.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 {
    /**
     * jdbc.driver=com.mysql.jdbc.Driver
     * jdbc.url=jdbc:mysql://localhost:3306/eesy_mybatis
     * jdbc.username=root
     * jdbc.password=123456
     */
    @Value("com.mysql.jdbc.Driver")
    private  String driver;

    @Value("jdbc:mysql://localhost:3306/eesy_mybatis")
    private  String url;

    @Value("root")
    private  String userName;

    @Value("123456")
    private  String password;

    /**
     * s实现第三bean注入资源
     * @return
     */
    @Bean
    public DataSource dataSource(){
        DruidDataSource ds=new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}

MybatiesConfig

package com.xiong.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
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sfb=new SqlSessionFactoryBean();
        sfb.setTypeAliasesPackage("com.xiong.domain");
        sfb.setDataSource(dataSource);
        return sfb;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerRegistrar(){
        MapperScannerConfigurer msc=new MapperScannerConfigurer();
        msc.setBasePackage("com.xiong.dao");
        return msc;

    }
}

SpringConfig

package com.xiong.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  //设定当前类为配置类
@ComponentScan({"com.xiong"})  //用于设置注解扫描路径,次注解只能添加一次
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatiesConfig.class})
public class SpringConfig {

    // 表示当前返回值是一个bean

}

数据层(dao)
package com.xiong.dao;

import com.xiong.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface AccountDao {

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

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

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

实体层(domain)
package com.xiong.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 +
                '}';
    }
}

服务层(service)
  • 实现(imp)
package com.xiong.service.impl;

import com.xiong.dao.AccountDao;
import com.xiong.domain.Account;
import com.xiong.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);
    }

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

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

  • 接口(interfa)
package com.xiong.service;

import com.xiong.domain.Account;

import java.util.List;

public interface AccountService {

    void save(Account account);

    Account findById(Integer id);

    List<Account> findAll();


}

测试
package com.xiong;

import com.xiong.config.SpringConfig;
import com.xiong.domain.Account;
import com.xiong.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】_第5张图片

你可能感兴趣的:(SSM+Spring,boot,spring,mybatis,java)