当前位置: 首页 > news >正文

ssm框架之mybatis框架搭建

第一步 引入依赖

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- mybatis mysql相关依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
    </dependency>

第二步 编写配置文件

最终目录如下:
在这里插入图片描述
我们要编写mybatis-config.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>
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <typeAliases>
        <package name="com.dts.entity" />
    </typeAliases>
    <!-- 配置mybatis运行环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- MySQL数据库驱动 -->
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <!-- 连接数据库的URL -->
                <property name="url"
                          value="jdbc:mysql://localhost:3306/cdes?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true&amp;serverTimezone=Asia/Shanghai" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
    <mappers>
        <mapper resource="mapper/WebsiteMapper.xml" />
    </mappers>

</configuration>

然后编写log4j.properties,内容如下

# Global logging configuration
log4j.rootLogger=ERROR,stdout
# MyBatis logging configuration...
log4j.logger.com.dts=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

第三步 编写实体类 mapper 和sql脚本

package com.dts.entity;

import java.util.Date;

public class Website {
    private int id;
    private String name;
    private String url;
    private int age;
    private String country;
    private Date createtime;

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "id" + id + "name" + name + "url" + url + "age" + age + "country" + country + "createtime" + createtime;
    }
}
package com.dts.mapper;

import com.dts.entity.Website;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface WebsiteMapper {

    void addWebsite(Website website);

    List<Website> selectAllWebsite();

    @Select("select * from website where id = #{id}")
    Website findById(Integer id);

    List<Website> selectByIds(List<Integer> ids);

    List<Website> selectByCondition(Website website);

    void updateWebsite(Website website);

    void deleteWebsite(Integer id);

    void deleteWebsiteByIds(List<Integer> ids);

}

<?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.dts.mapper.WebsiteMapper">

    <!-- 添加一个网站 -->
    <insert id="addWebsite" parameterType="com.dts.entity.Website">
        insert into website
        (name,url,age,country)
        values(#{name},#{url},#{age},#{country})
    </insert>

    <!-- 查询所有网站信息 -->
    <select id="selectAllWebsite"
            resultType="com.dts.entity.Website">
        select * from website
    </select>

    <select id="selectByIds" resultType="com.dts.entity.Website">
        select * from website where id in
        <foreach collection="list" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

    <select id="selectByCondition" resultType="com.dts.entity.Website">
        select * from website
        <where>
            <if test="name != null and name != ''">
                and name like concat('%',#{name},'%')
            </if>
            <if test="country != null and country != ''">
                and country like concat('%',#{country},'%')
            </if>
            <if test="age != null and age != ''">
                and age = #{age}
            </if>
        </where>
    </select>

    <update id="updateWebsite">
        update website
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="url != null and url != ''">
                url = #{url},
            </if>
            <if test="age != null and age != ''">
                age = #{age},
            </if>
            <if test="country != null and country != ''">
                country = #{country},
            </if>
        </set>
        where id = #{id}
    </update>

    <delete id="deleteWebsite">
        delete from website where id = #{id}
    </delete>

    <delete id="deleteWebsiteByIds">
        delete from website where id in
        <foreach collection="list" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>
</mapper>

最后 编写test方法

package com.dts;

import com.dts.entity.Website;
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.InputStream;
import java.util.List;

public class MybatisTest {

    public static void main(String[] args)throws Exception {
        test1();
    }
    
    public static void test1() throws Exception {
        // 读取配置文件mybatis-config.xml
        InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
        // 根据配置文件构建SqlSessionFactory
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
        // 通过SqlSessionFactory创建SqlSession
        SqlSession ss = ssf.openSession();
        ss.getConnection().setAutoCommit(false);
        // SqlSession执行文件中定义的SQL,并返回映射结果
        // 添加网站
        Website website = new Website();
        website.setName("编程帮");
        website.setUrl("https://www.cainiaoplus.com/");
        website.setAge(21);
        website.setCountry("CN");
        ss.insert("com.dts.mapper.WebsiteMapper.addWebsite", website);
        //这种方式
//        WebsiteMapper mapper = ss.getMapper(WebsiteMapper.class);
//        mapper.addWebsite(website);

        // 查询所有网站
        List<Website> listWeb = ss.selectList("com.dts.mapper.WebsiteMapper.selectAllWebsite");
        for (Website site : listWeb) {
            System.out.println(site);
        }
        // 提交事务
        ss.commit();
        // 关闭 SqlSession
        ss.close();
    }

}

经过以上步骤,mybatis框架就算搭建完成了。最终项目结构如下
在这里插入图片描述

http://www.dtcms.com/a/75560.html

相关文章:

  • 牛客周赛 Round 85(DE)
  • 蓝桥杯备赛(基础语法4)
  • Shell 脚本中的 `read` 命令:灵活处理用户输入
  • 20. Excel 自动化:Excel 对象模型
  • 【NeurIPS-2022】CodeFormer: 将人脸复原转化为码本预测以减少LQ-HQ映射的不确定性
  • 基于ssm学科竞赛小程序的设计及实现(源码+lw+部署文档+讲解),源码可白嫖!
  • 使用Flux查询数据
  • (6)用于无GPS导航的Nooploop
  • [原创](Modern C++)现代C++的关键性概念: 灵活多变的绑定: std::bind
  • 化学工业领域 - 石油化工、高分子化工、生物化工极简理解
  • 软考 中级软件设计师 考点知识点笔记总结 day05
  • E1-数组的平衡点2(前缀和)
  • .[OnlyBuy@cyberfear.com].REVRAC勒索mysql恢复---惜分飞
  • 基于 ELK、Python、OLaMA 和飞书群的 AI 自动化巡检方案
  • 25. K 个一组翻转链表(C++)
  • 微服务面试题:远程调用
  • 注解与设计模式:解锁Java编程的魔法与艺术!
  • mac npm run dev报错 error:0308010C:digital envelope routines::unsupported
  • Redis基础:命令行操作实践指南
  • QML与C++交互
  • Flink读取Kafka数据写入IceBerg(HiveCatalog)
  • 汽车一键启动系统使用方便,舒适出行,轻松匹配
  • Java 中线程废弃方法(stop、suspend、resume)原因及替代方案
  • 2025年春季学期《算法分析与设计》练习4
  • 碰一碰发视频saas系统技术源头一站式开发文档
  • Tomcat虚拟主机配置详解:Centos环境下多域名部署(详细教程!)
  • 输入输出 数组 冒泡排序举例
  • 基于Spring Boot的大学校园生活信息平台的设计与实现(LW+源码+讲解)
  • 机器学习之支持向量机(SVM)算法详解
  • docker 的volumes如何清理