myBatis系列之一:搭建开发环境

myBatis系列之三:增删改查

myBatis系列之四:关联数据的查询

myBatis系列之五:与Spring3集成

myBatis系列之六:与SpringMVC集成

myBatis系列之七:事务管理

myBatis系列之一:搭建开发环境是采用SqlSession的通用方法并强制转换的方式,存在着转换安全的问题:

User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);

可以采用接口加sql语句的方式来解决,sql语句理解为是接口的实现:

1.新建接口类:

package com.john.hbatis.mapper;

import com.john.hbatis.model.User;

public interface IUserMapper {
	User getUserById(int id);
}

2.修改User.xml文件,确保namespace属性值和接口的全限定名相同,且id属性值和接口方法名相同:

<mapper namespace="com.john.hbatis.mapper.IUserMapper">
    <select id="getUserById"

3.在MyBatisBasicTest类中添加测试方法:

@Test
	public void queryInInterfaceWayTest() {
		SqlSession session = sqlSessionFactory.openSession();
		IUserMapper mapper = session.getMapper(IUserMapper.class); // 如果namespace和接口全限定名不一致,报org.apache.ibatis.binding.BindingException: Type interface com..IUserMapper is not known to the MapperRegistry异常。
		User user = mapper.getUserById(1);
		log.info("{}: {}", user.getName(), user.getAddress());
	}

附:

上面的实现是把sql语句放在XML文件中,并通过一定的约束来保证接口能够在XML中找到对应的SQL语句;

还有一种方式是通过接口+注解SQL方式来交互数据:

①.新建接口类:

package com.john.hbatis.mapper;

import org.apache.ibatis.annotations.Select;

import com.john.hbatis.model.User;

public interface IUserMapper2 {
	@Select({ "select * from `user` where id = #{id}" })
	User getUserById(int id);
}

②.在Configuration.xml文件中加入:

<mappers>
	<mapper class="com.john.hbatis.mapper.IUserMapper2" />
</mappers>

或在初始化语句中加入:

sqlSessionFactory.getConfiguration().addMapper(IUserMapper2.class);

③.相应修改上面的测试方法:

IUserMapper2 mapper = session.getMapper(IUserMapper2.class);

参考:

http://www.yihaomen.com/article/java/304.htm