spring快速连接mybatis

spring快速连接mybatis

      • spring整合mybatis
        • 1.maven依赖配置
        • 2.数据库sql设计
        • 3.数据库连接配置
        • 4.实体类设计
        • 5.Dao层开发
        • 6.SqlMapConfig.xml
        • 7.运行程序进行crud

spring整合mybatis

1.maven依赖配置

配置pom.xml如下


<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.0modelVersion>

    <groupId>com.ttcgroupId>
    <artifactId>springdemo1artifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>warpackaging>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.10.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.28version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>
    dependencies>


    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.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



<configuration>
    
    <properties resource="druid.properties">properties>
    
    <typeAliases>
        
        
        
        <package name="com.ttc.entity">package>
    typeAliases>
    
    <environments default="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>
    
    <mappers>
        
        
        <package name="com.ttc.dao">package>
        
    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_第1张图片

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