温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

mybatis介绍与环境搭建

发布时间:2020-07-21 01:02:51 来源:网络 阅读:379 作者:xmgdc 栏目:数据库

一、不用纯jdbc的原因,即缺点。

1、数据库理解,使用时创建,不用时释放,会对数据库进行频繁的链接开启和关闭,造成数据库的资源浪费,影响数据库的性能。
设想:使用数据库的连接池。
2、将sql语句硬编码到java代码中,不利于系统维护。
设想:将sql放到配置文件中。
3、向preparedstatement中设置参数,对占位符位置和设置参数值,硬编码在Java代码中,不利于系统维护。
设想:将sql语句及占位符配置到xml中。
4、从resultset中便利结果集时,存在硬编码,将获取表的字段进行硬编码,不利于系统维护。
设想;将结果集,自动映射成Java对象

二、mybatis是什么

1、mybatis让程序员将主要精力放在sql上,通过mybatis提供的映射方式,自由灵活生成满足需要的sql语句。
2、mybatis可以将输入参数自动映射,可以将结果集映射为Java对象,并且sql相对自由,不想hibernate那样看不到sql。
3、mybatis需要一个SqlMapConfig.xml,它是mybatis的全局配置文件,其中包括了数据库连接池,配置了数据源、事务等。
4、还需要一个SQLMap配置文件,它配置了映射关系(配置sql语句),sql语句要写在这个配置文件里,其实就是配置了一个statement,避免了sql语句硬编码到Java源文件中。后面会详细介绍这个配置文件的使用。
5、SqlsessionFactory是mybatis中生成Sqlsession的工厂,操作数据库。
mybatis框架结构是把sql语句的映射文件加载到SQLMapConfig中去,然后SqlSessionFactory加载SQLMapConfig后生成SQLSession,SQLSession来执行Statement。

三、构建一个mybatis工程。

1.所需要的jar包

mybatis介绍与环境搭建

即需要下载mybatis包和数据库驱动包,可以从GitHub上下载mybatis,解压后里面有lib文件夹和一个mybatis的核心包,lib中得包是mybatis的依赖包

mybatis的下载

2.工程结构。

mybatis介绍与环境搭建

src中放源码,lib中放所依赖的jar包,config中放各种配置文件,config文件下的sqlmap包中放sql映射文件。lib和config文件夹创建好后要记得邮件选择build path->use a source folder

 3.编写log4j.properties

mybatis介绍与环境搭建

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 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

mybatis介绍与环境搭建

 

 注意:开发时log4j.rootLogger=DEBUG,生产环境可以把DEBUG换成info

4.编写SqlMapConfig.xml

 

mybatis介绍与环境搭建

<?xml version="1.0" encoding="UTF-8" ?>   
    <!DOCTYPE configuration
     PUBLIC "-//mybatis.org//DTD Confi 3.0//EN"
    "http://www.mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>            
        <environments default="development">  
            <environment id="development">  
                <transactionManager type="JDBC" />  
                <dataSource type="POOLED">  
                    <property name="driver" value="com.mysql.jdbc.Driver" />  
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatisTest?characterEncoding=utf-8" />  
                    <property name="username" value="root" />  
                    <property name="password" value="123456" />  
                </dataSource>  
            </environment>  
        </environments>
        <mappers>
        <mapper resource="sqlmap/user.xml"/>
      </mappers> 
    </configuration>

mybatis介绍与环境搭建

 

 

 

 <mappers>中包括的是针对每个对象的sql映射文件,environment标签中配置的是数据源,需要变动的只有这两个地方。

5.编写user.xml

mybatis介绍与环境搭建

<?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对应一个dao -->
<mapper namespace="test">
    <select id="srarchByid" parameterType="int" resultType="entity.users">
        select * from users where id=#{id}
    </select>
    <select id="searchByName" parameterType="String" resultType="entity.users">
        select * from users where name like '%${value}%'
    </select>
    <insert id="insertUser" parameterType="entity.users">
        insert into users(name,birthday,address,sex) values(#{name},#{birthday},#{address},#{sex})
        <selectKey keyProperty="id" order="AFTER" resultType="int">
            select last_insert_id()
        </selectKey>
    </insert>
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from users where id=#{id}
    </delete>
    <update id="updateUser" parameterType="entity.users">
        update users set name=#{name},address=#{address},birthday=#{birthday},sex=#{sex} where id=#{id}
    </update>

</mapper>

mybatis介绍与环境搭建

 

 这里共写了查询,插入,删除,更新四个sql语句,都用对应的标签包裹起来,每一个标签最后会映射为一个statement,标签中的属性id是此statement的唯一标示,以后再Java中就是通过这个id来调用的。parameterType表示输入参数,类似于在jdbc的预编译时为占位符赋值时的参数类型。

resultType是数据库返回结果对应的pojo类的类型。

<selectKey>标签是用来返回主键的,当插入一条记录后向立马得到这条记录的id就要加上这个标签,其中keyProperty属性标示的是实体类的主键属性,order表示此查询是在插入前执行还是插入后执行,resultType是查询的结果类型

6.创建一个实体类对应数据库,因为比较简单,此处不再给出代码

7.用Junit来测试。

mybatis介绍与环境搭建

package mt;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.List;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 entity.Classes;import entity.users;public class FirstDemo {
    @Test    public void findUserbyIdTest(){        
        try {
            String resource="SqlMapConfig.xml";
            InputStream stream=Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(stream);
            SqlSession sqlSession=sqlSessionFactory.openSession();
            users u=sqlSession.selectOne("test.srarchByid", 1);
            System.out.println(u.getBirthday().toString());
            sqlSession.close();
            
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Test    public void findUserByName(){        try {
            String resource="SqlMapConfig.xml";
            InputStream stream=Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(stream);
            SqlSession sqlSession=sqlSessionFactory.openSession();
            List<users> u=sqlSession.selectList("test.searchByName", "张");
            sqlSession.close();
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
    @Test    public void insertUser(){        try {
            String resource="SqlMapConfig.xml";
            InputStream stream=Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(stream);
            SqlSession sqlSession=sqlSessionFactory.openSession();
            users u=new users();
            u.setName("王磊");
            u.setSex("f");
            u.setBirthday(new Date());
            u.setAddress("上海");
            sqlSession.insert("test.insertUser", u);
            System.out.println(u.getId());
            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    @Test    public void deleteUser(){        try {
            String resource="SqlMapConfig.xml";
            InputStream stream=Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(stream);
            SqlSession sqlSession=sqlSessionFactory.openSession();
            sqlSession.insert("test.deleteUser",2);
            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Test    public void updateUser(){        try {
            String resource="SqlMapConfig.xml";
            InputStream stream=Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(stream);
            SqlSession sqlSession=sqlSessionFactory.openSession();
            users u=new users();
            u.setId(3);
            u.setName("王磊");
            u.setSex("f");
            u.setBirthday(new Date());
            u.setAddress("上海66666");
            sqlSession.update("updateUser",u);
            System.out.println(u.getId());
            sqlSession.commit();
            sqlSession.close();
        } catch (IOException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

mybatis介绍与环境搭建

 


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI