一. 接口方式
1.创建接口
public interface UserDao {
User selectUserById(int id);
}
2.User.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.souke.mybatis.dao.UserDao">
<select id="selectUserById" parameterType="int" resultType="User">
select * from user where id = #{id}
</select>
</mapper>
3.测试
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
User user = userDao.selectUserById(1);
System.out.println(user.getName());
session.close();
}
ps:User.xml 中的namepace路径要设置成UserDao的路径。
二.注解方式
1.创建接口
public interface UserDao {
@Select("select * from user where id = #{id}")
User selectUserById(int id);
}
2.测试
public static void main(String[] args) {
sqlSessionFactory.getConfiguration().addMapper(UserDao.class);
SqlSession session = sqlSessionFactory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
User user = userDao.selectUserById(1);
System.out.println(user.getName());
session.close();
}
ps:User.xml不需要。这样子就可以进行正常运行,显示结果。