通过mybatis读取数据库数据并提供rest接口访问
分类:计算机网络

通过mybatis读取数据库数据并提供rest接口访谈,mybatisrest

1 mysql 创造数据库脚本

-- phpMyAdmin SQL Dump
-- version 4.2.11
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: 2016-08-02 18:13:50
-- 服务器版本: 5.6.21
-- PHP Version: 5.6.3

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `mybatis`
--

-- --------------------------------------------------------

--
-- 表的结构 `Student`
--

CREATE TABLE IF NOT EXISTS `Student` (
`id` int(10) NOT NULL,
  `name` varchar(256) NOT NULL,
  `age` int(4) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- 转存表中的数据 `Student`
--

INSERT INTO `Student` (`id`, `name`, `age`) VALUES
(1, 'zhansan', 20);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `Student`
--
ALTER TABLE `Student`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `Student`
--
ALTER TABLE `Student`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;

2  创设与数据库表Student对应的pojo类

package com.mtour.mybatis.demo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {
 int id;
 String name;
 int age;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

3  创制映射 studentMapper

<?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="com.mtour.mybatis.demo.studentMapper">

    <select id="getStudent" parameterType="int" 
        resultType="com.mtour.mybatis.demo.Student">
        select * from Student where id=#{id}
    </select>
</mapper>
  1.  创建 conf.xml

  2.  创建 rest 资源

    package com.mtour.mybatis.demo;

    import java.io.IOException; import java.io.InputStream;

    import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.core.MediaType;

@Path("/student")  
public class demo {  

 static String resource = "conf.xml";
 static InputStream is = demo.class.getClassLoader().getResourceAsStream(resource);
 static SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);

    @GET  
    @Produces(MediaType.TEXT_PLAIN)  
    public String sayHello() {  
        return "hello jersey , first demo" ;  
    }  

    @GET  
    @Path("/{param}")    
    @Produces("text/plain;charset=UTF-8")  
    public String sayHelloToUTF8(@PathParam("param") String username) {  
        return "Hello " + username;  
    }  

    @GET  
    @Path("/getstudent/{id}")  
    @Produces(MediaType.APPLICATION_JSON)  
    public Student getUserJson(@PathParam("id") String id) {  

     Integer studentId = Integer.valueOf(id);


     SqlSession session = sessionFactory.openSession();

     String statement = "com.mtour.mybatis.demo.studentMapper.getStudent";

     Student s = session.selectOne(statement, studentId);

     session.close();

     return s;  
    }




}  
  1. 初步调节和测验 

图片 1

 

源码下载: 

 

1 mysql 创立数据库脚本 -- phpMyAdmin SQL Dump-- version 4.2.11-- Host...

1 Mybatis映射文件

  • Mybatis映射文件指点着Mybatis怎样进展数据库的充实、删除、查询、改善,有着非常主要的意义。

 

  • cache:命名看空间的二级缓存配置。
  • cache-ref:别的命名空间缓存配置的引用。
  • resultMap:自定义结果集映射。
  • sql:收取科重用的语句块。
  • insert:映射插入语句。
  • update:映射更新语句。
  • delete:映射删除语句。
  • select:映射查询语句。

 

2 扩展、删除、修正、查询示例

  • Mybatis能够依附不一致的数据库,使用相应的例外的SQL。可是必要在全局配置文件中布置databaseIdProvider节点,何况在炫人眼目文件的讲话中标记所使用的数据库,示比方下(以MySQL为例)

  • 大局配置文件mybatis-config.xml

        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
    
  • 照耀文件

    INSERT INTO employee (last_name,gender,email) VALUE (#{lastName},#{gender},#{email})

 

  • Employee.java

    package com.xuweiwei.mybatis.pojo;

    public class Employee {

    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getLastName() {
        return lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    public String getGender() {
        return gender;
    }
    
    public void setGender(String gender) {
        this.gender = gender;
    }
    
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + ''' +
                ", gender='" + gender + ''' +
                ", email='" + email + ''' +
                '}';
    }
    

    }

  • 全局配置文件mybatis-config.xml

        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
    
  • EmployeeMapper.java

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);
    
    public boolean insertEmployee(Employee employee);
    
    public Long updateEmployee(Employee employee);
    
    public Integer deleteEmployeeById(Integer id);
    

    }

  • EmployeeMapper.xml

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    INSERT INTO employee (last_name,gender,email) VALUE (#{lastName},#{gender},#{email}) UPDATE employee SET last_name = #{lastName},gender=#{gender},email=#{email} WHERE id = #{id} DELETE from employee WHERE id = #{id}
  • 测试

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            System.out.println(employeeMapper.getEmployeeById(1));
        } finally {
            session.close();
        }
    }
    
    /**
     * 增加
     * @throws IOException
     */
    @Test
    public void testInsert() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = new Employee();
            employee.setLastName("许威");
            employee.setGender("男");
            employee.setEmail("1975356467@qq.com");
            System.out.println(employeeMapper.insertEmployee(employee));
            session.commit();
        } finally {
            session.close();
        }
    }
    
    /**
     * 修改
     */
    @Test
    public void testUpdate() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = new Employee();
            employee.setId(1);
            employee.setLastName("许威");
            employee.setGender("女");
            employee.setEmail("1975356467@qq.com");
            System.out.println(employeeMapper.updateEmployee(employee));
            session.commit();
        } finally {
            session.close();
        }
    }
    /**
     * 删除
     */
    @Test
    public void testDelete() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            System.out.println(employeeMapper.deleteEmployeeById(1));
            session.commit();
        } finally {
            session.close();
        }
    }
    
}

 

3 主键生成情势(以MySQL为例)

  • 咱俩清楚MySQL是支撑主键自动生成的,而Oracle是不援救的。
  • 那么对于MySQL大家得以在insert标签上安装useGeneratedKeys="truue",然后再把keyProperty设置到指标属性上。

    <insert id="insertEmployee" parameterType="com.xuweiwei.mybatis.pojo.Employee"  useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
        INSERT INTO employee (last_name,gender,email) VALUE (#{lastName},#{gender},#{email})
    </insert>
    

 

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public boolean insertEmployee(Employee employee);


}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    INSERT INTO employee (last_name,gender,email) VALUE (#{lastName},#{gender},#{email})
    • 测试  

    /**

     * 增加
     * @throws IOException
     */
    @Test
    public void testInsert() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = new Employee();
            employee.setLastName("许威");
            employee.setGender("男");
            employee.setEmail("1975356467@qq.com");
            System.out.println(employeeMapper.insertEmployee(employee));
            System.out.println(employee);
            session.commit();
        } finally {
            session.close();
        }
    }
    

 

4 参数传递

4.1 单个参数

  • 能够接收基本项目,对象类型,集结类型的之,这种场所下,Mybatis能够直接使用这么些参数,无需通过别的的拍卖。

 

  • 示例:

    • 大旨项目
      • EmployeeSingleParamMapper.java    

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeSingleParamMapper {

    public Employee getEmployeeById(Integer id);
    

    }

      • EmployeeSingleParamMapper.xml    

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
      • mybatis-config.xml    

        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
    
      • 测试    

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeSingleParamMapper; 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;

    public class MybatisTest2 {

    /**
     * 查询
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeSingleParamMapper employeeSingleParamMapper = session.getMapper(EmployeeSingleParamMapper.class);
            System.out.println(employeeSingleParamMapper.getEmployeeById(3));
        } finally {
            session.close();
        }
    }
    

    }

 

    • 目的类型
      • EmployeeSingleParamMapper.java    

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeSingleParamMapper {

    public Long updateEmployee(Employee employee);
    

    }

      • EmpoyeeSingleParamMapper.xml    

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    UPDATE employee SET last_name = #{lastName},gender=#{gender},email=#{email} WHERE id = #{id}
      • 测试    

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeSingleParamMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest2 {

    /**
     * 修改
     */
    @Test
    public void testUpdate() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeSingleParamMapper employeeSingleParamMapper = session.getMapper(EmployeeSingleParamMapper.class);
            Employee employee = new Employee();
            employee.setId(3);
            employee.setLastName("许威");
            employee.setGender("女");
            employee.setEmail("1975356467@qq.com");
            employeeSingleParamMapper.updateEmployee(employee);
            session.commit();
        } finally {
            session.close();
        }
    }
    

    }

 

    • 集中类型(借使是List、Set、Collection集合也许数组的话,Mybatis会对做特殊管理,key分别是collection、list、array)
      • EmployeeSingleParamMapper.java    

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    import java.util.List;

    public interface EmployeeSingleParamMapper {

    public List getEmployeeByIds(List ids);

}
      • EmployeeSingleParamMapper.xml    

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <select id="getEmployeeByIds" resultType="com.xuweiwei.mybatis.pojo.Employee" parameterType="java.lang.Integer">
        SELECT * FROM employee where id IN
        <foreach collection="list" item="id" index="index"
                 open="(" close=")" separator=",">
            #{id}
        </foreach>
    
    </select>
    
</mapper>
      • 测试    

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeSingleParamMapper; import com.xuweiwei.mybatis.pojo.Employee; 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.ArrayList; import java.util.List;

    public class MybatisTest2 {

    /**
     * 修改
     */
    @Test
    public void testSelect() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeSingleParamMapper employeeSingleParamMapper = session.getMapper(EmployeeSingleParamMapper.class);
            List<Integer> ids = new ArrayList<>();
            ids.add(3);
            ids.add(4);
            List<Employee> employees = employeeSingleParamMapper.getEmployeeByIds(ids);
            for(Employee employee:employees){
                System.out.println(employee);
            }
            session.commit();
        } finally {
            session.close();
        }
    }
    

    }

 

    • 参数是List集合
      • EmployeeMapper.java    

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    import java.util.List;

    public interface EmployeeMapper {

    public void insertEmployee(List<Employee> employees);
    

    }

      • EmployeeMapper.xml    

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    INSERT INTO employee(last_name,gender,email) VALUES (#{list[0].lastName},#{list[0].gender},#{list[0].email}),(#{list[1].lastName},#{list[1].gender},#{list[1].email})
      • 测试    

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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.ArrayList; import java.util.List;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            List<Employee> employees = new ArrayList<>();
    
            Employee emp1 = new Employee();
            emp1.setLastName("哈哈");
            emp1.setGender("男");
            emp1.setEmail("1232163.com");
            employees.add(emp1);
    
            Employee emp2 = new Employee();
            emp2.setLastName("呵呵");
            emp2.setGender("男");
            emp2.setEmail("1232163.com");
            employees.add(emp2);


            employeeMapper.insertEmployee(employees);

            session.commit();
        } finally {
            session.close();
        }
    }


}

 

    • 参数是数组
      • EmployeeMapper.java    

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    import java.util.List;

    public interface EmployeeMapper {

    public List<Employee> getEmpsByIds(Integer[] ids);
    

    }

      • EmployeeMapper.xml    

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
      • 测试    

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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 MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Integer[] ids = new Integer[2];
            ids[0] = 3;
            ids[1] = 4;
    
            List<Employee> emps = employeeMapper.getEmpsByIds(ids);
            for(Employee employee : emps){
                System.out.println(employee);
            }
    
            session.commit();
        } finally {
            session.close();
        }
    }
    
}

 

4.2 四个参数

  • 假若是七个参数,Mybatis会做非常的拍卖,会将参数封装成二个Map,key是param1,param2……恐怕索引也足以。

 

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public Employee getEmployeeByIdAndLastName(Integer id ,String lastName);
    
}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.getEmployeeByIdAndLastName(3, "许威");
            System.out.println(employee);
        } finally {
            session.close();
        }
    }
    
}

 

4.3 命名参数

  • 为参数使用@Param起四个名字,Mybatis就能将那么些参数封装进Map中,key正是大家和好钦定的名字

 

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

        import com.xuweiwei.mybatis.pojo.Employee;
        import org.apache.ibatis.annotations.Param;
    

    public interface EmployeeMapper {

    public Employee getEmployeeByIdAndLastName(@Param("id") Integer id ,@Param("lastName") String lastName);
    
}
    • EmployeeMapper.xml  

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee = employeeMapper.getEmployeeByIdAndLastName(3, "许威");
            System.out.println(employee);
        } finally {
            session.close();
        }
    }
    
}

 

4.4 POJO

  • 当那几个参数属于工作的POJO的时候,直接传送POJO

 

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public void insertEmployee(Employee employee);
    

    }

    • EmployeeMapper.xml  

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    INSERT INTO employee(last_name,gender,email) VALUES (#{lastName},#{gender},#{email})
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = new Employee();
            emp.setEmail("123@163.com");
            emp.setGender("女");
            emp.setLastName("凤姐");
            employeeMapper.insertEmployee(emp);
            session.commit();
        } finally {
            session.close();
        }
    }
    
}

 

4.5 Map

  • 大家也足以将参数封装到一个Map对象中,直接传送

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import java.util.Map;

    public interface EmployeeMapper {

    public void insertEmployee(Map<String, Object> param);
    

    }

    • EmployeeMapper.xml  

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    INSERT INTO employee(last_name,gender,email) VALUES (#{lastName},#{gender},#{email})
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; 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.HashMap; import java.util.Map;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Map<String,Object> map = new HashMap<>();
            map.put("lastName", "哈哈");
            map.put("email", "123@163.com");
            map.put("gender", "女");
            employeeMapper.insertEmployee(map);
    
            session.commit();
        } finally {
            session.close();
        }
    }


}

 

5 #{}和${}的区别

  • 相像点:都足以获得map中的值可能POJO对象属性的值。
  • 不同点:
    • #{}是以预编译的款型,将参数设置到sql语句中
    • ${}将抽取的值直接拼接到sql中。会有SQL注入难题。日常用在原生JDBC不援助占位符的地点,就能够动用${}  

 

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee; import org.apache.ibatis.annotations.Param;

    public interface EmployeeMapper {

    public Employee getEmpByIdAndListName(@Param("id") Integer id, @Param("lastName") String lastName);
    

    }

    • EmployeeMapper.xml  

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = employeeMapper.getEmpByIdAndListName(3,"许威");
            System.out.println(emp);
            session.commit();
        } finally {
            session.close();
        }
    }
    
}

图片 2

 

  • 示范:表名使用${}

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee; import org.apache.ibatis.annotations.Param;

    public interface EmployeeMapper {

    public Employee getEmpByIdAndListName(@Param("id") Integer id, @Param("lastName") String lastName,@Param("tabName") String tabName);
    

    }

    • EmployeeMapper.xml  

        <!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = employeeMapper.getEmpByIdAndListName(3,"许威","employee");
            System.out.println(emp);
            session.commit();
        } finally {
            session.close();
        }
    }
    
}

 

6 select标签

  • select成分用来定义查询操作。
    • 属性
      • id:唯后生可畏标记符。用来援用那条语句,须求和接口的措施名相近。
      • parameterType:参数类型。能够不传,Mybatis会依照TypeHandler自动推测。
      • resultType:重临值类型。小名或许全类名,借使回去的是谋面,定义集结瓜时素的门类。不可能和resultMap同不常间使用。    

 

6.1 resultType

6.1.1 返回List集合

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    import java.util.List;

    public interface EmployeeMapper {

    public List<Employee> getEmpsByName(String name);
    

    }

    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <select id="getEmpsByName" resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT *
        FROM employee
        WHERE last_name like #{lastName}
    </select>

</mapper>
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; import com.xuweiwei.mybatis.pojo.Employee; 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 MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            List<Employee> emps = employeeMapper.getEmpsByName("%许%");
            for(Employee employee:emps){
                System.out.println(employee);
            }
        } finally {
            session.close();
        }
    }
    
}

 

6.1.2 返回Map集合

  • 示例:

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import java.util.Map;

    public interface EmployeeMapper {

    public Map<String,Object> getEmpById(Integer id);


}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <select id="getEmpById" resultType="map">
        SELECT *
        FROM employee
        WHERE id = #{id}
    </select>

</mapper>
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.EmployeeMapper; 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.Map;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Map<String,Object> map = employeeMapper.getEmpById(3);
            System.out.println(map);
        } finally {
            session.close();
        }
    }
    
}

 

6.1.3 再次回到Map<主键,记录所对应的成团对象类型>

  • 示例:

    • EmployeeMapper.java 

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee; import org.apache.ibatis.annotations.MapKey;

    import java.util.Map;

    public interface EmployeeMapper {

    @MapKey("id")
    public  Map<Integer,Employee> getEmpsByName(String name);
    
}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <select id="getEmpsByName" resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT *
        FROM employee
        WHERE last_name like #{name}
    </select>

</mapper>
    • 测试  

    package com.xuweiwei.mybatis.test;

        import com.xuweiwei.mybatis.mapper.EmployeeMapper;
        import com.xuweiwei.mybatis.pojo.Employee;
        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.Map;
    

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Map<Integer,Employee> map = employeeMapper.getEmpsByName("%许%");
            System.out.println(map);
        } finally {
            session.close();
        }
    }
    
}

 

6.2 resultMap

6.2.1 自定义结果集

  • 我们必要领会的是数据库中的字段是last_name,而实体类中的属性是lastName,假如要兑现五头之间的照耀,犹如下三种办法。

 

  • ①在大局配置文件中,设置如下属性

 

  • ②就是在查询的时候使用外号

    SELECT id,last_name lastName,gender,email WHERE id = #{id}

 

  • ③自定义结果集

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);
    
}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <resultMap id="empMap" type="com.xuweiwei.mybatis.pojo.Employee">
        <id property="id" column="id"/>
        <result property="lastName" column="last_name"/>
        <result property="gender" column="gender"/>
        <result property="email" column="email"/>
    </resultMap>
    
    <select id="getEmployeeById" resultMap="empMap" >
        SELECT * FROM employee WHERE id = #{id}
    </select>
    
</mapper>
    • 测试  

    package com.xuweiwei.mybatis.test;

        import com.xuweiwei.mybatis.mapper.EmployeeMapper;
    

    import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee  = employeeMapper.getEmployeeById(3);
            System.out.println(employee);
        } finally {
            session.close();
        }
    }
    
}

 

6.2.2 关联合检查询

  • 脚本

    CREATE TABLE department(

    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(255)    
    

    )

    ALTER TABLE employee ADD COLUMN department_id INT; ALTER TABLE employee ADD CONSTRAINT fk_emp_department FOREIGN KEY (department_id) REFERENCES department(id)

 

6.2.2.1 关联合检查询之级联属性封装结果集

  • 示例:

    • Employee.java  

    package com.xuweiwei.mybatis.pojo;

    public class Employee {

    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + ''' +
                ", gender='" + gender + ''' +
                ", email='" + email + ''' +
                ", department=" + department +
                '}';
    }
}
    • Department.java  

    package com.xuweiwei.mybatis.pojo;

    public class Department {

    private Integer id;
    private String name;
    
    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;
    }
    
    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", name='" + name + ''' +
                '}';
    }
    

    }

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public Employee getEmployeeAndDepartmentById(Integer id);
    
}
    • EmployeeMapper.xml    

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <resultMap id="empMap" type="com.xuweiwei.mybatis.pojo.Employee">
        <id property="id" column="id"/>
        <result property="lastName" column="last_name"/>
        <result property="gender" column="gender"/>
        <result property="email" column="email"/>
        <result property="department.id" column="did"/>
        <result property="department.name" column="dname"/>
    </resultMap>
    
    <select id="getEmployeeAndDepartmentById" resultMap="empMap">
        SELECT e.id id,e.last_name last_name,e.gender gender ,e.email email ,d.id did,d.name dname
        FROM `employee` e INNER  JOIN `department` d
        ON e.department_id = d.id
        WHERE e.id = #{id};
    </select>
    
</mapper>
    • 测试  

    package com.xuweiwei.mybatis.test;

        import com.xuweiwei.mybatis.mapper.EmployeeMapper;
    

    import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee  = employeeMapper.getEmployeeAndDepartmentById(3);
            System.out.println(employee);
        } finally {
            session.close();
        }
    }
    
}

 

6.2.2.2 关联合检查询之association定义关联对象封装结果集

  • 示例:

    • EmployeeMapper.xml    

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <resultMap id="empMap" type="com.xuweiwei.mybatis.pojo.Employee">
        <id property="id" column="id"/>
        <result property="lastName" column="last_name"/>
        <result property="gender" column="gender"/>
        <result property="email" column="email"/>
        <!--
            可以指定关联的JavaBean对象
            property:指定那个属性是联合对象
            javaType:指定这个属性对应的类型(不能少)
        -->
        <association property="department" javaType="com.xuweiwei.mybatis.pojo.Department" >
            <id property="id" column="did"/>
            <result property="name" column="dname"/>
        </association>
    
    </resultMap>
    
    <select id="getEmployeeAndDepartmentById" resultMap="empMap">
        SELECT e.id id,e.last_name last_name,e.gender gender ,e.email email ,d.id did,d.name dname
        FROM `employee` e INNER  JOIN `department` d
        ON e.department_id = d.id
        WHERE e.id = #{id};
    </select>
    
</mapper>
  • 其余代码和6.2.2.1如出生龙活虎辙。

 

6.2.2.3 关联合检查询之association分步查询

  •  示例:

    • Employee.java  

    package com.xuweiwei.mybatis.pojo;

    public class Employee {

    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + ''' +
                ", gender='" + gender + ''' +
                ", email='" + email + ''' +
                ", department=" + department +
                '}';
    }
}
    • Department.java  

    package com.xuweiwei.mybatis.pojo;

    public class Department {

    private Integer id;
    private String name;
    
    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;
    }
    
    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", name='" + name + ''' +
                '}';
    }
    

    }

    • DepartmentMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Department;

    public interface DepartmenMapper {

    public Department getDepartmentById(Integer id);
    

    }

    • DepartmentMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public Employee getEmployeeAndDepartmentById(Integer id);
    
}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <resultMap id="empMap" type="com.xuweiwei.mybatis.pojo.Employee">
        <id property="id" column="id"/>
        <result property="lastName" column="last_name"/>
        <result property="gender" column="gender"/>
        <result property="email" column="email"/>
    
        <!--
            分步查询
        -->
        <association property="department"  select="com.xuweiwei.mybatis.mapper.DepartmenMapper.getDepartmentById" column="department_id">
        </association>
    
    </resultMap>
    
    <select id="getEmployeeAndDepartmentById" resultMap="empMap">
        SELECT  e.`id` id ,e.`last_name` last_name,e.`gender` gender,e.`email` email,e.`department_id` department_id
        FROM employee e
        WHERE id = #{id}
    </select>
    
</mapper>
    • 测试  

    package com.xuweiwei.mybatis.test;

        import com.xuweiwei.mybatis.mapper.EmployeeMapper;
    

    import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee  = employeeMapper.getEmployeeAndDepartmentById(3);
            System.out.println(employee);
        } finally {
            session.close();
        }
    }
    
}

 

6.2.2.4 分步查询&延迟加载

  • 分步查询才有延期加载。

 

  • 在大局配置文件中布署如下音信

 

  • 测验(别的代码和6.2.2.3生机勃勃律)

    package com.xuweiwei.mybatis.test;

        import com.xuweiwei.mybatis.mapper.EmployeeMapper;
    

    import com.xuweiwei.mybatis.pojo.Employee; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee employee  = employeeMapper.getEmployeeAndDepartmentById(3);
            System.out.println(employee.getLastName());
        } finally {
            session.close();
        }
    }
    
}

图片 3

 

6.2.2.5 关联合检查询之collection定义关联合集团合打包结果集

  • 示范:查询部门的时候,将部门呼应的职工新闻查询出来

    • Employee.java  

    package com.xuweiwei.mybatis.pojo;

    public class Employee {

    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + ''' +
                ", gender='" + gender + ''' +
                ", email='" + email + ''' +
                '}';
    }
}
    • Department.java  

    package com.xuweiwei.mybatis.pojo;

    import java.util.List;

    public class Department {

    private Integer id;
    private String name;
    
    private List<Employee> employees;
    
    public List<Employee> getEmployees() {
        return employees;
    }
    
    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
    
    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;
    }
    
    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", employees=" + employees +
                '}';
    }
    

    }

  • DepartmentMapper.java

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Department;

    public interface DepartmenMapper {

    public Department getDepartmentById(Integer id);
    

    }

  • DepartmentMapper.xml

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
  • 测试

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.DepartmenMapper; import com.xuweiwei.mybatis.pojo.Department; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            DepartmenMapper departmenMapper = session.getMapper(DepartmenMapper.class);
            Department department = departmenMapper.getDepartmentById(1);
            System.out.println(department);
    
        } finally {
            session.close();
        }
    }
    
}

 

