Mybatis基础使用方法

1.导入约束:

https://blog.csdn.net/yang5726685/article/details/80072954

2.导包:

数据库连接驱动包
mybatis包
备注:记得BuildPath引用包

3.创建Mybatis管理的表单对象(例如:创建User.xml)

3.1.声明文档类型
	<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

3.2.<marpper>标签
	属性:namespace用于区分不同的表
	mapper下的标签:<insert> <delete> <update> <select>
		属性:
			id用于区分操作
			parameterType参数类型
			resultType返回值类型(引用类型变量格式:包名.类型)	
例子:
 <mapper namespace="test">
	<!-- 通过ID查询一个用户 -->
	<select id="findUserById" parameterType="Integer" resultType="pojo.User">
		select * from user where id = #{v}
	</select>
</mapper>

3.3.写sql语句
	模糊查询:select * from user where username like '%${value}%'
	可变参数:?在mybatis中用#{}代替
		select * from user where id=#{v1111}

4.创建核心配置文件SqlMapConfig.xml

4.1.声明文档类型
4.2.<configuration>
	4.2.1.配置jdbc:

	例子:
		<!-- 和spring整合后 environments配置将废除jdbc -->
		<environments default="development">
			<environment id="development">
				<!-- 使用jdbc事务管理 -->
				<transactionManager type="JDBC" />
				<!-- 数据库连接池 -->
				<dataSource type="POOLED">
					<property name="driver" value="com.mysql.jdbc.Driver" />
					<property name="url"
						value="jdbc:mysql:///mybatis" />
					<property name="username" value="root" />
					<property name="password" value="root" />
				</dataSource>
			</environment>
		</environments>

	4.2.2.创建mapper映射

		例子:
			<mappers>
				<mapper resource="sqlmap/User.xml"/>
			</mappers>

5.创建测试类MybatisTest

5.1.创建测试方法@test
5.2.创建核心配置文件类:
	String resource="sqlMapConfig.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
5.3.创建sqlSessionFactory:
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
5.4.创建Session
	SqlSession sqlSession = sqlSessionFactory.openSession();
5.5.执行sql语句(“sql位置”,可变参数)
	User user = sqlSession.selectOne("test.findUserById", 10);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值