使用mapper的方法进行Mybatis的实例测试
1.首先需要导入Mybatis 和mysql的jar包。
2.创建Mybatis.xml,配置Mybatis的数据源
<!-- 加载属性文件 -->
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<!-- 使用JDBC事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接处,配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
3.配置UserMapper.xml文件,该文件用来编写SQL语句
<mapper namespace="xiaoying.sun.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="xiaoying.sun.model.User">
select * from user where id = #{id}
</select>
</mapper>
该配置是根据Id查询用户信息,同时需要编写User的pojo类。
最后UserMapper.xml文件文件编写好后,需要把该文件加载到Mybatis.xml文件中
<mappers>
<mapper resource="xiaoying/sun/mapper/UserMapper.xml"/>
</mappers>
4.根据 id="selectUserById"来编写Mapper接口
public interface UserMapper {
public User selectUserById(int id);
}
5.最后需要测试,执行查询语句:
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
String resource="mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void selectUserById(){
SqlSession openSession = sqlSessionFactory.openSession();
UserMapper mapper = openSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(2);
System.out.println(user);
}