`
snoopy7713
  • 浏览: 1152314 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

sqlSession.getMapper(UserMapper.class)的使用方式

阅读更多

说明:

1,本文采用的Mybatis框架版本为: mybatis-3.0.4.jar

2, 以持久化一个简单的User bean为例

User实体类的代码如下:

 package bean;
     
    public class User {
        private String name;
        private Integer age;
       
        public String getName() {
           return name;
        }
        public void setName(String name) {
           this.name = name;
        }
        public Integer getAge() {
           return age;
        }
        public void setAge(Integer age) {
           this.age = age;
        }
        public User(String name, Integer age) {
           super();
           this.name = name;
           this.age = age;
        }
       
        public User() {
           super();
        }  //必须要有这个无参构造方法,不然根据UserMapper.xml中的配置,在查询数据库时,将不能反射构造出User实例
    } 

 
User实体的映射器取名为UserMapper(接口),其代码如下

   package Mapper;
    import bean.User;
     
    public interface UserMapper {
        public void insertUser(User user);
        public User getUser(String name);
    } 
 

注意,该接口类似于Hibernate中的DAO层接口,唯一不同的是,MyBatis中,只声明该接口就可以,不需要去实现.

UserMapper映射器对应的配置文件如下(相当于Hibernate中的User.hbm.xml,当然这里面不是属性映射字段,而是直接是映射器中各种方法对应的sql语句):

 <?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="Mapper.UserMapper">
    <!-- 这里namespace必须是UserMapper接口的路径,不然要运行的时候要报错 “is not known to the MapperRegistry”-->
        <insert id="insertUser" parameterType="User">
           insert into vincent_user(name,age) values(#{name},#{age})
           <!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 -->
        </insert>
    
        <!-- 这里的id必须和UserMapper接口中的接口方法名相同,不然运行的时候也要报错 -->
        <select id="getUser" resultType="User" parameterType="java.lang.String">
            select * from vincent_user where name=#{name}
        </select>
    </mapper>
 


MyBatis的配置文件这里取名为mybatis-config.xml其配置代码如下(相当与Hibernate的hibernate.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>
        <settings>
            <!-- changes from the defaults for testing -->
            <setting name="cacheEnabled" value="false" />
            <setting name="useGeneratedKeys" value="true" />
            <setting name="defaultExecutorType" value="REUSE" />
        </settings>
        <typeAliases>
           <typeAlias alias="User" type="bean.User"/>
        </typeAliases>
        <environments default="development">
           <environment id="development">
               <transactionManager type="jdbc"/>
               <dataSource type="POOLED">
                  <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                  <property name="url" value="jdbc:oracle:thin:@192.168.56.201:1521:system"/>
                  <property name="username" value="vincent"/>
                  <property name="password" value="1234"/>
               </dataSource>
           </environment>
        </environments>
        <mappers>
            <mapper resource="resource/UserMapper.xml" />
        </mappers>
    </configuration> 
 


加载配置文件得到sqlSessionFactory的工具类

package 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 MyBatisUtil  {
        private  final static SqlSessionFactory sqlSessionFactory;
        static {
           String resource = "resource/mybatis-config.xml";
           Reader reader = null;
           try {
               reader = Resources.getResourceAsReader(resource);
           } catch (IOException e) {
               System.out.println(e.getMessage());
              
           }
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }
       
        public static SqlSessionFactory getSqlSessionFactory() {
           return sqlSessionFactory;
        }
    }

 


测试代码如下:

 package TestMapper;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.junit.Test;
     
    public class TestMapper {
        static SqlSessionFactory sqlSessionFactory = null;
        static {
           sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
        }
       
        @Test
        public void testAdd() {
           SqlSession sqlSession = sqlSessionFactory.openSession();
           try {
               UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
               User user = new User("tom",new Integer(5));
               userMapper.insertUser(user);
               sqlSession.commit();//这里一定要提交,不然数据进不去数据库中
           } finally {
               sqlSession.close();
           }
        }
       
        @Test
        public void getUser() {
           SqlSession sqlSession = sqlSessionFactory.openSession();
           try {
               UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
               User user = userMapper.getUser("jun");
               System.out.println("name: "+user.getName()+"|age: "+user.getAge());
           } finally {
               sqlSession.close();
           }
        }
     
    }
 

 

分享到:
评论

相关推荐

    MyBatis(四)

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.deleteById(id); ``` 3. 提交事务:在MyBatis中,所有操作默认都是在事务中进行的。如果需要保存更改,必须调用`SqlSession`的`commit()`方法...

    weekend:基于 https

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Weekend&lt;User&gt; weekend = Weekend.of(User.class); weekend.weekendCriteria() .andIsNull(User::getId) .andBetween(User::getId,0,10) .andIn...

    使用Mybatis对数据库进行单表操作的实现示例

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; userList = userMapper.selectAll(); return userList; } finally { sqlSession.close(); } } @Repository public int ...

    MyBatis - CRUD+多表联合查询

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class); // CRUD示例 User user = new User(); user.setUsername("testUser"); ...

    Mybatis框架两表案例上课代码.zip

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List&lt;Order&gt; orders = userMapper.selectUserOrders(userId); sqlSession.close(); ``` 这里,`sqlSessionFactory`是一个SqlSessionFactory对象...

    Mybatis框架+Mapper代理

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 执行SQL List&lt;User&gt; users = userMapper.selectAll(); ``` 通过以上步骤,我们可以利用Mybatis的Mapper代理模式轻松地实现对数据库的操作。...

    MyBatis简单实例

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; users = userMapper.selectAllUsers(); ``` 6. **日志信息表的CRUD操作**:对于日志信息表,我们需要实现增、删、改、查四个基本...

    Mybtatis注解开发案例详解.zip

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } ``` 三、注解开发的优势 1. 简洁性:使用注解可以减少...

    02_ibatis教程_查询所有的对象.ra

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; users = mapper.selectAllUsers(); sqlSession.close(); ``` 7. **测试**:编写JUnit测试用例,验证查询所有用户的功能是否正常工作...

    mybatis_test09_mybatis_Mine!_

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.selectUser(1L); ``` MyBatis还支持动态SQL,这使得在XML映射文件中可以编写条件语句,比如IF、WHERE、choose(when/otherwise)...

    MyBatisPlus删除方法deletetById、deleteBatchIds、deleteByMap的使用示例代码

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); int result = mapper.deleteById(1L); // 假设1L是User的主键ID ``` 这里的`result`返回的是受影响的行数,如果删除成功,返回1,否则返回0。 其次...

    ibatis使用及环境搭建文档

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; users = userMapper.selectAllUsers(); sqlSession.close(); ``` **总结** Ibatis作为一款轻量级的ORM框架,提供了灵活的SQL编写...

    Mybatis源码分析.md

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); ``` 2. **执行接口方法**: ```java List&lt;User&gt; users = userMapper.selectAllUsers(); ``` #### 4. 执行mapper接口方法 当获取到`...

    mybatis(入门了解)

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(1, "Jerry", 13); mapper.updateUser(user); sqlSession.commit(); } finally { sqlSession.close(); } ``` #### 五、...

    Mybatis的基本应用

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); ``` Mybatis 还支持动态 SQL,使得 SQL 语句可以根据条件进行拼接。比如,我们可以使用 `&lt;if&gt;`、`&lt;choose&gt;`、`...

    用java程序生成mybatis的mapper.xml和mapper.java文件

    例如,`UserMapper userMapper = sqlSession.getMapper(UserMapper.class);` 6. **动态SQL**:Mybatis的mapper.xml文件支持动态SQL,如if、choose、when、otherwise等标签,可以根据条件动态生成SQL语句,增加了SQL...

    mybatis入门02

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } ``` 对于其他的CRUD操作,如`insert`、`update`和`...

    mybatis框架

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; users = userMapper.selectAllUsers(); for (User user : users) { System.out.println(user.getName()); } sqlSession.close()...

    mybatis 小程序(适合初入门者)

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; users = userMapper.selectAllUsers(); for (User user : users) { System.out.println(user); } } finally { sqlSession....

    Mybatis中文教程

    UserMapper mapper = sqlSession.getMapper(UserMapper.class); List&lt;User&gt; users = mapper.selectAllUsers(); ``` #### 二十、应用目录结构 - **目录结构**:推荐的应用程序目录结构应包括必要的配置文件和资源...

Global site tag (gtag.js) - Google Analytics