【MyBatis】第1个MyBatis,创建Java项目之MyBatis

在这里插入图片描述在这里插入图片描述

CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(255),
gender CHAR(1),
email VARCHAR(255)
);

在这里插入图片描述

–实体类

package com.mybatis.bean;

public class Employee {  //对应DB内那个表:来完成映射
	
	private Integer id;
	private String last_name;  //若属性名与DB内字段名不同,则无法完成映射【可在sql.xml内起别名解决:
	private String email;
	private String gender;
}
package com.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.mybatis.bean.Employee;
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 {
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();//由mybatis-config.xml创建个SqlSessionFactory,该工厂以创建SqlSession对象
		SqlSession openSession = sqlSessionFactory.openSession();
		try { 
			Employee employee = openSession.selectOne("com.mybatis.EmployeeMapper.selectEmp", 1);  
			System.out.println(employee);
		} finally {
			openSession.close();
		}

	}
}


–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="com.mybatis.EmployeeMapper">
	<select id="selectEmp" resultType="com.mybatis.bean.Employee">
		select * from tbl_employee where id = #{id}
	</select>
</mapper>

全局配置文件:含数据库连接池信息,事务管理器信息等…系统运行环境信息

<?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:3306/mybatis" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="EmployeeMapper.xml" />
	</mappers>
</configuration>

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值