栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis的学习方法?

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis的学习方法?

为什么使用框架技术?
通过框架来制定开发规范,更进一步保证所有开发人员能够快速编写出统一的代码,让开发人员专注于业务实现
常用的框架技术 1、Spring
Spring是一个J2EE的框架,这个框架提供了对轻量级IOC的良好支持,同时也提供了对AOP技术非常好的封装,相比于其他的框架,
Spring框架的设计更加模块化,框架内的每个模块都能完成特定的工作,而且各个模块可以独立的运行,不会相互的前置,
因此,在使用Spring框架的时候,我们可以使用整个框架,也可以使用框架中的一部分
2、SpringMVC
Spring MVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架,通过把Model,View,Controller分离,将web层进行职责解耦,
把复杂的web应用分成逻辑清晰的几部分,简化开发,减少出错,方便组内开发人员之间的配合。
3、Mybatis
Mybatis是一个半ORM(对象关系映射)框架,它内部封装了JDBC,开发时只需要关注SQL语句本身,不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。
ORM框架,(只要提供了持久化类与表的映射关系,ORM框架在运行时就能参照映射文件的信息,把对象持久化到数据库中)
Mybatis框架 Mybatis背景
MyBatis前身是iBatis,本是Apache的一个开源的项目
Mybatis特点

灵活性能高,耦合度低

程序员直接编写原生态sql,可以严格控制sql执行性能,灵活度高
基于SQL语法,简单易学
SQL语句封装在配置文件中,便于统一管理与维护
Mybatis组成部分: 1、核心对象

通过SqlSessionFactoryBuilder才能创建SqlSessionFactory,才能拓展到SqlSession

SqlSessionFactoryBuilder:
SqlSessionFactory:MyBatis应用的核心
SqlSession
2、核心配置文件

mybatis-config.xml文件中

  						//默认的运行环境 ID
								//运行环境 ID
							//事务管理器配置
									//数据源配置
    
	
	
	



当然,我们也可以创建一个jdbc.properties使用配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.user=root
jdbc.password=ok

再在mybatis-config.xml文件中更改




    
    
        
    
    
        
            
            
                
                
                
                
            
        
    
    
        
    
3、sql映射文件

作用是映射实体类和数据库当中的表

    
            
        select count(1) from user    
    
理论是实践的基础,接下来就是实践 首先创建工程 1、创建实体类
package cn.happy.entity;

public class Person {
    private Integer id;
    private String name;
    private String nickname;
    private Integer age;

    public Person() {
    }

