Spring整合Mybatis

首先我们复习一下Mybatis想要运行需要进行哪些配置?

0、创建一个表导入数据

1、在maven中加入Mybatis所需要的依赖,此处的依赖我们至少需要mybatis依赖和mysql依赖

2、配置jdbc连接信息以及mapper映射代理路径

3、编写接口以及对应的xml配置文件,或在接口中使用注解进行sql语句的编写。

4、创建sqlsession工厂对象,生成session对象,用session对象生成mapper代理,用mapper代理调用方法。

Spring是如何进行整合的呢?

0、添加maven依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.20</version>
        </dependency>

        <dependency>
            <groupId>io.github.linceln</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.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>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>

1、创建SpringConfig配置类,设置bean的扫描范围,导入properties配置文件,引入其他的配置类。

@Configuration
@ComponentScan("com.tsj")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {

}

2、创建JdbcConfig配置类,用来配置连接数据库的基本信息

这里我们采用了properties文件的方法以防止硬编码,同时@Value注解对基础数据类型进行注入。

随后我们创建了一个dataSouce引用数据类型,来管理第三方bean,通过set方法进行数据初始化。

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 DataSource dataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(userName);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}

3、创建Mybatis配置类

此处我们使用了Spring给我们准备好的两个bean。通过创建方法创建bean对象并对其进行数据初始化。

SqlSessionFactoryBean:

0、创建对象

1、设置包扫描范围,这样在这个包里面的数据类型可以不用写其全类名

2、通过形参自动装配的方法,将我们先前创建的dataSource创建并赋值。

3、返回bean

MapperScanneConfigurer:

0、创建对象

1、设置mapper映射路径(去哪里寻找待执行的sql语句)

2、返回bean

public class MybatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        //此bean是Spring中对mybatis专门实现做的,用来创建session工厂对象
        //我们需要对其进行初始化
        SqlSessionFactoryBean ssb=new SqlSessionFactoryBean();
        //设置包扫描起别名,从此这个包下的类引用时只需要写他的名字,而不是一连串从com开始写
         ssb.setTypeAliasesPackage("com.tsj.domain");
         //有关连接服务器的配置,比如说url,用户名,密码等
        // Spring给引用数据类型注入,注解开发中只要在bean类中提供形参,Spring会自动装配
         ssb.setDataSource(dataSource);

         return ssb;
    }
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc=new MapperScannerConfigurer();
        //相当于xml中存放Mysql语句的接口
        msc.setBasePackage("com.tsj.dao");
        return msc;
    }
}

 4、创建dao和daomin

dao层,用来与数据库CRUD操作

@Component
public interface AccountDao {

    //此处是Mybatis注解开发模式,另外一种是在对应的xml文件中写语句
    @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);
}

daomin,一个javabean类用于创建对象 

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 +
                '}';
    }
}

5、创建Service层

创建接口书写Service中所需要的方法。

public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}

创建Impl包,在包下创建接口的实现类

使用@AutoWired注解自动注入对象获取dao对象

随后对方法进行编写 

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

6、创建APP

通过ApplicationContext创建bean工厂,随后通过getbean方法获取Service的对象。

使用Service对象调用其中的方法完成Mybatis基础开发。

public class APP {
    public static void main(String[] args) {
        ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = ctx.getBean(AccountService.class);
        Account account = accountService.findById(1);
        System.out.println(account);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值