Mybatis步步进阶(六)——Mybatis Mapper代理和逆向工程

一、原始的开发方式

以dao层为例,业务处理过程如下:

1、Dao实现类

public class UserDaoImpl implements UserDao {

	// 需要向dao实现类中注入SqlSessionFactory
	// 这里通过构造方法注入
	private SqlSessionFactory sqlSessionFactory;

	public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	@Override
	public User findUserById(int id) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = sqlSession.selectOne("test.findUserById", id);
		// 释放资源
		sqlSession.close();
		return user;
	}

	@Override
	public void insertUser(User user) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//执行插入操作
		sqlSession.insert("test.insertUser", user);
		// 提交事务
		sqlSession.commit();
		// 释放资源
		sqlSession.close();
	}

2、测试类 

public class UserMapperTest {
	private SqlSessionFactory sqlSessionFactory;
	// 此方法是在执行testFindUserById之前执行
	@Before
	public void setUp() throws Exception {
		// 创建sqlSessionFactory
		// mybatis配置文件
		String resource = "SqlMapConfig.xml";
		// 得到配置文件流
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 创建会话工厂,传入mybatis的配置文件信息
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	@Test
	public void testFindUserById() throws Exception {		
		SqlSession sqlSession = sqlSessionFactory.openSession();		
		//创建UserMapper对象,mybatis自动生成mapper代理对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);		
		//调用userMapper的方法		
		User user = userMapper.findUserById(1);		
		System.out.println(user);
		
	}

3、原始方式的弊端

1)每个方法中重复出现opensession、closesession方法调用

2)selectone、insert方法的参数采用泛型传入,即便传入参数类型错误,也会先执行select,执行过程中再类型错误,无法提前对参数类型进行检查

二、Mybatis Mapper代理类 

Mybatis提供了使用Mapper接口自动生成实现类的代理对象,只需要在配置Mapper.xml遵循Mybatis提供的开发规范:

1、在mapper.xml中namespace等于mapper接口地址

2、mapper.java接口中的方法名和mapper.xml中statement的id一致

3、mapper.java接口中的方法输入参数类型和mapper.xml中statement的parameterType指定的类型一致。

4、mapper.java接口中的方法返回值类型和mapper.xml中statement的resultType指定的类型一致。

mapper配置:



	
接口编写:

package cn.itcast.ssm.mapper;
public interface UserMapper {	
	//根据id查询用户信息
	public User findUserById(int id) throws Exception;
}
测试类:

public class UserMapperTest {
	private SqlSessionFactory sqlSessionFactory;
	// 此方法是在执行testFindUserById之前执行
	@Before
	public void setUp() throws Exception {
		// 创建sqlSessionFactory
		// mybatis配置文件
		String resource = "SqlMapConfig.xml";
		// 得到配置文件流
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 创建会话工厂,传入mybatis的配置文件信息
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
	}
	@Test
	public void testFindUserById() throws Exception {		
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//创建UserMapper对象,mybatis自动生成mapper代理对象
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);		
		//调用userMapper的方法		
		User user = userMapper.findUserById(1);		
	}
}
注:代理对象的内部调用,通过getMapper()中传入调用类(UserMapper.class 接口),直接调用接口的find方法,通过返回值是单个pojo还是List来判断调用selectone或是selectList方法。
三、Mybatis 逆向工程

     Mybatis的逆向工程就是运用了mapper代理的方式,通过配置db的表字段,根据数据库生成对单个表操作的service接口、mapper配置、pojo实体。generatorConfig.xml配置文件如下:


	
		
			
			
		
		
		
		
		

		
		
			
		

		
		
			
			
			
			
		
        
		
			
			
		
		
		
			
			
		
		
		
java类