    public Person(Integer id, String name, String nickname, Integer age) {
        this.id = id;
        this.name = name;
        this.nickname = nickname;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
2、mapper的接口
package cn.happy.mapper;

import cn.hayyp.entity.Person;
import org.apache.ibatis.annotations.Param;

import javax.naming.Name;
import java.util.List;

public interface PersonMapper {
    //查询数据库记录数的方法
    public Integer findCount();

    //增加
    public Integer addPerson(Person person);

    //删除
    public Integer delById(Integer id);

    //修改
    public Integer updatePerson(Person person);

    //删除2
    public Integer delById2(Person person);

    //通过id查询对象
    public Person findById(Integer id);

    //查询所有
    public List findAll();

    //模糊查询
    public List findByName(String name);

    //通过用户名和昵称,多参查询
    public List findByPerson(Person person);

    //通过用户名和昵称,查询2
    //@Param()为加的注解,这样在xml中就不需要加parameterType了。
    public List findByUser(@Param("a") String name, @Param("b") String nickname);

    //测试$的使用方式
    public List findColList(@Param("colName") String colName);
}
3、创建PersonMapper.xml文件



    
        select * from t_person where id=#{id};
    

    
        select * from t_person where `name` like concat('%',#{name},'%')
    

    
        select * from t_person where `name` = #{a} and nickname = #{b};
    

    
4、创建测试类TestMybastis
package cn.happy.test;

import cn.happy.entity.Person;
import cn.happy.mapper.PersonMapper;
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;

public class TestMybastis {
    //查询记录数
    @Test
    public void testHelloWorld() throws IOException {
        //1.定义配置文件
        String config = "mybatis-config.xml";
        //2.通过流的机制获取主配置文件mybatis-config.xml的主配置信息
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建(实例化)SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4.调用builder对象的build()方法,获取SqlSessionFactory对象
        SqlSessionFactory factory = builder.build(in);
        //5.调用factory对象的openSession()方法,获取sqlSession对象
        SqlSession sqlSession = factory.openSession();
        //6.执行sql语句,调用接口方法
        Integer count = sqlSession.getMapper(PersonMapper.class).findCount();
        //输出对应的返回值
        System.out.println("count:" + count);
        //7.关闭sqlSession对象
        sqlSession.close();
    }
    //增加
    @Test
    public void testInsert()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();
        Person p = new Person();
        p.setName("曹桑");
        p.setAge(23);
        p.setNickname("野尻");
        sqlSession.getMapper(PersonMapper.class).addPerson(p);
        //提交,该行代码务必在被关闭sqlSession之前
        sqlSession.commit();
        sqlSession.close();
    }
    //修改
    @Test
    public void testupdate()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();
        Person p= new Person();
        p.setId(5);
        p.setName("王桑");
        p.setNickname("王野尻");
        p.setAge(26);
        sqlSession.getMapper(PersonMapper.class).updatePerson(p);
        sqlSession.commit();
        sqlSession.close();
    }
    //删除
    @Test
    public void testDel()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        sqlSession.getMapper(PersonMapper.class).delById(1);
        sqlSession.commit();
        sqlSession.close();
    }
    //删除2
    @Test
    public void testDel2()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        Person person = new Person();
        person.setId(2);
        sqlSession.getMapper(PersonMapper.class).delById2(person);
        sqlSession.commit();
        sqlSession.close();
    }

    //通过id查找
    @Test
    public void testfindById()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        Person p = sqlSession.getMapper(PersonMapper.class).findById(3);
        System.out.println("id:"+p.getId()+"name:"+p.getName()+"nickname:"+p.getNickname()+"age:"+p.getAge());
        sqlSession.close();
    }

    //查询所有
    @Test
    public void testfindAll()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        List list = sqlSession.getMapper(PersonMapper.class).findAll();
        for (Person p:list) {
            System.out.println(
                    "id:" + p.getId() + "name:" + p.getName() +
                            "nickname:" + p.getNickname() +
                            "age:" + p.getAge()
            );
        }
        sqlSession.close();
    }

    //模糊查询
    @Test
    public void testfindByName()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        List list = sqlSession.getMapper(PersonMapper.class).findByName("曹");
        for (Person p:list) {
            System.out.println(
                    "id:" + p.getId() + "name:" + p.getName() +
                            "nickname:" + p.getNickname() +
                            "age:" + p.getAge()
            );
        }
        sqlSession.close();
    }

    //通过用户名和昵称,多参查询
    @Test
    public void testfindByPerson()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        Person person = new Person();
        person.setName("曹桑");
        person.setNickname("曹大卓");
        List list = sqlSession.getMapper(PersonMapper.class).findByPerson(person);
        for (Person p:list) {
            System.out.println(
                    "id:" + p.getId() + "name:" + p.getName() +
                            "nickname:" + p.getNickname() +
                            "age:" + p.getAge()
            );
        }
        sqlSession.close();
    }
    //通过用户名和昵称,多参查询
    @Test
    public void testfindByUser()throws Exception{
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        SqlSession sqlSession = factory.openSession();

        List list = sqlSession.getMapper(PersonMapper.class).findByUser("王大朗","脆饼");
        for (Person p:list) {
            System.out.println(
                    "id:" + p.getId() + "name:" + p.getName() +
                            "nickname:" + p.getNickname() +
                            "age:" + p.getAge()
            );
        }
        sqlSession.close();
    }
}
这时会发现很多重复的代码,我们可以创建工具类MybatisUtil,使其更加简单
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {
    private static SqlSessionFactory factory = null;

    static {
        try {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            factory = builder.build(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        SqlSession sqlSession = null;
        if (factory != null){
            sqlSession = factory.openSession();
        }
        return sqlSession;
    }
}
通过MybatisUtil工具类,这样的测试代码就会简单很多:
package cn.happy.test2;

import cn.happy.entity.Person;
import cn.happy.mapper.PersonMapper;
import cn.happy.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestMybatis2 {
    @Test
    public void testfindCount(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        Integer count = sqlSession.getMapper(PersonMapper.class).findCount();
        System.out.println(count);
    }

    @Test
    public void testfindColList(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        List colList = sqlSession.getMapper(PersonMapper.class).findColList("age");
       for (Person p:colList){
           System.out.println("id"+p.getId()+"  name"+p.getName()+"  age"+p.getAge());
       }
    }

}

 

以上就是我对Mybatis学习的个人理解,还望多多指教

一个爱骑机车的码农敬上!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/605584.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号