一个完整的Mybatis搭建步骤的一个简单例子

完整内容如下
![

***pom.xm***l

<?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">
    <parent>
        <artifactId>mybatis-study</artifactId>
        <groupId>com.mrZhang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>mybatis-07</artifactId>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

根据数据库内容创建实体类

package com.mrZhang.pojo;


import java.util.Date;

@lombok.Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;//与数据库的命名不一致,可以用驼峰命名法(mapUnderscoreToCamelCase)解决
    private int views;
}

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:核心配置文件-->
<configuration>
<!--引入配置文件-->
    <properties resource="db.properties"/>
<!--  标准的日志工厂的实现  -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
<!--    开启驼峰命名转换    -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
<!--  给实体类取别名  -->
    <typeAliases>
<!--        <typeAlias type="com.User" alias="User"/>-->
        <!--  给实体类取别名,可以直接扫描到包,别名默认为类名的小写(大写也可以)  -->
        <package name="com.mrZhang.pojo"/>
    </typeAliases>



<!--mybatis默认的数据源是JDBC,连接池是:POOLED-->
    <environments default="development">
        <environment id="development">

<!-- transactionManager:事务管理器(两种类型:JDBC|MANAGED)           -->
            <transactionManager type="JDBC"/>

<!--dataSource:数据源(连接数据库),有三种数据源:(POOLED|UNPOOLED|JNDI)-->
            <dataSource type="POOLED">

<!--      通过properties引用配置文件          -->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--  每一个mapper.xml文件都需要在mybatis核心配置文件中注册  -->
<mappers>
    <mapper resource="com/mrZhang/dao/UserMapper.xml"/>
</mappers>
</configuration>

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3307/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

BlogMapper接口

public interface BlogMapper {
    //添加博客
    int addBlog(Blog blog);
    //查询博客信息
    List<Blog> getBlogIf(Map map);

    //查询博客,chose
    List<Blog> queryBlogChoose(Map map);
    //更新博客
    int updateBlog(Map map);
}

UserMapper.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.mrZhang.dao.BlogMapper">
    <insert id="addBlog" >
        insert into mybatis.blog(id, title, author, create_time, views)
        VALUES(#{id},#{title},#{author},#{createTime},#{views})
    </insert>

    <select id="getBlogIf" resultType="blog">
        select * from mybatis.blog where 1=1
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{autjor}
        </if>
    </select>

    <select id="queryBlogChoose" resultType="blog">
    select * from mybatis.blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>
                <when test="author!=null">
                    author=#{author}
                </when>
                <otherwise>
                    views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>

    <update id="updateBlog" >
        update mybatis.blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
        </set>
        where id=#{id}
    </update>
</mapper>

工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){

        return sqlSessionFactory.openSession(true);//自动提交事务true
    }
}

/**
 * 获取随机的id
 */
@SuppressWarnings("all")//印制警告
public class IDUtils {
    public static String getId(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Test
    public void test1(){
        System.out.println(IDUtils.getId());
    }
}

测试类

public class BlogTest {
    @Test
    public void addBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("Mybatis如此简单");
        blog.setAuthor("爱因斯坦");
        blog.setCreateTime(new Date());
        blog.setViews(9999);
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("java也简单");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("Spring也是如此");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("微服务应该也不难");
        mapper.addBlog(blog);

        sqlSession.close();
    }

    @Test
    public void getBlogIf(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title", "Mybatis如此简单");
        List<Blog> blogIf = mapper.getBlogIf(map);
        for (Blog blog : blogIf) {
            System.out.println(blog);
        }
    }

    @Test
    public void queryBlogChoose(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap hashMap = new HashMap();
        hashMap.put("views", "9999");
        hashMap.put("author", "爱因斯坦");
        hashMap.put("title","java也简单");
        List<Blog> blogs = mapper.queryBlogChoose(hashMap);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

    @Test
    public void updateBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","java也简单2");
        map.put("id","f8c4faaa63574520b81513df52180494");
        mapper.updateBlog(map);
        sqlSession.close();
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值