您的位置:首页 > 移动开发

MyBatis Mapper代理实现DAO

2015-11-15 13:15 417 查看

 

mapper接口遵循的开发约定

1、mapper.xml中namespace属性等于mapper接口的地址

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

3、mapper接口中的方法参数类型和mapper.xml中的statement的parameterType类型一致

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

 

 

sqlMapConfig.xml中加载配置采用包扫描的方式,定义别名也采用包扫描的方式

<typeAliases>
<package name="entity" />
</typeAliases>
<mappers>
<package name="mapper"/>
</mappers>

 

定义mapper接口,接口的参数和返回值需要和mapper.xml文件中的parameterType、resutlType一致

public interface IUserMapper {
public User findUserById(User entity);
public List<User> findAll();
}

创建配置文件,namespace的名称和IUserMapper接口的全路径名一致

<mapper namespace="mapper.IUserMapper">
<select id="findAll" resultType="entity.User">
select * from user
</select>

<select id="findUserById" parameterType="entity.User" resultType="entity.User">
select * from user where id=#{id}
</select>
</mapper>

 测试类

public class TestMapperDAO {
public static final String RESOURCE = "sqlMapConfig.xml"; // 配置文件
SqlSessionFactory sqlSessionFactory;// Session工厂

@Before
public void initFactory() throws IOException {
InputStream in = Resources.getResourceAsStream(RESOURCE);// 配置文件的输入流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); // 获得sqlSessionFactory
}

@Test
public void testFindAll() {
SqlSession session = sqlSessionFactory.openSession();
IUserMapper mapper = session.getMapper(IUserMapper.class);
User u = new User();
u.setId("1");
User user = mapper.findUserById(u);
System.out.println(user);

List<User> users = mapper.findAll();
System.out.println(users);
}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: