Mybatis之helloword篇

主配置文件(mybatis-config.xml)

<?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.cj.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>

	<!-- 将我们写好的sql映射文件一定要注册到全局配置文件中 -->
	<mappers>
		<mapper resource="EmployeeMapper.xml" />
	</mappers>
</configuration>

mapper映射文件(EmployeeMapper.xml)

<?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="com.mybatis.DAO.EmployeeMapper">
<!-- 
namespace:名称空间;指定为接口的全类名
id:唯一标识
resultType:返回值类型
#{id}:从传递过来的参数中取出id值


public Employee getEmpById(Integer id);
 -->
	<select id="getEmpById" resultType="com.lly.mybatis.entity.Employee">
		select id,last_name lastName,email,gander from employee where id = #{id}
	</select>
</mapper>

在mybatis中要想操作数据库需要创建SqlSessionFactory对象

创建的基本步骤

1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象,有数据源一些运行环境信息
2.sql映射文件,配置了每个sql,以及sql的封装规则
3、将sql映射文件注册在全局配置文件中
4、写代码:

  • 1)根据全局配置文件得到SqlSessionFactory
  • 2)使用SqlSession工厂,获取到SqlSession对象来执行增删改查,一个SqlSession就代表和数据库的一次对话,用完关闭
  • 3)使用sql的唯一标识来告诉MyBatis执行哪个sql,sql都是保存在sql映射文件中的
    主配置文件(mybatis-config.xml)
	@Test
	public void test() throws IOException {
		String resource = "mybatisconfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		//获取一个SqlSession实例,直接执行已经映射的sql语句
		//sql执行的唯一标识:statement Unique identifier matching the statement to use.
		//执行sql要使用的参数:parameter A parameter object to pass to the statement.
		SqlSession openSession = sqlSessionFactory.openSession();
		try {
			Employee emp = openSession.selectOne("com.mybatis.EmployeeMapper.selectEmp", 1);
			System.out.println(emp);
		}finally {
			openSession.close();
		}
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值