Mybatis笔记一:写一个demo

什么是Mybatis?

在Java中,我们连接数据库可以使用最初级的JDBC,但是这样很麻烦,每次都要写好多,所以Mybatis出现了,Mybatis可以帮我们很简单很简单的实现与数据库的读取改写操作

引入文件

  1. Maven引入一个Mybatis的包
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>
  1. 还需要一个Mybatis的配置文件,可以起名为Mybatis.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>

    <!-- 设置一个默认的连接环境信息 -->
    <environments default="mysql_developer">
        <environment id="mysql_developer">
            <!-- mybatis使用jdbc事务管理方式 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- mybatis使用连接池方式来获取连接 -->
            <dataSource type="POOLED">
                <!-- 配置与数据库交互的4个必要属性,不要直接写,单独写在一个配置文件中 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/shuyunquan?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 加载映射文件-->
    <mappers>
        <mapper resource="config/Message.xml"/>
    </mappers>

</configuration>

这里Mybatis写了连接数据库的几个要素,还有下面的mappers写了我们要加载的类的配置文件,这个我们下面细讲

  1. 类的配置文件
<?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 -->
<mapper namespace="Message">
    <!--
        数据库查询数据
        insert、select、delete、update:sql语句类型
        id:sql语句唯一标识
        resultType:结果返回值类型-包名+类名 或 基本数据类型
        parameterType:匹配字段值-包名+类名 或 基本数据类型
    -->

    <select id="selectListMessage" parameterType="com.vae.springboot.study.bean.Message"  resultType="com.vae.springboot.study.bean.Message">
            select * from message where 1=1
            <if test="command !=null and !&quot;&quot;.equals(command.trim())">and COMMAND =#{command}</if>
            <if test="description !=null and !&quot;&quot;.equals(description.trim())">and DESCRIPTION like '%' #{description} '%'</if>
    </select>


    <select id="selectOneMessage" parameterType="com.vae.springboot.study.bean.Message"  resultType="com.vae.springboot.study.bean.Message">
        select * from message where ID=#{ID}
    </select>
    <!--<insert id="xx1" resultType="xx" parameterType="xxx">-->
            <!--insert into tb(c1) values(#{v1})-->
        <!--</insert>-->

    <delete id="deleteOneMessage" parameterType="com.vae.springboot.study.bean.Message">
            delete from message where ID = #{para}
    </delete>

    <!--<update id="xx3" parameterType="xxx">-->
            <!--update advertis set c1 = v1 where c2 =#{v2};-->
        <!--</update>-->

</mapper>

这个其实,我想取的数据库,对应的字段我建立了一个对应的Java Bean,然后这里xml主要写的是增删改查之类的

看看我的数据库

两个配置文件复制一下,看看我的数据库

看看我的Java Bean

package com.vae.springboot.study.bean;

/**
 * 消息表对应的Java Bean
 */
public class Message {
    private String id;
    private String command;
    private String description;
    private String content;

    public String getId() {
        return id;
    }

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

    public String getCommand() {
        return command;
    }

    public void setCommand(String command) {
        this.command = command;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

看看我的Controller

package com.vae.springboot.study.Controller;

import com.vae.springboot.study.DB.DBAcess;
import com.vae.springboot.study.bean.Message;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 列表页面初始化
 */
@Controller
public class ListController {

    @ResponseBody
    @RequestMapping("/list")
    public List<Message> list(@RequestBody Message message) throws IOException {

        List<Message> list=new ArrayList<>();
        DBAcess dbAcess=new DBAcess();
        SqlSession sqlSession = dbAcess.getSqlSession();
        System.out.println("---------------"+message.getCommand());
        System.out.println("---------------"+message.getDescription());
        try {
            list =sqlSession.selectList("Message.selectListMessage",message);
            return list;
        }finally {
            sqlSession.close();
        }
       
       
    }


    @ResponseBody
    @RequestMapping("/getOne")
    public List<Message> getOne() throws IOException {

        List<Message> list=new ArrayList<>();
        DBAcess dbAcess=new DBAcess();
        SqlSession sqlSession = dbAcess.getSqlSession();
        try {
            list =sqlSession.selectList("Message.selectOneMessage",1);
            System.out.println(list.get(0));
            return list;
        }finally {
            sqlSession.close();
        }

    }


    @ResponseBody
    @RequestMapping("/delete")
    public List<Message> delete(@RequestBody Message message) throws IOException {

        List<Message> list=new ArrayList<>();
        DBAcess dbAcess=new DBAcess();
        SqlSession sqlSession = dbAcess.getSqlSession();
        System.out.println("---------------"+message.getCommand());
        System.out.println("---------------"+message.getDescription());
        try {
            list =sqlSession.selectList("Message.deleteOneMessage",message);
            return list;
        }finally {
            sqlSession.close();
        }

    }

}

由于sqlSessionFactory经常会需要创建,所以我们把创建sqlSessionFactory返回sqlSession封装一下,就叫DBAcess

package com.vae.springboot.study.DB;

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.Reader;

public class DBAcess {

    public SqlSession getSqlSession() throws IOException {
        Reader reader=Resources.getResourceAsReader("config/Mybatis.xml");
        SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

测试类

package com.vae.springboot.study.Controller;

import com.vae.springboot.study.DB.DBAcess;
import com.vae.springboot.study.bean.Message;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ListControllerTest {
    @Test
    public void test() throws IOException {
        List<Message> list=new ArrayList<>();

        DBAcess dbAcess=new DBAcess();
        SqlSession sqlSession = dbAcess.getSqlSession();
        list = sqlSession.selectList("Message.selectListMessage");
        System.out.println(list);
    }


    @Test
    public void getOne() throws IOException {

        List<Message> list=new ArrayList<>();
        DBAcess dbAcess=new DBAcess();
        SqlSession sqlSession = dbAcess.getSqlSession();
        try {
            list =sqlSession.selectList("Message.selectOneMessage",1);
            System.out.println(list.get(0).getId()+list.get(0).getCommand()+list.get(0).getDescription());
        }finally {
            sqlSession.close();
        }

    }
}

我的前端,使用Ajax技术

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE" />
		<title>内容列表页面</title>
		<link href="css/all.css" rel="stylesheet" type="text/css" />
		<script src="js/jquery-1.8.0.min.js"></script>
	</head>
	<body style="background: #e1e9eb;">
		<form action="" id="mainForm" method="post">
			<div class="right">
				<div class="current">当前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">内容管理</a> &gt; 内容列表</div>
				<div class="rightCont">
					<p class="g_title fix">内容列表 <a class="btn03" href="#">新 增</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="btn03" href="#">删 除</a></p>
					<table class="tab1">
						<tbody>
							<tr>
								<td width="90" align="right">指令:</td>
								<td>
									<input type="text" id="command" class="allInput" value=""/>
								</td>
								<td width="90" align="right">描述:</td>
								<td>
									<input type="text" id="description" class="allInput" value=""/>
								</td>
	                            <td width="85" align="right"><input type="button" class="tabSub" onclick="refurbishIndex()" value="查 询" /></td>
	       					</tr>
						</tbody>
					</table>
					<div class="zixun fix">


						<table class="tab2" width="100%">
							<tr>
								<th><input type="checkbox" id="all" onclick="#"/></th>
								<th>id</th>
								<th>指令</th>
								<th>描述</th>
								<th>操作</th>
							</tr>

							<tbody id="tbodydata">

							</tbody>
						</table>


						<div class='page fix'>
							共 <b>4</b> 条
							<a href='###' class='first'>首页</a>
							<a href='###' class='pre'>上一页</a>
							当前第<span>1/1</span>页
							<a href='###' class='next'>下一页</a>
							<a href='###' class='last'>末页</a>
							跳至&nbsp;<input type='text' value='1' class='allInput w28' />&nbsp;页&nbsp;
							<a href='###' class='go'>GO</a>
						</div>
					</div>
				</div>
			</div>
	    </form>
	</body>
</html>

<script type="text/javascript">

    $(function () {
        refurbishIndex();
    })

    function refurbishIndex(){

        var queryData = {
            command : $('#command').val(),
            description : $('#description').val()
        }

        $.ajax({
            type:"post",
            url:"/list",
            data:JSON.stringify(queryData),
            contentType : "application/json",
            success:function (data) {
                var str="";
                for (i in data) {
                    str += "<tr>" +
                        "<td>"+"<input type=\"checkbox\" />"+"</td>"+
                        "<td align='center'>" + data[i].id + "</td>" +
                        "<td align='center'>" + data[i].command + "</td>" +
                        "<td align='center'>" + data[i].description + "</td>" +
                        "<td>\n" +
                        "<a href=\"#\">修改</a>\n" +
                        "<a href=\"#\">删除</a>\n" +
                        "</td>"
                    "</tr>";
                }

                document.getElementById("tbodydata").innerHTML=str;

            }
        });
    }
</script>
posted @ 2019-02-18 23:32  蜀云泉  阅读(1662)  评论(2编辑  收藏  举报