2021-7-11(mybatis01)学习笔记-mybatis

1.mybatis约等于接口实现类的功能

2.简单的mybatis实例
根据id查询单条数据
a.路径在这里插入图片描述
b.创建全局配置文件mybatis-config.xml

<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:3333/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
  	<!-- 包+xml名 这里没有在包下就直接写名就可了 -->
    <mapper resource="Mapper.xml"/>
  </mappers>
</configuration>

c.创建Mapper.xml

<mapper namespace="Mapper">
									<!-- 包+类 -->
  <select id="selectBlog" resultType="pojo.User">
    select * from user where id = #{id}
  </select>
</mapper>

d.创建实体类User

public class User {
	private int id;
	private String name;
	private String pwd;
	//set和get方法省略
}

e.在mybatisTest.java类中

		@Test
	public void test() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		// 获取sqlSessionFactory实例,能直接执行映射的sql语句
		SqlSession openSession = sqlSessionFactory.openSession();
//										   Mapper的id
		User user = openSession.selectOne("selectBlog", 2);
		System.out.println(user);
		
		openSession.close(); 
	}

小结:
由SqlSessionFactory获取到SqlSession
且SqlSession能直接执行映射的sql语句!

	//1.绑定全局配置文件mybatis-config.xml并且创建SqlssionFactory
	//(这步在mybatis文档中有)
	String resource = "mybatis-config.xml";
	InputStream inputStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	//2.根据上步获取到的SqlSessionFatory对象来获取SqlSession对象
	// 获取sqlSessionFactory实例,能直接执行映射的sql语句
	SqlSession openSession = sqlSessionFactory.openSession();
	//3.然后由openSession的方法实现就行了
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值