MyBatis学习(一)基本配置与使用
1、前期准备
文件具体架构图
1、配置conf.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/xiao?serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载映射文件 -->
<mapper resource="com/feng/entity/personMapper.xml"/>
</mappers>
</configuration>
2、创建对应的表和实体类
package com.feng.entity;
public class Person {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Person() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
对应mysql中的表如图所示:
3、配置对应的映射文件xxxMapper.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.feng.entity.personMapper">
<select id="queryPersonById" resultType="com.feng.entity.Person" parameterType="int">
select * from person where id = #{id}
</select>
</mapper>
4、创建对应的测试类
package com.feng.entity;
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 java.io.IOException;
import java.io.Reader;
public class TestMyBatis {
public static void main(String[] args) throws IOException {
// 1、加载MyBatis配置文件、为了访问数据库
Reader reader = Resources.getResourceAsReader("com/feng/conf.xml");
// 2、sqlSessionFactory -- connection
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 3、执行查询、需要所在映射文件的namespace + id 值
String statement = "com.feng.entity.personMapper.queryPersonById";
Person person = sqlSession.selectOne(statement, 1);
System.out.println(person);
// 4、关闭连接
sqlSession.close();
}
}