public class GeneratorSqlmap {
	public void generator() throws Exception{
		List warnings = new ArrayList();
		boolean overwrite = true;
		//指定 逆向工程配置文件
		File configFile = new File("generatorConfig.xml"); 
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
				callback, warnings);
		myBatisGenerator.generate(null);

	} 
	public static void main(String[] args) throws Exception {
		try {
			GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
生成的pojo和pojo扩展类

public class Items {
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    private Date createtime;
    private String detail;
}
//扩展类
public class ItemsExample {
    protected String orderByClause;
    protected boolean distinct;
    protected List oredCriteria;
}
逆向工程生成的Itemmapper.xml配置




  
    
    
    
    
    
  
  
    
  
  
    
      
        
          
            
              
                
                  and ${criterion.condition}
                
                
                  and ${criterion.condition} #{criterion.value}
                
                
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                
                
                  and ${criterion.condition}
                  
                    #{listItem}
                  
                
              
            
          
        
      
    
  
  
    
      
        
          
            
              
                
                  and ${criterion.condition}
                
                
                  and ${criterion.condition} #{criterion.value}
                
                
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                
                
                  and ${criterion.condition}
                  
                    #{listItem}
                  
                
              
            
          
        
      
    
  
  
    id, name, price, pic, createtime
  
  
    detail
  
  
  
  
  
    delete from items
    where id = #{id,jdbcType=INTEGER}
  
  
    delete from items
    
      
    
  
  
    insert into items (id, name, price, 
      pic, createtime, detail
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{price,jdbcType=REAL}, 
      #{pic,jdbcType=VARCHAR}, #{createtime,jdbcType=TIMESTAMP}, #{detail,jdbcType=LONGVARCHAR}
      )
  
  
    insert into items
    
      
        id,
      
      
        name,
      
      
        price,
      
      
        pic,
      
      
        createtime,
      
      
        detail,
      
    
    
      
        #{id,jdbcType=INTEGER},
      
      
        #{name,jdbcType=VARCHAR},
      
      
        #{price,jdbcType=REAL},
      
      
        #{pic,jdbcType=VARCHAR},
      
      
        #{createtime,jdbcType=TIMESTAMP},
      
      
        #{detail,jdbcType=LONGVARCHAR},
      
    
  
  
  
    update items
    
      
        id = #{record.id,jdbcType=INTEGER},
      
      
        name = #{record.name,jdbcType=VARCHAR},
      
      
        price = #{record.price,jdbcType=REAL},
      
      
        pic = #{record.pic,jdbcType=VARCHAR},
      
      
        createtime = #{record.createtime,jdbcType=TIMESTAMP},
      
      
        detail = #{record.detail,jdbcType=LONGVARCHAR},
      
    
    
      
    
  
  
    update items
    set id = #{record.id,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      price = #{record.price,jdbcType=REAL},
      pic = #{record.pic,jdbcType=VARCHAR},
      createtime = #{record.createtime,jdbcType=TIMESTAMP},
      detail = #{record.detail,jdbcType=LONGVARCHAR}
    
      
    
  
  
    update items
    set id = #{record.id,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      price = #{record.price,jdbcType=REAL},
      pic = #{record.pic,jdbcType=VARCHAR},
      createtime = #{record.createtime,jdbcType=TIMESTAMP}
    
      
    
  
  
    update items
    
      
        name = #{name,jdbcType=VARCHAR},
      
      
        price = #{price,jdbcType=REAL},
      
      
        pic = #{pic,jdbcType=VARCHAR},
      
      
        createtime = #{createtime,jdbcType=TIMESTAMP},
      
      
        detail = #{detail,jdbcType=LONGVARCHAR},
      
    
    where id = #{id,jdbcType=INTEGER}
  
  
    update items
    set name = #{name,jdbcType=VARCHAR},
      price = #{price,jdbcType=REAL},
      pic = #{pic,jdbcType=VARCHAR},
      createtime = #{createtime,jdbcType=TIMESTAMP},
      detail = #{detail,jdbcType=LONGVARCHAR}
    where id = #{id,jdbcType=INTEGER}
  
  
    update items
    set name = #{name,jdbcType=VARCHAR},
      price = #{price,jdbcType=REAL},
      pic = #{pic,jdbcType=VARCHAR},
      createtime = #{createtime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  



你可能感兴趣的:(Mybatis)