spring整合mybatis (xml方式)

spring整合mybatis(xml方式)

1.引入maven坐标
<?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>
        <!-- druid依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</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.数据库连接配置

在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文件

<?xml version="1.0" encoding="UTF-8"?>
<!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配置
<?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>
    <!--配置mybatis日志等级为标准输出-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--自定义别名-->
    <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\ttc\dao\AccountMapper.xml"/>-->
        <!--package注册指定包下的所有 mapper 接口-->
        <!--<package name="com.ttc.dao"></package>-->
        <!--会找到dao接口和对应的dao映射配置文件userDao.xml-->
        <mapper resource="AccountMapper.xml"></mapper>
        <!--扫描单个文件在src/main/resources目录内-->
    
    </mappers>

</configuration>

TODO:
1.Mapper代理文件即此处的AccountMapper.xml文件需要AccountMapper.java文件同名才能实现代理
2. <mapper resource="AccountMapper.xml"></mapper>,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 注解方式

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值