一、原始Dao层开发
userMapper.xml数据库映射文件配置
<?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="com.mark.mapping.userMapper">
<!--
根据id查询得到一个user对象
-->
<select id="getUserById" parameterType="int" resultType="com.mark.domain.User">
select * from `user` where id=#{id}
</select>
<insert id="insertUser" parameterType="com.mark.domain.User">
insert into `user`
(`id`,
`username`,
`birthday`,
`sex`,
`address`)
values(#{id},
#{username},
#{birthday},
#{sex},
#{address});
</insert>
</mapper>
1.UserDaoI接口
public interface UserDao {
/**根据用户ID查询用户信息
* @param id
* @return
*/
User getUserById(Integer id);
/**
* 添加用户
* @param user
*/
void insertUser(User user);
}
2.UserDaoImpl接口实现类
public class UserDaoImpl implements UserDao {
@Override
public User getUserById(Integer id) {
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
User user = sqlSession.selectOne("com.mark.mapping.userMapper.getUserById", id);
sqlSession.close();
return user;
}
@Override
public void insertUser(User user) {
SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
sqlSession.insert("com.mark.mapping.userMapper.insertUser", user);
sqlSession.commit();
sqlSession.close();
}
}
二、接口动态代理(不需要自己写Dao层接口实现类)
采用Mapper动态代理方法只需要编写相应的Dao层对应xxxMapper接口,那么Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体等同于Dao接口实现类方法
1.Mapper接口开发需要遵循以下规范
1. xxxMapper.xml文件中的namespace与Dao层对应mapper接口的全路径类名相同
2. Dao层对应mapper接口方法名和xxxMapper.xml中定义的每个statement的id相同
3. Dao层对应mapper接口方法的输入参数类型和xxxMapper.xml中定义的每个sql 的parameterType的类型相同
4. Dao层对应mapper接口方法的输出参数类型和xxxMapper.xml中定义的每个sql的resultType的类型相同
2.Dao层UserDaoI接口(遵循以上规则)
public interface UserDao {
/**根据用户ID查询用户信息
* @param id
* @return
*/
User getUserById(Integer id);
/**
* 添加用户
* @param user
*/
void insertUser(User user);
}
3.获取接口代理实现类调用方法
//获取接口代理实现类
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用具体方法
User user = mapper.getUserById(10);