• MyBatis -- 对表进行增删改查(基于注解的实现)


    1、MyBatis对数据库表进行增/删/改/查

    前一篇使用基于XML的方式实现对数据库的增/删/改/查

    以下我们来看怎么使用注解的方式实现对数据库表的增/删/改/查

    1.1  首先须要定义映射sql的接口。代码例如以下:

    package org.guus.inter;
    
    import java.util.List;
    
    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 org.guus.bean.User;
    
    /**
     * 
     * @描写叙述:定义sql映射的接口,使用注解指明方法要运行的SQL
     * @author Guus
     * @date 2015年8月7日
     */
    public interface UserMapperInterface {
    
        //使用@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();
    }
    
    1.2  接着须要在mybatis-config.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="2015" /> </dataSource> </environment> </environments> <mappers> <!-- 注冊userMapper.xml文件, userMapper.xml位于org.guus.mapping这个包下, 所以resource写成org/guus/mapping/userMapper.xml --> <mapper resource="org/guus/mapping/userMapper.xml" /> <!-- 注冊UserMapper映射接口--> <mapper class="org.guus.inter.UserMapperInterface"/> </mappers> </configuration>

    1.3  以下我们编写測试类进行測试 ,測试类中用的SessionUtil是一个获取Session的工具类,详细见:MyBatis -- 对表进行增删改查(基于XML的实现)

    package org.guus.test;
    
    import java.io.IOException;
    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.guus.bean.User;
    import org.guus.inter.UserMapperInterface;
    import org.guus.utils.SessionUtil;
    import org.junit.Test;
    
    /**
     * 
     * @描写叙述:測试MyBatis的CURD操作  -- 基于注解
     * @author Guus
     * @date 2015年8月7日
     */
    public class TestCURD2 {
    
        @Test
        public void Add() throws IOException{
            SqlSession sqlSession = SessionUtil.getSqlSession(true);  //true代表自己主动提交事务
            //得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来
            UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
            User user = new User();
            user.setName("Guus3");
            user.setAge(3);
            //运行插入操作
            int retResult = mapper.add(user);
            //使用SqlSession运行完SQL之后须要关闭SqlSession
            sqlSession.close();
            System.out.println("Add操作返回值----> "+retResult);
        }
        
        @Test
        public void Update() throws IOException{
            SqlSession sqlSession = SessionUtil.getSqlSession(true);
            UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
            User user = new User();
            user.setId(3);
            user.setName("Guus333");
            user.setAge(4);
            //运行改动操作
            int retResult = mapper.update(user);
            sqlSession.close();
            System.out.println("Update操作返回值----> "+retResult);
        }
        
        @Test
        public void Delete() throws IOException{
            SqlSession sqlSession = SessionUtil.getSqlSession(true);
            UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
            //运行删除操作
            int retResult = mapper.deleteById(2);
            sqlSession.close();
            System.out.println("Delete操作返回值----> "+retResult);
        }
        
        @Test
        public void GetAll() throws IOException{
            SqlSession sqlSession = SessionUtil.getSqlSession();
            UserMapperInterface mapper = sqlSession.getMapper(UserMapperInterface.class);
            //运行查询操作。将查询结果自己主动封装成List<User>返回
            List<User> lstUsers = mapper.getAll();
            sqlSession.close();
            System.out.println("GetAll操作返回值----> "+lstUsers);
        }
    }
    1.4  測试结果:

  • 相关阅读:
    51 张图助你彻底掌握 HTTP
    Nginx从原理到实战
    vu3.0 + ts + swiper6 的问题
    使用 react-router-dom v5 查询query 参数的方法
    visual studio 2015配置SVN
    SVN使用教程总结
    C#与SAP进行数据交互
    shell csv/txt文件对比
    persto array_join(array_agg(),',')
    shell 拼接html table 发送邮件
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/6875422.html
Copyright © 2020-2023  润新知