MyBatis学习笔记之注解式

1. 了解什么是MyBatis:

  用百度的话来说,MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。

 简而言之,MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架,MyBatis提供的是一种“半自动化”的ORM实现

 

2.简单例子:

在这里我们用的是IDEA开发工具,首先我们新建一个Maven项目

MyBatis学习笔记之注解式_第1张图片

然后在pom.xml导入jar包:

mybatis需要jar包:mybatis-3.3.0.jar

mysql驱动jar包:mysql-connector-java-5.1.44.-bin.jar

日志记录jar包:log4j-1.2.17.jar

 

配置MyBatis映射文件mybatis.cfg.xml




     
     
        
    
    
    
        
    
    
    
        
            
            
                
                
                
                
            
        
    
    
    
        
        
    








实体类:

City:

package com.zking.pojo;

import java.io.Serializable;

public class City extends Province implements Serializable{

    private String cid;
    private String cname;
    private String pid;
    //设置1对M关系
    private Province province;

    public City() {
    }

    public City(String cid, String cname, String pid) {
        this.cid = cid;
        this.cname = cname;
        this.pid = pid;
    }

    public String getCid() {
        return cid;
    }

    public void setCid(String cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public Province getProvince() {
        return province;
    }

    public void setProvince(Province province) {
        this.province = province;
    }
}

Province:

package com.zking.pojo;

import java.io.Serializable;
import java.util.Set;

public class Province implements Serializable{

    private String pid;
    private  String pname;
    //设置关系 1V1
    private City city;
    //1VM
    private Set sc;

    public Province() {
    }

    public Province(String pid, String pname) {
        this.pid = pid;
        this.pname = pname;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public Set getSc() {
        return sc;
    }

    public void setSc(Set sc) {
        this.sc = sc;
    }
}

创建方法接口:

package com.zking.mapper;

import com.zking.pojo.City;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;


import java.util.List;

public interface ICityMapper {

    @Insert("insert into City values(#{cid},#{cname},#{pid})")
    public  int addCity(City city);

    @Update("UPDATE City SET cname=#{cname},pid=#{pid} where cid=#{cid}")
    public  int editCity(City city);

    @Delete("delete from City where cid=#{cid}")
    public  int removeCity(City city);

    @Select("select * from City where pid=#{pid}")
    public List finfCityAll();
}
package com.zking.mapper;

import com.zking.pojo.City;
import com.zking.pojo.Province;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface IProvinceMapper {

    @Insert("INSERT INTO Province VALUES(#{pid},#{pname})")
    public  int addProvince(Province province);

    @Update("UPDATE Province SET pname=#{pname} where pid=#{pid}")
    public int editProvince(Province province);
  
    //1V1关系注解
    @Select("select * from Province")
    @Results({
            @Result(id = true,column = "pid",property = "pid"),
            @Result(column = "pname",property = "pname"),
            @Result(property = "city",column = "pid",
            one=@One(select = "com.zking.mapper.ICityMapper.finfCityAll"))
    })
    public List findProvinceAll();

    //多对多关系注解
    @Select("select * from Province")
    @Results({
            @Result(id = true,column = "pid",property = "pid"),
            @Result(column = "pname",property = "pname"),
            @Result(property = "sc",column = "pid",
                    many=@Many(select = "com.zking.mapper.ICityMapper.finfCityAll"))
    })
    public List findProvinceAll2();

    //动态SQL注解 作用在接口的方法上
    @SelectProvider(type = ProvinceSqlBuilder.class,method = "findProvinceSql")
    public List findProvinceAll3();

    @SelectProvider(type = ProvinceSqlBuilder.class,method = "findProvinceByQuery")
    public List findProvinceAll4(Province province);

    @SelectProvider(type = ProvinceSqlBuilder.class,method = "findProvinceAll")
    public List findProvinceAll5();
}

在MyBatis的映射配置文件中写sql语句有时候很方便,但是对于有大量字段的表结构却不太简单,幸好MyBatis提供的有SqlBuilder工具类,可以生成相应的SQL语句,如下:

package com.zking.mapper;

import com.zking.pojo.Province;
import org.apache.ibatis.jdbc.SQL;

public class ProvinceSqlBuilder {

    public String findProvinceSql(){
          return new SQL()
                  .SELECT("*")
                  .FROM("Province")
                  .toString();
    }

    public  String findProvinceByQuery(final Province province){
        return  new SQL(){{
            SELECT("*");
            FROM("Province");
            if(province.getPname()!=null){
                AND();
                WHERE("pname like #{pname}");
            }
        }}.toString();
    }


    public String findProvinceAll(){
        return  new SQL(){{
            SELECT("*");
            FROM("Province p");
            LEFT_OUTER_JOIN(" City c on p.pid=c.pid");
        }}.toString();
    }


}

测试类:

package com.zking.test;

import com.zking.mapper.ICityMapper;
import com.zking.mapper.IProvinceMapper;
import com.zking.pojo.City;
import com.zking.pojo.Province;
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.util.List;
import java.util.UUID;

public class MyBatis04Test {

    @Test
    public void addProvince() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        Province p=new Province();
        p.setPid(String.valueOf(UUID.randomUUID()));
        p.setPname("湖北");
        ipm.addProvince(p);
        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void editProvince() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        Province p=new Province();
        p.setPid("044ff20a-9da1-4205-a75a-991b6bfb413f");
        p.setPname("湖北");
        ipm.editProvince(p);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void addCity() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ICityMapper icm = sqlSession.getMapper(ICityMapper.class);
        City c=new City();
        c.setCid(String.valueOf(UUID.randomUUID()));
        c.setCname("株洲");
        c.setPid("5894c3bf-f89c-4dca-810c-64c5c25da742");
        icm.addCity(c);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void editCity() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ICityMapper icm = sqlSession.getMapper(ICityMapper.class);
        City c=new City();
        c.setCid("441c77ef-80aa-4327-9fd7-e1f08c92292b");
        c.setCname("长沙");
        c.setPid("5894c3bf-f89c-4dca-810c-64c5c25da742");
        icm.editCity(c);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void removeCity() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ICityMapper icm = sqlSession.getMapper(ICityMapper.class);
        City c=new City();
        c.setCid("521b672e-0109-432b-ae92-cc75323ea3fc");
        icm.removeCity(c);
        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void findProvinceAll() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        ipm.findProvinceAll();
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void findProvinceAll2() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        ipm.findProvinceAll2();
        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void findProvinceAll3() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        ipm.findProvinceAll3();
        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void findProvinceAll4() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        Province province=new Province();
        province.setPname("%南%");
        ipm.findProvinceAll4(province);
        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void findProvinceAll5() throws  Exception{
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        IProvinceMapper ipm = sqlSession.getMapper(IProvinceMapper.class);
        List list = ipm.findProvinceAll5();
        for (City c : list) {
            System.out.println(c.getPname()+"---"+c.getCname());
        }
        sqlSession.commit();
        sqlSession.close();
    }



}

其实MyBatis的注解式如果说是单一的Crud可能比较简便,但是在动态SQL部分就比较麻烦,所以更建议使用配置式。

你可能感兴趣的:(MyBatis学习笔记之注解式)