spring快速连接mybatis

Posted 内部静态类

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring快速连接mybatis相关的知识,希望对你有一定的参考价值。

spring快速连接mybatis

spring整合mybatis

1.maven依赖配置

配置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.ttc</groupId>
    <artifactId>springdemo1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!--导入spring依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
        <!--jdbc驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- MyBatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--Spring整合mybatis的依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
    </dependencies>


    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

2.数据库sql设计

-- 创建tbl_account
CREATE TABLE `tbl_account` (
  `id` int NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `money` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
-- 录入数据
INSERT INTO `boot`.`tbl_account` (`id`, `name`, `money`) VALUES ('1', 'Tom', '1000');
INSERT INTO `boot`.`tbl_account` (`id`, `name`, `money`) VALUES ('2', 'Jerry', '500');

3.数据库连接配置

在/src/main/resources 目录下新建druid.properties文件存放数据库练接配置

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

4.实体类设计

package com.ttc.entity;

public class Account 
    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.Dao层开发

package com.ttc.dao;

import com.ttc.entity.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

public interface AccountDao 
    /**
     * 根据id查询单个账户信息
     * @param id
     * @return
     */
    @Select("select id,name,money from tbl_account where id = #id")
    Account findById(Integer id);

    /**
     * 添加单个账户
     * @param account
     */
    @Insert("insert into tbl_account(id,name,money) value(#id,#name,#money)")
    void save(Account account);

6.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>
    <!--dateSource配置-->
    <properties resource="druid.properties"></properties>
    <!--自定义别名-->
    <typeAliases>
        <!--单个别名定义-->
        <!-- <typeAlias type="com.ttc.entity.Account" alias="account"></typeAlias>-->
        <!--批量别名定义,扫描包下的类,别名为类名(首字母大写或者小写都可以)-->
        <package name="com.ttc.entity"></package>
    </typeAliases>
    <!--配置环境与下面对应-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置链接数据库信息:用的是数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="$driver"/>
                <property name="url" value="$url"/>
                <property name="username" value="$username"/>
                <property name="password" value="$password"/>
            </dataSource>
        </environment>
    </environments>
    <!--告知mybatis映射配置的位置-->
    <mappers>
        <!--<mapper resource="com\\yg\\dao\\IUserDao.xml"/>-->
        <!--package注册指定包下的所有 mapper 接口-->
        <package name="com.ttc.dao"></package>
        <!--会找到dao接口和对应的dao映射配置文件userdao.xml-->
    </mappers>
</configuration>

7.运行程序进行crud

import com.ttc.dao.AccountDao;
import com.ttc.entity.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对象执行sql语句,获得结果
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        Account ac = accountDao.findById(1);
        System.out.println(ac);
        // new 一个Account对象添加到数据库中
        Account account = new Account();
        account.setId(3);
        account.setName("我是兔兔小淘气");
        account.setMoney(2000.0);
        // 添加账户
        accountDao.save(account);
        // 增删改操作需提交事务
        sqlSession.commit();
        Account ac3 = accountDao.findById(3);
        System.out.println(ac3);
//        6.释放SqlSession
        sqlSession.close();
    


以上是关于spring快速连接mybatis的主要内容,如果未能解决你的问题,请参考以下文章

spring整合MyBatis思路

MybatisMybatis入门——Mybatis简介

MyBatisMyBatis分页插件Pagehelper

MybatisMyBatis之配置自定义数据源

SSM整合(springMVC+mybatis)

spring快速连接mybatis