MyBatis——(2)MyBatis_HelloWorld
发布日期:2021-05-07 02:35:43 浏览次数:21 分类:精选文章

本文共 2916 字,大约阅读时间需要 9 分钟。

思路:

1:根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象 有数据源一些运行环境信息
2:sql映射文件;配置了每一个sql,以及sql的封装规则等。
3:将sql映射文件注册在全局配置文件中
4:写代码:
1)、根据全局配置文件得到SqlSessionFactory;
2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查一个sqlSession就是代表和数据库的一次会话,用完关闭
3)、使用sql的唯一标志来告诉MyBatis执行哪个sql。sql都是保存在sql映射文件中的。

创建一个Employee数据表

在这里插入图片描述
创建一个Employee类

package com.atguigu.mybatis.bean;public class Employee {   		private Integer id;	private String lastName;	private String email;	private String gendar;			public Integer getId() {   		return id;	}	public void setId(Integer id) {   		this.id = id;	}	public String getLastName() {   		return lastName;	}	public void setLastName(String lastName) {   		this.lastName = lastName;	}	public String getEmail() {   		return email;	}	public void setEmail(String email) {   		this.email = email;	}	public String getGender() {   		return gendar;	}	public void setGender(String gender) {   		this.gendar = gender;	}	@Override	public String toString() {   		return "Employee [id=" + id + ", lastName=" + lastName + ", email="				+ email + ", gender=" + gendar + "]";	}}

按照思路我们来实现如下代码

1:在conf文件夹中写一个mybatis-config.xml全局配置文件,并在MyBatisTest测试类中创建一个SqlSessionFactory对象

public SqlSessionFactory getSqlSessionFactory() throws IOException {   		String resource = "mybatis-config.xml";		InputStream inputStream = Resources.getResourceAsStream(resource);		return new SqlSessionFactoryBuilder().build(inputStream);	}

2,3:写一个sql映射文件,并且要把该文件注入到全局配置文件(mybatis-config.xml)中

4:在MyBatisTest测试类中写演示代码

package com.atstudying.mybatis.test;import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import com.atstudying.mybatis.bean.Employee;import com.atstudying.mybatis.dao.EmployeeMapper;public class MyBatisTest {   		public SqlSessionFactory getSqlSessionFactory() throws IOException {   		String resource = "mybatis-config.xml";		InputStream inputStream = Resources.getResourceAsStream(resource);		return new SqlSessionFactoryBuilder().build(inputStream);	}	@Test	public void test() throws IOException {   		// 2、获取sqlSession实例,能直接执行已经映射的sql语句		// sql的唯一标识:statement Unique identifier matching the statement to use.		// 执行sql要用的参数:parameter A parameter object to pass to the statement.		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();		SqlSession openSession = sqlSessionFactory.openSession();		try {   			Employee employee = openSession.selectOne(					"com.atguigu.mybatis.dao.EmployeeMapper.getEmpById", 1);			System.out.println(employee);		} finally {   			openSession.close();		}	}}

查询结果

在这里插入图片描述

上一篇:MyBatis——(3)MyBatis_接口式编程
下一篇:MyBatis——(1)MyBatis简介

发表评论

最新留言

不错!
[***.144.177.141]2025年04月07日 13时52分33秒