6.2.2.5 关联合检查询之collection分步查询

  • 示例:

    • Employee.java    

    package com.xuweiwei.mybatis.pojo;

    public class Employee {

    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    
    private Department department;

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + ''' +
                ", gender='" + gender + ''' +
                ", email='" + email + ''' +
                '}';
    }
}
    • Department.java  

    package com.xuweiwei.mybatis.pojo;

    import java.util.List;

    public class Department {

    private Integer id;
    private String name;
    
    private List<Employee> employees;
    
    public List<Employee> getEmployees() {
        return employees;
    }
    
    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
    
    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;
    }
    
    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", employees=" + employees +
                '}';
    }
    

    }

    • EmployeeMapper.java  

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Employee;

    public interface EmployeeMapper {

    public Employee getEmployeeById(Integer departmentId);
    
}
    • EmployeeMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <select id="getEmployeeById"  resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT  e.`id` id ,e.`last_name` last_name,e.`gender` gender,e.`email` email
        FROM employee e
        WHERE e.`department_id` = #{departmentId}
    </select>


</mapper>
    • DepartmentMapper.java    

    package com.xuweiwei.mybatis.mapper;

    import com.xuweiwei.mybatis.pojo.Department;

    public interface DepartmenMapper {

    public Department getDepartmentById(Integer id);
    

    }

    • DepartmentMapper.xml  

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    • 测试  

    package com.xuweiwei.mybatis.test;

    import com.xuweiwei.mybatis.mapper.DepartmenMapper; import com.xuweiwei.mybatis.pojo.Department; 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;

    public class MybatisTest {

    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            DepartmenMapper departmenMapper = session.getMapper(DepartmenMapper.class);
            Department department = departmenMapper.getDepartmentById(1);
            System.out.println(department);
            System.out.println(department.getEmployees());
    
        } finally {
            session.close();
        }
    }
    
}

 

本文由正版必中一肖图发布于计算机网络,转载请注明出处:通过mybatis读取数据库数据并提供rest接口访问

上一篇:没有了 下一篇:没有了
猜你喜欢
热门排行
精彩图文