下载地址:https://github.com/mybatis/mybatis-3
简单调试
1、首先我们先将准备工作做好,先创建数据表。
2、·创建工程
创建普通的java工程,首先创建和数据库表对应的映射文件Emplyee;创建一个普通的文件夹,将mybatis.jar和数据库连接使用的jar复制进去,右键jar包 选择 build path将jar添加进工程依赖。
3、创建xml文件放在config文件夹中,自己创建的源码文件夹。
以下内容可从下载的官方文档复制过来;将数据源信息换成自己数据库的信息。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:8080/mybatis_test" />
<property name="username" value="" />
<property name="password" value="" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml" />
</mappers>
</configuration>
4、创建mapper.xml文件,编写我们的sql语句。
<?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="EmployeeMapper">
<!--
namespace:名称空间
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取的id值
-->
<select id="selectEmployee" resultType="cc_study.pojo.Employee">
select * from employee where id = #{id}
</select>
</mapper>
5、在全局配置文件中注册我们的mapper.xml
6、创建测试文件进行测试
(1)根据全局配置文件得到SqlSessionFactory
(2)使用SqlSessionFactory,获取到sqlSession对象来执行增删改查;用完记得关闭。
(3)使用 sql的唯一标识告诉Mybatis执行 那个sql,为了保证唯一性,这里使用的是唯一标识前加上命名空间。
public class MybatisTest {
@Test
public void test() throws IOException {
String resource = "mybatis_config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
try {
//为了保证唯一性,在唯一标识前面加上对应的命名空间
//第一个参数是唯一标识符号
//第二个参数为执行sql需要使用的参数
Employee employee = openSession.selectOne("EmployeeMapper.selectEmployee", 1);
System.out.println(employee);
} catch (Exception e) {
e.printStackTrace();
} finally {
openSession.close();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/16883.html