步骤:
1.在根目录下编写 mybatis-config.xml(全局配置文件)
2.在根目录下编写sql映射文件,并将映射文件注册到全局配置文件里
3.写java代码
3.1 根据全局文件得到sqlSessionFactory
3.2. 使用sqlSessionFactory创建sqlSession对象进行crud 用完需要close
3.3 使用sql的唯一标识符告诉session执行哪个sql。
1.在根目录下编写 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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://47.94.129.191:3306/mysql"/>
<property name="username" value="admin"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="employee.xml"/>
</mappers>
</configuration>
2.在根目录下编写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.casm.entity.Employee">
<select id="selectEmployee" resultType="com.casm.entity.Employee">
select * from tab_terminal_device where dev_id = #{dev_id}
</select>
</mapper>
3.写java代码
package com.casm.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 com.casm.entity.Employee;
public class test {
public static void main(String[] args) {
String resource = "mybatis-config.xml";
InputStream inputStream=null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
Employee employee = (Employee) session.selectOne("com.casm.entity.Employee.selectEmployee", 5);
System.out.println(employee);
} finally {
session.close();
}
}
}
输出结果
Employee [dev_id=5, id=User5, muMac=c8fd19008f89]