关于Mybatis与mysql交互的1点小基础

  • 内容
  • 评论
  • 相关

关于Mybatis与mysql交互的一点小基础.
      现在做开发都离不开与数据库打交道,在我们现在的J2EE开发中与数据库有交互的框架数hibernate用的最多了,但是也有不少的朋友用Mybatis(以前叫Ibatis).它们都是优秀的O/R mapping框架.

      哪他们的区别主要在什么地方呢?只是两者的官方网站,上面都有介绍我就不多累述了.

                     Hibernate参考资料: http://docs.jboss.org/hibernate/core/3.6/reference/zh-CN/html_single/

                     MyBatis 参考资料官网:http://www.mybatis.org/core/zh/index.html

下面是个人做的Mybatis的一些代码,供给基础薄弱,的朋友参考.如有什么不正确的地方请多多包涵,毕竟是我的处女文章.

声明:本人还是草根阶级,所以用的开发工具基本上都是免费的,个别工具是收费的,不过来到我们中国就不知不觉的免费了...

一下是本次开发所用的工具:

          *  mysql 5.6

          * intellij Idea 31.01

          * Mybatis 的jar包

          * mysql的jar包

          以上所需的两个jar包我上传到csdn上了的,不需要的积分,地址是:

http://download.csdn.net/download/nanguojisi/6820561

 

       OK,我们开始吧!

1.先创建一个名为blog数据库

create database bbs;

再创建名为t_blog的表  如下:

CREATE TABLE t_blog (
id  int NOT NULL AUTO_INCREMENT ,
content  varchar(500) NULL ,
doc  varchar(500) NULL ,
title  varchar(50) NULL ,
PRIMARY KEY (id)
)
;

2.创建一个名为Blog.java的javabean

package cn.it.beans;

/**
* Created by Mr_Huang on 14-1-7.
*/
public class Blog {
    private int id;
    private String title;
    private String content;
    private String doc;

    public Blog() {
    }

    public Blog(String title, String content, String doc) {
        this.title = title;
        this.content = content;
        this.doc = doc;
    }

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

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

    public String getDoc() {
        return doc;
    }

    public void setDoc(String doc) {
        this.doc = doc;
    }
}

3.先写一个连接数据库的  .properties文件,再写一个Mybatis.xml的文件两个文件都在src的根目录(为了方便建议都放在src的根目录,也可以放于其他目录).

  (1).jdbc_config.properties  文件内容如下:

db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://127.0.0.1:3306/bbs?useUnicode=true&characterEncoding=utf8
db.username = 你的数据库用户名
db.password = 数据库密码

注意在每行的末尾不能有空格.

(2).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>
        <!--第一步引进properties文件路径-->
            <properties resource="jdbc_config.properties"></properties>
<!--这了只是在学改别名-->
    <typeAliases>
        <typeAlias type="cn.it.beans.Blog" alias="Blog"/>
    </typeAliases>

        <!--第二步,配置environments-->
            <environments default="development">
                <environment id="development">
                    <transactionManager type="JDBC"></transactionManager>      <!--transactionManager事务管理器-->
                    <dataSource type="POOLED">

                        <!--第三步,配置  property-->
                        <property name="driver" value="${db.driver}"/>
                        <property name="url" value="${db.url}"/>
                        <property name="username" value="${db.username}"/>
                        <property name="password" value="${db.password}"/>
                    </dataSource>
                </environment>
            </environments>
    <mappers>
        <mapper resource="cn/it/beans/BlogMapper.xml"></mapper>
    </mappers>
        </configuration>

4.创建一个BlogMapper.xml的文件,放在Blog.java同一个包里(也是问了一一对应起来方便):

