1. 程式人生 > >MyBatis學習筆記之註解式

MyBatis學習筆記之註解式

1. 瞭解什麼是MyBatis:

  用百度的話來說,MyBatis 是一款優秀的持久層框架,它支援定製化 SQL、儲存過程以及高階對映。MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和對映原生資訊,將介面和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java物件)對映成資料庫中的記錄。

 簡而言之,MyBatis是支援普通SQL查詢,儲存過程和高階對映的優秀持久層框架,MyBatis提供的是一種“半自動化”的ORM實現

2.簡單例子:

在這裡我們用的是

IDEA開發工具,首先我們新建一個Maven專案

然後在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

<?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>
     <!--配置LOG4J-->
     <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--批量別名定義-->
    <typeAliases>
        <package name="com.zking.pojo"></package>
    </typeAliases>
    <!--jdbc資料庫連線池-->
    <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/test"/>
                <property name="username" value="root"/>
                <property name="password" value="sasa"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置對映檔案-->
    <mappers>
        <mapper class="com.zking.mapper.IProvinceMapper"/>
        <mapper class="com.zking.mapper.ICityMapper"/>
    </mappers>
</configuration>







實體類:

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<City> 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<City> getSc() {
        return sc;
    }

    public void setSc(Set<City> 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<City> 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<Province> 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<Province> findProvinceAll2();

    //動態SQL註解 作用在介面的方法上
    @SelectProvider(type = ProvinceSqlBuilder.class,method = "findProvinceSql")
    public List<Province> findProvinceAll3();

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

    @SelectProvider(type = ProvinceSqlBuilder.class,method = "findProvinceAll")
    public List<City> 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<City> list = ipm.findProvinceAll5();
        for (City c : list) {
            System.out.println(c.getPname()+"---"+c.getCname());
        }
        sqlSession.commit();
        sqlSession.close();
    }



}

其實MyBatis的註解式如果說是單一的Crud可能比較簡便,但是在動態SQL部分就比較麻煩,所以更建議使用配置式。