MyBatis框架注解开发

1. 注解方式单表的CRUD的操作

  1. SqlMapConfig.xml配置文件



    
    
    
    
    
        
        
        
        
        
        
    
    
    
    
        
        
    
    
    
    
        
        
            
            
            
            
                
                
                
                
                
            
        
    
    
    
    
        
    

     2.UserMapper接口方法和注解的编写

package com.qcby.mapper;
​
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.qcby.domain.User;
​
/**
 * 在MyBatis环境中,UserDao称为UserMapper接口
 * @author Administrator
 */
public interface UserMapper {
    
    @Select(value="select * from user")
    @Results(id="userMap",value= {
        @Result(id=true,column="id",property="id"),
        @Result(column="username",property="username"),
        @Result(column="birthday",property="birthday"),
        @Result(column="sex",property="sex"),
        @Result(column="address",property="address")
    })
    public List findAll();
    
    @Select(value="select * from user where id = #{uid}")
    @ResultMap(value="userMap")
    public User findById(Integer uid);
​
    // 保存
    @Insert(value="insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})")
    public void insert(User user);
    
    // 修改
    @Update("update user set username = #{username},birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id}")
    public void update(User user);
    
    // 删除
    @Delete("delete from user where id = #{id}")
    public void delete(Integer userId);
    
    // 查询数量
    @Select("select count(*) from user")
    public Integer findByCount();
    
    // 模糊查询
    @Select("select * from user where username like #{username}")
    public List findByUsername(String username);
    
}​

     3.UserTest测试方法的编写

package com.qcby.test;
import java.io.InputStream;
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.After;
import org.junit.Before;
import org.junit.Test;
import com.qcby.domain.User;
import com.qcby.mapper.UserMapper;
​
public class UserTest {    
    private InputStream in;
    private SqlSession session;
    SqlSessionFactory factory;
    private UserMapper mapper;
    
    // 初始化的方法
    @Before
    public void init() throws Exception {
        // 加载主配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建工厂对象
        factory = new SqlSessionFactoryBuilder().build(in);
        // 创建session
        session = factory.openSession();
        // 获取到代理对象
        mapper = session.getMapper(UserMapper.class);
    }
    
    // 销毁的方法
    @After
    public void destory() throws Exception {
        // 关闭资源
        session.close();
        in.close();
    }
    
    /**
     * 测试查询
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        // 调用方法
        List list = mapper.findAll();
        for (User user : list) {
            System.out.println(user);
        }
    }
    
    @Test
    public void testFindById() {
        User user = mapper.findById(41);
        System.out.println(user);
    }
    
    /**
     * 保存
     * @throws Exception
     */
    @Test
    public void testInsert() throws Exception {
        // 创建User对象
        User user = new User();
        user.setUsername("美美2");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setAddress("监狱");
        
        // 保存
        mapper.insert(user);
        session.commit();
    }
    
    /**
     * 测试
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        // 先通过id查询
        User user = mapper.findById(41);
        // 设置新的数据内容
        user.setUsername("熊大");
        user.setAddress("深林深处");
        
        // 修改
        mapper.update(user);
        session.commit();
    }
    
    /**
     * 删除
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception {
        mapper.delete(2);
        session.commit();
    }
    
    /**
     * 查询的是聚合函数
     * @throws Exception
     */
    @Test
    public void testFindByCount() throws Exception {
        Integer count = mapper.findByCount();
        System.out.println("总数量:"+count);
    }
    
    /**
     * 模糊查询
     * @throws Exception
     */
    @Test
    public void testFindByUsername() throws Exception {
        // 第一种测试的方式
        List list = mapper.findByUsername("%王%");
        for (User user : list) {
            System.out.println(user);
        }
    }
​
}
​​

2. 多对一的注解查询

 1.多对一立即加载查询(推荐)

  1. AccountMapper接口编写方法和注解
/**
     * 立即加载
     * @return
     */
    @Select("SELECT a.ID AS aid,a.UID,a.MONEY,u.* FROM account a,USER u WHERE a.UID = u.id")
    @Results(value= {
        @Result(id=true,column="aid",property="id"),
        @Result(column="uid",property="uid"),
        @Result(column="money",property="money"),
        @Result(column="id",property="user.id"),
        @Result(column="username",property="user.username"),
        @Result(column="birthday",property="user.birthday"),
        @Result(column="sex",property="user.sex"),
        @Result(column="address",property="user.address")
    })
    public List findAll();

     2.AccountTest进行测试

package com.qcby.test;
import java.io.InputStream;
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.After;
import org.junit.Before;
import org.junit.Test;
import com.qcby.domain.Account;
import com.qcby.mapper.AccountMapper;
​
public class AccountTest {
    
    private InputStream in;
    private SqlSession session;
    private AccountMapper mapper;
    
    // 初始化的方法
    @Before
    public void init() throws Exception {
        // 加载主配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建session
        session = factory.openSession();
        // 获取到代理对象
        mapper = session.getMapper(AccountMapper.class);
    }
    
    // 销毁的方法
    @After
    public void destory() throws Exception {
        // 关闭资源
        session.close();
        in.close();
    }
    
    /**
     * 测试查询
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        // 调用方法
        List list = mapper.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }
}

 2.多对一延迟加载查询

  1. AccountMapper编写方法和注解
/**
     * 延迟加载
     * @return
     */
    @Select("select * from account")
    @Results(value= {
        @Result(id=true,column="aid",property="id"),
        @Result(column="uid",property="uid"),
        @Result(column="money",property="money"),
        @Result(property="user",javaType=User.class,column="uid",one=@One(select="com.qcby.mapper.UserMapper.findById",fetchType=FetchType.LAZY))
    })
    public List findAll();   

     2.UserMapper接口编写方法

@Select(value="select * from user where id = #{uid}")
 public User findById(Integer uid);

     3.测试

package com.qcby.test;
import java.io.InputStream;
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.After;
import org.junit.Before;
import org.junit.Test;
import com.qcby.domain.Account;
import com.qcby.mapper.AccountMapper;
​
public class AccountTest {    
    private InputStream in;
    private SqlSession session;
    private AccountMapper mapper;
    
    // 初始化的方法
    @Before
    public void init() throws Exception {
        // 加载主配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建工厂对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建session
        session = factory.openSession();
        // 获取到代理对象
        mapper = session.getMapper(AccountMapper.class);
    }
    
    // 销毁的方法
    @After
    public void destory() throws Exception {
        // 关闭资源
        session.close();
        in.close();
    }
    
    /**
     * 测试查询
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        // 调用方法
        List list = mapper.findAll();
        for (Account account : list) {
            System.out.println(account.getMoney());
            System.out.println(account.getUser());
        }
    }
    
}​

3. 一对多的注解查询

        1.一对多查询,使用延迟加载的方式查询

        2.UserMapper接口编写方法

/**
     * 查询用户,延迟加载用户下的所有的账号
     * @return
     */
    @Select(value="select * from user")
    @Results(id="userMap",value= {
        @Result(id=true,column="id",property="id"),
        @Result(column="username",property="username"),
        @Result(column="birthday",property="birthday"),
        @Result(column="sex",property="sex"),
        @Result(column="address",property="address"),
        @Result(property="accounts",column="id",many=@Many(select="com.qcby.mapper.AccountMapper.findByUid",fetchType=FetchType.LAZY))
    })
    public List findAll(); 

     3.测试

/**
     * 测试查询
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        // 调用方法
        List list = mapper.findAll();
        for (User user : list) {
            System.out.println(user.getUsername());
            System.out.println(user.getAccounts());
        }
    }

你可能感兴趣的:(mybatis)