`

Mybatis中配置Mapper的方法

阅读更多

        我们知道在Mybatis中定义Mapper信息有两种方式,一种是利用xml写一个对应的包含Mapper信息的配置文件;另一种就是定义一个Mapper接口,然后定义一些相应的操作方法,再辅以相应的操作注解。

        现假设我有这样一个实体类:

package com.bijian.model;

public class User {

    private int id;
    private String name;
    private 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;
    }
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

        它对应的数据库表结构是这样的:


        然后我要利用Mybatis对它做一个简单的增删改查操作,那么如果利用xml配置Mapper的方式来定义的话,我对应的UserMapper.xml文件会是这样:

<?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.bijian.mapper.UserMapper">
    <insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="id">
       insert into user_tb(name, age) values(#{name}, #{age})
    </insert>
   
    <update id="updateUser" parameterType="User">
       update user_tb set name=#{name}, age=#{age} where id=#{id}
    </update>
   
    <select id="findById" parameterType="int" resultType="User">
       select * from user_tb where id=#{id}
    </select>
   
    <delete id="deleteUser" parameterType="int">
       delete from user_tb where id=#{id}
    </delete>
</mapper>

        如果使用接口加注解的方式,那么我们的UserMapper接口应该这样定义:

package com.bijian.mapperinterface;

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 com.bijian.model.User;

public interface UserMapper {

    @Insert("insert into user_tb(name, age) values(#{name}, #{age})")
    public void insertUser(User user);

    @Update("update user_tb set name=#{name}, age=#{age} where id=#{id}")
    public void updateUser(User user);

    @Select("select * from user_tb where id=#{id}")
    public User findById(int id);

    @Delete("delete from user_tb where id=#{id}")
    public void deleteUser(int id);
}

        注意看这里我故意把UserMapper接口的namespace也就是它的包名置为与UserMapper.xml的namespace属性不一样。这主要是为了要更好的讲以下的内容。

        接下来要做的就是把Mapper信息注册到Mybatis的配置中,告诉Mybatis我们定义了哪些Mapper信息。这主要是在Mybatis的配置文件中通过mappers元素来进行的。在以前版本的Mybatis中我们在Mybatis的配置文件中需要这样定义Mapper信息资源的位置。

<mappers>
       <mapper resource="com/bijian/mapper/UserMapper.xml"/>
       <mapper url="file:///E:/UserMapper.xml"/>
</mappers>

        这主要是通过mapper元素的resource和url属性来指定的,resource属性指定的是相对于跟类路径下的资源,url属性指定的是通过URL可以获取到的资源。这有一点不好的地方,当我们使用Mapper接口加注解来定义当前Mapper的操作信息时,我们还需要定义一个与它对应的Mapper.xml文件。如:

<?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.bijian.mapperinterface.UserMapper">
 
</mapper>
package com.bijian.mapperinterface;

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 com.bijian.model.User;

public interface UserMapper {

    @Insert("insert into user_tb(name, age) values(#{name}, #{age})")
    public void insertUser(User user);

    @Update("update user_tb set name=#{name}, age=#{age} where id=#{id}")
    public void updateUser(User user);

    @Select("select * from user_tb where id=#{id}")
    public User findById(int id);

    @Delete("delete from user_tb where id=#{id}")
    public void deleteUser(int id);
}

        我发现在现在使用的这个Mybatis3.2.1中这个问题已经得到了改善,现在我们在定义基于接口的定义的Mapper时可以通过一个class属性来指定接口。

<mappers>
       <mapper class="com.bijian.mapperinterface.UserMapper"/>
</mappers>

        这里的一个package只针对于一个包。当在多个包里面定义有Mapper接口时,我们需要定义对应的多个package元素。

        这四种注册Mapper的方式就是我想在这篇文章中表达的。总结一下:

<mappers>
       <!-- 通过package元素将会把指定包下面的所有Mapper接口进行注册 -->
       <package name="com.bijian.mapperinterface"/>
       <!-- 通过mapper元素的resource属性可以指定一个相对于类路径的Mapper.xml文件 -->
       <mapper resource="com/bijian/mapper/UserMapper.xml"/>
       <!-- 通过mapper元素的url属性可以指定一个通过URL请求道的Mapper.xml文件 -->
       <mapper url="file:///E:/UserMapper.xml"/>
       <!-- 通过mapper元素的class属性可以指定一个Mapper接口进行注册 -->
       <mapper class="com.bijian.mapperinterface.UserMapper"/>
</mappers>

        当使用mapper元素进行Mapper定义的时候需要注意:mapper的三个属性resource、url和class对于每个mapper元素只能指定一个,要么指定resource属性,要么指定url属性,要么指定class属性,不能都指定,也不能都不指定。

        下面将对上面的代码给出一些对应的测试代码。

        先看下工程结构图:

        再贴出测试对应的Mybatis的配置文件:

<?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>
    <typeAliases>
        <typeAlias alias="User" type="com.bijian.model.User" />
    </typeAliases>
    <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://127.0.0.1:3306/test?characterEncoding=utf8" />
                <property name="username" value="test" />
                <property name="password" value="test" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
   		<!-- 通过mapper元素的resource属性可以指定一个相对于类路径的Mapper.xml文件 -->
		<mapper resource="com/bijian/mapper/UserMapper.xml" />
		<!-- 通过package元素将会把指定包下面的所有Mapper接口进行注册 -->
		<package name="com.bijian.mapperinterface" />
	</mappers>
</configuration>

Util.java

package com.bijian.util;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Util {

    public static SqlSessionFactory getSqlSessionFactory() {
        
        String resource = "configure.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
        return factory;
    }
}

 

一.对于使用xml方式定义的UserMapper.xml,然后直接使用SqlSession访问定义在其中的statement的测试:

package com.bijian.test;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Before;
import org.junit.Test;

import com.bijian.model.User;
import com.bijian.util.Util;

/**
 * 这个类主要用来测试直接使用SqlSession访问定义在UserMapper.xml文件中的statement
 */
public class UserMapperTest {

    SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void before() {
        sqlSessionFactory = Util.getSqlSessionFactory();
    }

    @Test
    public void testInsert() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setName("张三");
            user.setAge(30);
            sqlSession.insert("com.bijian.mapper.UserMapper.insertUser", user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testUpdate() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setId(1);
            user.setName("李四");
            user.setAge(34);
            sqlSession.update("com.bijian.mapper.UserMapper.updateUser", user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testFind() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = sqlSession.selectOne("com.bijian.mapper.UserMapper.findById", 1);
            System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testDelele() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.delete("com.bijian.mapper.UserMapper.deleteUser", 2);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}

 

二.对于使用Mapper接口加对应的注解来定义的Mapper信息直接使用SqlSession访问Mapper接口中使用注解定义好的statement的测试:

package com.bijian.test;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Before;
import org.junit.Test;

import com.bijian.model.User;
import com.bijian.util.Util;

/**
 *这个类是测试直接使用SqlSession访问UserMapper接口中使用注解定义好的statement
 */
public class UserMapperTest2 {

    SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void before() {
        sqlSessionFactory = Util.getSqlSessionFactory();
    }
    
    @Test
    public void testInsert() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setName("张三");
            user.setAge(30);
            sqlSession.insert("com.bijian.mapperinterface.UserMapper.insertUser", user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testUpdate() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setId(1);
            user.setName("李四");
            user.setAge(34);
            sqlSession.update("com.bijian.mapperinterface.UserMapper.updateUser", user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testFind() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = sqlSession.selectOne("com.bijian.mapperinterface.UserMapper.findById", 1);
            System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testDelele() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            sqlSession.delete("com.bijian.mapperinterface.UserMapper.deleteUser", 3);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}

 

三.对于使用Mapper接口加注解定义好的Mapper信息通过SqlSession获取其对应的Mapper接口来操作其中定义好的statement的测试:

package com.bijian.test;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Before;
import org.junit.Test;

import com.bijian.mapperinterface.UserMapper;
import com.bijian.model.User;
import com.bijian.util.Util;

/**
 *这个类是测试使用SqlSession获取UserMapper接口来执行使用注解定义在UserMapper接口中的statement
 */
public class UserMapperTest3 {

    SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void before() {
        sqlSessionFactory = Util.getSqlSessionFactory();
    }
    
    @Test
    public void testInsert() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setName("张三");
            user.setAge(30);
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userMapper.insertUser(user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testUpdate() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setId(1);
            user.setName("李四");
            user.setAge(34);
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userMapper.updateUser(user);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testFind() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.findById(1);
            System.out.println(user.getId() + "--" + user.getName() + "--" + user.getAge());
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testDelele() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            userMapper.deleteUser(5);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}

 

文章来源:http://haohaoxuexi.iteye.com/blog/1841033

  • 大小: 2.9 KB
  • 大小: 17.4 KB
分享到:
评论

相关推荐

    mybatis自动生成mapper文件

    下面将详细阐述MyBatis Generator的使用方法、功能以及它如何帮助我们自动化生成实体类和Mapper文件。 1. **MyBatis Generator概述** MyBatis Generator基于Java,它可以解析数据库表结构,并根据这些信息生成相应...

    mybatis热部署mapper增量更新.

    例如,在Java代码中调用SqlSessionFactory的`refresh()`方法,强制MyBatis重新加载mapper配置。 6. **监控文件系统**:还可以自己编写监控文件系统变化的逻辑,当检测到mapper.xml文件有变动时,通过Java的`...

    Java的MyBatis框架中Mapper映射配置的使用及原理解析

    总的来说,Mapper映射配置在MyBatis中扮演着桥梁的角色,连接Java代码和数据库操作。通过合理的配置和使用,开发者可以有效地进行数据库操作,提高代码的可读性和可维护性。了解并熟练掌握Mapper映射配置是每个使用...

    这个是配置mybatis的配置的其中一个mapper.dtd

    这个是我今天学的一个Java里面mybatis的主配置中的其中一个包,由于软件问题,只可以传一个,这是接上一个config.dtd的mapper.dtd,这个下载了,记得解压,这个是mapper.dtd还有一个config,等会发下一个教程和代码,...

    mybatis逆向生成mapper

    MyBatis逆向生成Mapper是一项高效实用的开发工具功能,它可以帮助Java开发者快速构建数据库操作的Mapper接口和对应的XML配置文件。在SSM(Spring、SpringMVC、MyBatis)框架中,Mapper是数据库操作的主要接口,而...

    spring-boot+tk.mybatis通用mapper

    本教程将深入探讨如何在Spring Boot项目中集成tk.mybatis通用Mapper,实现高效的数据访问。 首先,我们需要理解Spring Boot的核心特性:自动配置。Spring Boot通过扫描类路径并根据存在的依赖来自动配置相应的Bean...

    Mybatis整合通用Dao,Mybatis整合通用Mapper,MyBatis3.x整合通用 Mapper3.5.x

    要整合MyBatis与通用Mapper,我们需要在项目中引入相应的依赖,配置MapperScannerConfigurer扫描Mapper接口,然后在Dao接口上添加通用Mapper的注解,如`@Select`、`@Insert`等。 在实际操作中,我们还需要创建一个...

    TkMybatis通用Mapper逆向工程代码生成工具

    在TkMybatis通用Mapper中,逆向工程指的是根据数据库的表结构自动生成相应的Java实体类、Mapper接口以及XML映射文件,这在数据库驱动的开发模式中非常有用。 使用TkMybatis通用Mapper逆向工程代码生成工具,开发者...

    MyBatis自动生成mapper.xml工具

    mybatis使用虽然灵活简单,但mapper.xml的配置却很繁琐。如果项目的实体表比较多,手工配置是不现实的。这个工具可以帮助自动后成model,dao,mapper.xml 使开发者从繁琐的mapper.xml映射中解放出来,把更多的精力投入...

    MyBatis的helloworld(不使用Mapper接口实现MyBatis查询数据库).zip

    在本示例中,我们将不使用Mapper接口来演示如何通过MyBatis进行基本的数据库查询,这对于理解MyBatis的核心工作原理是非常有帮助的。 首先,MyBatis的核心组件包括XML配置文件、SqlSessionFactory和SqlSession。XML...

    浅谈MyBatis通用Mapper实现原理

    在通用Mapper中,使用了ProviderSqlSource来生成MappedStatement实例,然后再使用StaticSqlSource来生成最终的SQL语句。 StaticSqlSource是MyBatis框架中的一种SqlSource实现,支持在SQL中使用#{param}方式的参数,...

    mybatis-3-mapper.rar

    MyBatis的XML映射文件是配置Mapper接口方法与SQL语句关联的关键部分。每个XML映射文件通常对应一个Mapper接口,其中包含`select`, `insert`, `update`, `delete`等元素,这些元素定义了对应的SQL操作。例如: ```...

    mybatis中的mapper配置文件样例

    简单的mybatis mapper配置文件,包括获取clob字段的配置,取出后将Object强制转化为clob即可使用

    Mybatis_SpringMapper

    4. **Mapper代理**:在Mybatis中,Mapper接口是用于定义数据库操作的方法,而Mapper XML文件则包含了对应的SQL语句。Mybatis的Mapper代理机制允许开发者直接通过Mapper接口调用方法执行SQL,无需关心底层的...

    MyBatis学习笔记(一):MyBatis configuration和mapper xml配置总结

    在MyBatis的学习过程中,理解其配置和Mapper XML文件的设置是至关重要的。本笔记将详细解析MyBatis的configuration配置文件和Mapper XML配置,帮助你深入掌握这两个核心组件。 首先,我们来看MyBatis的`...

    mybatis自动生成mapper、dao和entity配置文件

    mybatis自动生成mapper、dao和entity配置文件,将文件放在classpath路径下

    mybatis自动生成mapper等数据

    "mybatis自动生成mapper等数据"这个主题主要涉及的是MyBatis中的代码自动化生成工具,它可以极大地提高开发效率,减少手动编写重复代码的时间,同时也能降低出错的可能性。 在传统的MyBatis开发中,我们需要手动...

    mybatis-3-mapper.dtd文件下载

    总结来说,`mybatis-3-mapper.dtd` 文件是 Mybatis 中用于验证映射文件语法的 DTD 文件,而 `mybatis-3-config.dtd` 文件则服务于 Mybatis 配置文件。这两个文件确保了 Mybatis 配置和映射文件的正确性,从而保证了...

    mybatis-通用Mapper-逆向工程-代码生成工具

    在MyBatis-通用Mapper中,逆向工程主要应用于根据数据库表结构生成对应的Java类和XML配置文件,减少了手动编写这些基础代码的工作量。 2. **通用Mapper核心组件**: - **Mapper接口**:这是开发者需要定义的接口,...

Global site tag (gtag.js) - Google Analytics