使用MyBatis对表执行增删改查操作——基于注解的实现

上篇博文的基于xml配置的只要学会了,原理搞清楚了,那么注解的方式更是随意学会,因为注解就是为了简化配置,甚至是不需要xml文件配置的。

下面是装载别人的一个注解项目,可以参考改动:

1、定义sql映射的接口

    package me.gacl.mapping;  
      
    import java.util.List;  
    import me.gacl.domain.User;  
    import org.apache.ibatis.annotations.Delete;  
    import org.apache.ibatis.annotations.Insert;  
    import org.apache.ibatis.annotations.Select;  
    import org.apache.ibatis.annotations.Update;  
      
    /** 
     * @author gacl 
     * 定义sql映射的接口,使用注解指明方法要执行的SQL 
     */  
    public interface UserMapperI {  
      
        //使用@Insert注解指明add方法要执行的SQL  
        @Insert("insert into users(name, age) values(#{name}, #{age})")  
        public int add(User user);  
          
        //使用@Delete注解指明deleteById方法要执行的SQL  
        @Delete("delete from users where id=#{id}")  
        public int deleteById(int id);  
          
        //使用@Update注解指明update方法要执行的SQL  
        @Update("update users set name=#{name},age=#{age} where id=#{id}")  
        public int update(User user);  
          
        //使用@Select注解指明getById方法要执行的SQL  
        @Select("select * from users where id=#{id}")  
        public User getById(int id);  
          
        //使用@Select注解指明getAll方法要执行的SQL  
        @Select("select * from users")  
        public List<User> getAll();  
    }  

2、在 conf.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>  
        <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/mybatis" />  
                    <property name="username" value="root" />  
                    <property name="password" value="XDP" />  
                </dataSource>  
            </environment>  
        </environments>  
          
        <mappers>  
            <!-- 注册userMapper.xml文件,   
            userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->  
            <mapper resource="me/gacl/mapping/userMapper.xml"/>  
            <!-- 注册UserMapper映射接口-->  
            <mapper class="me.gacl.mapping.UserMapperI"/>  
        </mappers>  
          
    </configuration>  

3.测试类方法:

    package me.gacl.test;  
      
    import java.util.List;  
    import me.gacl.domain.User;  
    import me.gacl.mapping.UserMapperI;  
    import me.gacl.util.MyBatisUtil;  
    import org.apache.ibatis.session.SqlSession;  
    import org.junit.Test;  
      
    public class TestCRUDByAnnotationMapper {  
      
        @Test  
        public void testAdd(){  
            SqlSession sqlSession = MyBatisUtil.getSqlSession(true);  
            //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来  
            UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);  
            User user = new User();  
            user.setName("用户xdp");  
            user.setAge(20);  
            int add = mapper.add(user);  
            //使用SqlSession执行完SQL之后需要关闭SqlSession  
            sqlSession.close();  
            System.out.println(add);  
        }  
          
        @Test  
        public void testUpdate(){  
            SqlSession sqlSession = MyBatisUtil.getSqlSession(true);  
            //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来  
            UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);  
            User user = new User();  
            user.setId(3);  
            user.setName("孤傲苍狼_xdp");  
            user.setAge(26);  
            //执行修改操作  
            int retResult = mapper.update(user);  
            //使用SqlSession执行完SQL之后需要关闭SqlSession  
            sqlSession.close();  
            System.out.println(retResult);  
        }  
          
        @Test  
        public void testDelete(){  
            SqlSession sqlSession = MyBatisUtil.getSqlSession(true);  
            //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来  
            UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);  
            //执行删除操作  
            int retResult = mapper.deleteById(7);  
            //使用SqlSession执行完SQL之后需要关闭SqlSession  
            sqlSession.close();  
            System.out.println(retResult);  
        }  
          
        @Test  
        public void testGetUser(){  
            SqlSession sqlSession = MyBatisUtil.getSqlSession();  
            //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来  
            UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);  
            //执行查询操作,将查询结果自动封装成User返回  
            User user = mapper.getById(8);  
            //使用SqlSession执行完SQL之后需要关闭SqlSession  
            sqlSession.close();  
            System.out.println(user);  
        }  
          
        @Test  
        public void testGetAll(){  
            SqlSession sqlSession = MyBatisUtil.getSqlSession();  
            //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来  
            UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);  
            //执行查询操作,将查询结果自动封装成List<User>返回  
            List<User> lstUsers = mapper.getAll();  
            //使用SqlSession执行完SQL之后需要关闭SqlSession  
            sqlSession.close();  
            System.out.println(lstUsers);  
        }  
    }  

4.一个原作者封装的MyBatisUtil工具类:

    package me.gacl.util;  
      
    import java.io.InputStream;  
      
    import org.apache.ibatis.session.SqlSession;  
    import org.apache.ibatis.session.SqlSessionFactory;  
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
      
    public class MyBatisUtil {  
      
        /** 
         * 获取SqlSessionFactory 
         * @return SqlSessionFactory 
         */  
        public static SqlSessionFactory getSqlSessionFactory() {  
            String resource = "conf.xml";  
            InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);  
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);  
            return factory;  
        }  
          
        /** 
         * 获取SqlSession 
         * @return SqlSession 
         */  
        public static SqlSession getSqlSession() {  
            return getSqlSessionFactory().openSession();  
        }  
          
        /** 
         * 获取SqlSession 
         * @param isAutoCommit  
         *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 
         *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务 
         * @return SqlSession 
         */  
        public static SqlSession getSqlSession(boolean isAutoCommit) {  
            return getSqlSessionFactory().openSession(isAutoCommit);  
        }  
    }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值