Mybatis的配置以及实例测试

使用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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值