Mybatis使用接口Mapper进行CRUD

package com.mybatis.inteface;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.mybatis.pojo.User;

public interface UserInterface {

   //根据表名查询用户信息(直接使用注解指定传入参数名称)
   //There is no getter for property named 'tableName' in 'class java.lang.String'
   //public List<User> queryUserByTableName(String tableName);
   public List<User> queryUserByTableName(@Param("tableName") String tableName);
   
   //使用注解指定传入参数名称
   //public User login(String userName, String password);
   public User login(@Param("userName") String userName, @Param("password") String password);

   public User queryUserById(Integer id);

   public List<User> queryUserByIds(List<Integer> ids);
   
   public List<User> queryUserAll();

   public void insertUser(User user);
   
   public void insertUserList(List<User> users);

   public void updateUser(User user);
   
   public void updateUserList(List<User> users);
  
   public void deleteUserById(Integer id);

}
<?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 namespace="com.mybatis.inteface.UserInterface">
    <!--
       1.#{},预编译的方式preparedstatement,使用占位符替换,防止sql注入,一个参数的时候,任意参数名可以接收
       2.${},普通的Statement,字符串直接拼接,不可以防止sql注入,一个参数的时候,必须使用${value}接收参数
     -->
    <select id="queryUserByTableName" resultType="com.mybatis.pojo.User">
        <!--select * from ${tableName} fail-->
        <!--select * from #{tableName} fail-->
        <!--select * from #{param1} fail-->
        <!--select * from ${param1} success-->
        select t.id as id,t.user_name as userName,t.password as password,
		t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
		t.created as created,t.updated as updated
		from ${tableName}  t	
    </select>

    <select id="login" resultType="com.mybatis.pojo.User">
       <!--select * from tb_user where user_name = #{userName} and password = #{password} fail-->
       <!--select * from tb_user where user_name = #{0} and password = #{1}  success-->
       <!-- select * from tb_user where user_name = #{param1} and password = #{param2} success-->
        select t.id as id,t.user_name as userName,t.password as password,
		t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
		t.created as created,t.updated as updated
        from tb_user t where t.user_name = #{userName} and t.password = #{password}
    </select>

    <!-- statement,内容:sql语句。
       id:唯一标识,在同一个命名空间下保持唯一,使用动态代理之后要求和方法名保持一致
       resultType:sql语句查询结果集的封装类型,使用动态代理之后和方法的返回类型一致;resultMap:二选一
       parameterType:参数的类型,使用动态代理之后和方法的参数类型一致
     -->
    <select id="queryUserById" resultType="com.mybatis.pojo.User" parameterType="int">
        select t.id as id,t.user_name as userName,t.password as password,
		t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
		t.created as created,t.updated as updated 
        from tb_user t where t.id = #{id}
    </select>
    
     <select id="queryUserByIds" resultType="com.mybatis.pojo.User" parameterType="java.util.List">
        select t.id as id,t.user_name as userName,t.password as password,
		t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
		t.created as created,t.updated as updated 
        from tb_user t where t.id in 
        <foreach collection="list" item="id" open="(" close=")" separator=",">
		       #{id}
		 </foreach> 
    </select>
    
    <select id="queryUserAll" resultType="com.mybatis.pojo.User">
        select t.id as id,t.user_name as userName,t.password as password,
		t.name as name,t.age as age, t.birthday as birthday,t.sex as sex,
		t.created as created,t.updated as updated 
        from tb_user t 
    </select>
    <!-- 新增的Statement
       id:唯一标识,在同一个命名空间下保持唯一,使用动态代理之后要求和方法名保持一致
       parameterType:参数的类型,使用动态代理之后和方法的参数类型一致
       useGeneratedKeys:开启主键回写
       keyColumn:指定数据库的主键
       keyProperty:主键对应的pojo属性名
     -->
    <insert id="insertUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id"
            parameterType="com.mybatis.pojo.User">
        insert into tb_user 
        (id,user_name,password,name,age,sex,birthday,created,updated)
        values
        (#{id},#{userName},#{password},#{name},#{age},#{sex},#{birthday},sysdate,sysdate)
    </insert>
    
    <insert id="insertUserList" parameterType="java.util.List">
        insert into tb_user 
        (id,user_name,password,name,age,sex,birthday,created,updated)
        select id,user_name,password,name,age,sex,birthday,created,updated
        from (
        <foreach collection="list" item="item" index="index" separator="UNION ALL">
            select #{item.id} as id,#{item.userName} as user_name,#{item.password} as password,
            #{item.name} as name,#{item.age} as age,#{item.sex} as sex,
            #{item.birthday} as birthday,sysdate as created,sysdate as updated
            from dual
        </foreach>
        ) A
    </insert>
    
    <update id="updateUser" parameterType="com.mybatis.pojo.User">
        update tb_user
        <trim prefix="set" suffixOverrides=",">
            <if test="userName!=null">user_name = #{userName},</if>
            <if test="password!=null">password = #{password},</if>
            <if test="name!=null">name = #{name},</if>
            <if test="age!=null">age = #{age},</if>
            <if test="sex!=null">sex = #{sex},</if>
            <if test="birthday!=null">birthday = #{birthday},</if>
            updated = sysdate,
        </trim>
        where id = #{id}
    </update>
    
    <update id="updateUserList" parameterType="java.util.List">
       <foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";">
            update tb_user
            <set>
                <if test="item.userName!=null">user_name = #{item.userName},</if>
	            <if test="item.password!=null">password = #{item.password},</if>
	            <if test="item.name!=null">name = #{item.name},</if>
	            <if test="item.age!=null">age = #{item.age},</if>
	            <if test="item.sex!=null">sex = #{item.sex},</if>
	            <if test="item.birthday!=null">birthday = #{item.birthday},</if>
	            updated = sysdate,
            </set>
            where id = #{item.id}
        </foreach>
    </update>
    <delete id="deleteUserById" parameterType="java.lang.Integer">
        delete from tb_user where id=#{id}
    </delete>
</mapper>
package com.mybatis.pojo;

import java.util.Date;

public class User {

    private Integer id;
    private String userName;//数据库字段名user_name
    private String password;
    private String name;
    private Integer age;
    private Integer sex;
    private Date birthday;
    private String created;
    private String updated;
    
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	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 Integer getSex() {
		return sex;
	}
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getCreated() {
		return created;
	}
	public void setCreated(String created) {
		this.created = created;
	}
	public String getUpdated() {
		return updated;
	}
	public void setUpdated(String updated) {
		this.updated = updated;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", password="
				+ password + ", name=" + name + ", age=" + age + ", sex=" + sex
				+ ", birthday=" + birthday + ", created=" + created
				+ ", updated=" + updated + "]";
	}

}
package com.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.Before;
import org.junit.Test;
import com.mybatis.inteface.UserInterface;
import com.mybatis.pojo.User;

public class UserDaoTest {
	
    public UserInterface userInterface;
    
    @Before
    public void setUp(){
    	
    	try {
            // 指定配置文件
            String resource = "mybatis-config.xml";
            // 读取配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 构建sqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            // 获取sqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            // 1. 映射文件的命名空间(namespace)必须是mapper接口的全路径
            // 2. 映射文件的statement的id必须和mapper接口的方法名保持一致
            // 3. Statement的resultType必须和mapper接口方法的返回类型一致
            // 4. statement的parameterType必须和mapper接口方法的参数类型一致(不一定)
            this.userInterface = sqlSession.getMapper(UserInterface.class);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    @Test
    public void testQueryUserByTableName() {
        List<User> userList = this.userInterface.queryUserByTableName("tb_user");
        for (User user : userList) {
            System.out.println(user);
        }
    }

    @Test
    public void testLogin() {
        System.out.println(this.userInterface.login("jingjing", "123456"));
    }

    @Test
    public void testQueryUserById() {
        System.out.println(this.userInterface.queryUserById(2));
    }
    
    @Test
    public void testQueryUserByIds() {
    	
    	List<Integer> ids = new ArrayList<Integer>();
    	ids.add(1);
    	ids.add(2);
    	ids.add(3);
        List<User> userList = this.userInterface.queryUserByIds(ids);
        for (User user : userList) {
            System.out.println(user);
        }
    }

    @Test
    public void testQueryUserAll() {
        List<User> userList = this.userInterface.queryUserAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }

    @Test
    public void testInsertUser() {
        User user = new User();
        user.setId(3);
        user.setAge(20);
        user.setBirthday(new Date());
        user.setName("大神");
        user.setPassword("123456");
        user.setSex(2);
        user.setUserName("bigGod222");
        this.userInterface.insertUser(user);
        System.out.println(user.getId());
    }

    @Test
    public void testInsertUserList() {
        User user10 = new User();
        user10.setId(10);
        user10.setAge(20);
        user10.setBirthday(new Date());
        user10.setName("大神");
        user10.setPassword("123456");
        user10.setSex(2);
        user10.setUserName("bigGod111");
        
        User user20 = new User();
        user20.setId(20);
        user20.setAge(40);
        user20.setBirthday(new Date());
        user20.setName("大力神");
        user20.setPassword("123456");
        user20.setSex(2);
        user20.setUserName("bigGod222");
        
        List<User> users = new ArrayList<User>();
        users.add(user10);
        users.add(user20);
        
        this.userInterface.insertUserList(users);
    }
    
    @Test
    public void testUpdateUser() {
        User user = new User();
        user.setId(1);
        user.setBirthday(new Date());
        user.setName("静静");
        user.setPassword("123456");
        user.setSex(0);
        user.setUserName("Jinjin");
        this.userInterface.updateUser(user);
    }

    @Test
    public void testupdateUserList() {
        User user1 = new User();
        user1.setId(1);
        user1.setName("name11");
        user1.setUserName("username11");
        
        User user2 = new User();
        user2.setId(2);
        user2.setName("name22");
        user2.setUserName("username22");
        
        List<User> users = new ArrayList<User>();
        users.add(user1);
        users.add(user2);
        this.userInterface.updateUserList(users);
    }
    
    @Test
    public void testDeleteUserById() {
        this.userInterface.deleteUserById(1);
    }
}
log4j.rootLogger=DEBUG,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%l] [%p]:%m%n
<?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>
	<properties>
		<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
		<property name="username" value="system"/>
	    <property name="password" value="bruce123"/>
   </properties>

   <!-- 环境,可以配置多个,default:指定采用哪个环境 -->
   <environments default="development">
      <!-- id:唯一标识 -->
      <environment id="test">
         <!-- 事务管理器,JDBC类型的事务管理器 -->
         <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/mybatis-110" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
         </dataSource>
      </environment>
      <environment id="development">
         <!-- 事务管理器,JDBC类型的事务管理器 -->
         <transactionManager type="JDBC" />
         <!-- 数据源,池类型的数据源 -->
         <dataSource type="POOLED">
            <property name="driver" value="${driver}" /> <!-- 配置了properties,所以可以直接引用 -->
            <property name="url" value="${url}" />
            <property name="username" value="${username}" />
            <property name="password" value="${password}" />
         </dataSource>
      </environment>
   </environments>
   <mappers>
     <mapper resource="com/mybatis/mapper/UserMapper.xml" />
   </mappers>
  </configuration>
发布了132 篇原创文章 · 获赞 64 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/qiuzhi__ke/article/details/104154278