spring整合mybatis (xml方式)

文章目录

      • spring整合mybatis(xml方式)
        • 1.引入maven坐标
        • 2.数据库连接配置
        • 3.实体类设计
        • 4.dao层Mapper设计
        • 5.建立AccountMapper.xml
        • 6.sqlMapperConfig配置
        • 7.运行程序进行crud
        • 8.查看日志
        • 9.文末有彩蛋哦

spring整合mybatis(xml方式)

1.引入maven坐标


<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>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.12version>
        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.数据库连接配置

在src/main/resources目录新建druid.properties

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

3.实体类设计

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

4.dao层Mapper设计

dao层新建 AccountMapper.java

package com.ttc.dao;

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


public interface AccountMapper {
    /**
     * 根据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);

    /**
     * 根据id查询账户信息采用mapper代理方式
     *
     * @return
     */
    Account getById(Integer id);
}

5.建立AccountMapper.xml

在src/main/resources目录下新建AccountMapper.xml文件


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ttc.dao.AccountMapper">  

    <resultMap id="accountMap" type="com.ttc.entity.Account">
        <id column="id" property="id">id>
        <result column="name" property="name">result>
        <result column="money" property="money">result>
    resultMap>

    <select id="getById" resultMap="accountMap" parameterType="java.lang.Integer">
        select id, name, money
        from tbl_account
        where id = #{id};
    select>

mapper>

6.sqlMapperConfig配置


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

    
    <properties resource="druid.properties">properties>
    
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
    <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>
        
        
        
        
        <mapper resource="AccountMapper.xml">mapper>
        
    
    mappers>

configuration>

TODO:
1.Mapper代理文件即此处的AccountMapper.xml文件需要AccountMapper.java文件同名才能实现代理
2. ,maven项目,默认从src/main/resources目录寻找xml文件

7.运行程序进行crud

import com.ttc.dao.AccountMapper;
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语句,获得结果
        AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
        Account ac = accountMapper.findById(1);
        System.out.println(ac);
        // new 一个Account对象添加到数据库中
        Account account = new Account();
        account.setId(6);
        account.setName("喜羊羊与灰太狼");
        account.setMoney(2000.0);
        // 添加账户
        accountMapper.save(account);
        // 增删改操作需提交事务
        sqlSession.commit();
        Account ac3 = accountMapper.findById(5);
        System.out.println(ac3);
        System.out.println(accountMapper.getById(3));
//        6.释放SqlSession
        sqlSession.close();
    }
}

8.查看日志

运行日志如下:

Checking to see if class com.ttc.entity.Account matches criteria [is assignable to Object]
Checking to see if class com.ttc.entity.Student matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 811301908.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@305b7c14]
==>  Preparing: select id,name,money from tbl_account where id = ?
==> Parameters: 1(Integer)
<==    Columns: id, name, money
<==        Row: 1, Tom, 1000
<==      Total: 1
Account{id=1, name='Tom', money=1000.0}
==>  Preparing: insert into tbl_account(id,name,money) value(?,?,?)
==> Parameters: 6(Integer), 喜羊羊与灰太狼(String), 2000.0(Double)
<==    Updates: 1
Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@305b7c14]
==>  Preparing: select id,name,money from tbl_account where id = ?
==> Parameters: 5(Integer)
<==    Columns: id, name, money
<==        Row: 5, 懒羊羊与灰太狼, 2000
<==      Total: 1
Account{id=5, name='懒羊羊与灰太狼', money=2000.0}
==>  Preparing: select id, name, money from tbl_account where id = ?;
==> Parameters: 3(Integer)
<==    Columns: id, name, money
<==        Row: 3, 我是兔兔小淘气, 2000
<==      Total: 1
Account{id=3, name='我是兔兔小淘气', money=2000.0}
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@305b7c14]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@305b7c14]
Returned connection 811301908 to pool.

Process finished with exit code 0

9.文末有彩蛋哦

spring整合mybatis 注解方式

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