BlogMapper.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="cn.it.beans.Blog">

    <!--实现插入一条语句-->
      <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true">
          insert into t_blog (title, content, doc) values (#{title}, #{content},#{doc});
      </insert>

    <!--查询语句-->
    <select id="selectBlog" parameterType="int" resultType="Blog">
        select * from t_blog where id = #{id}
    </select>
   
    <!--删除语句-->
    <delete id="deleteBlog" parameterType="int" >
        delete from t_blog where id = #{id}
    </delete>
   
    <!--查询所有-->
    <select id="selectAll" resultType="Blog">
        select * from t_blog
    </select>
   
    <!--更新数据-->
    <update id="updateBlog" parameterType="Blog">
        update t_blog set title = #{title}, content = #{content}, doc = #{doc} where id = #{id}
    </update>
   
    <!--模糊查询-->
    <select id="selectDim" parameterType="java.lang.String" resultType="Blog">
        select * from t_blog where title like "%"#{title}"%"
    </select>
    </mapper>

5.这是最后一步,创建一个测试类(我个人习惯用IDEA了,很方便.如有对IDEA感兴趣者可与我联系交流):

TestIbatis.java

package cn.it.test.mybatis;

import cn.it.beans.Blog;
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 org.junit.Test;

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

/**
* Created by Mr_Huang on 14-1-7.
* 用于测试Mybatis与数据库是否交互成功
*/
public class TestIbatis {

    /**
     * 测试插入一条语句是否成功
     */
    @Test
    public void testInser(){

        String resource = "Mybatis.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            Blog blog1 = new Blog("半厘米阳光1","半厘米阳光半厘米阳光半厘米阳光半厘米阳光半厘米阳光","半厘米阳光");
            Blog blog2 = new Blog("半厘米阳光3","半厘米阳光半厘米阳光半厘米阳光半厘米阳光","半厘米阳光");
            Blog blog3 = new Blog("半厘米阳光4","半厘米阳光半厘米阳光半厘米阳光","半厘米阳光");
            session.insert("cn.it.beans.Blog.insertBlog",blog1);//插入对象
            session.insert("cn.it.beans.Blog.insertBlog",blog2);//插入对象
            session.insert("cn.it.beans.Blog.insertBlog",blog3);//插入对象
            session.commit();//提交事务
            session.close();//关闭session
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试查询语句
     */
    @Test
    public void testSelect(){

        try {
            InputStream inputStream = Resources.getResourceAsStream("Mybatis.xml");//读取数据库连接文件
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            Blog blog = session.selectOne("cn.it.beans.Blog.selectBlog",1);
            System.out.println(blog.getContent());

            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试删除语句
     */
    @Test
    public void testDelete(){
        try {
            InputStream inputStream = Resources.getResourceAsStream("Mybatis.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            session.delete("cn.it.beans.Blog.deleteBlog",2);
            session.commit();
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试查询所有语句
     */
    @Test
    public void testSelectAll(){
        try {
            InputStream inputStream = Resources.getResourceAsStream("Mybatis.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            List<Blog> blogs = session.selectList("cn.it.beans.Blog.selectAll");

            //循环遍历每一个的值
            for (Blog blog:blogs){
                System.out.println(blog.getTitle());
            }
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试更新数据
     */
    @Test
    public void testUpdate(){

        try {
            InputStream inputStream = Resources.getResourceAsStream("Mybatis.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            Blog blog = new Blog("重庆","沙坪坝区西永镇","半厘米阳光");
            blog.setId(1);
            session.update("cn.it.beans.Blog.updateBlog",blog);
            session.commit();
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试模糊查询
     */
    @Test
    public void testSelectDim(){
        try {
            InputStream inputStream = Resources.getResourceAsStream("Mybatis.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            List<Blog> blogs = session.selectList("cn.it.beans.Blog.selectDim","热");

            for(Blog blog:blogs){
                System.out.println(blog.getContent());
            }
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

大体内容就是以上这些了.有话好好说.望不满者勿喷为谢!!!

原创文章,转载请注明: 转载自搞代码

本文链接地址: 关于Mybatis与mysql交互的1点小基础

微信支付二维码

微信 赏一包辣条吧~

支付宝支付二维码

支付宝 赏一听可乐吧~

评论

0条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注