主配置文件(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();
}
}