mapper.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.Demo1.mapper">
<!-- parameterType输出参数 -->
<select id="selectBlog" resultType="com.Demo1.Person" parameterType="int">
select * from person where id=#{id}
</select>
</mapper>
mybaties-config
<?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/demodatabase?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载映射文件 -->
<mapper resource="com/Demo1/mapper.xml"/>
</mappers>
</configuration>
JavaBean
package com.Demo1;
public class Person {
private int ID;
private String name;
private int age;
public int getID() {
return ID;
}
public void setID(int iD) {
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 + "]";
}
public Person(int iD, String name, int age) {
super();
ID = iD;
this.name = name;
this.age = age;
}
public Person() {
}
}
测试类
package com.Demo1;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {
public static void queryOne() {
try {
//加载MyBaties配置文件
//普通的硬盘文件读到内存中,变为一个reader对象
Reader reader = Resources.getResourceAsReader("config.xml");
//通过reader对象产生SqlSessionFactory工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
//通过sessionFactroy 工厂产生真正的SqlSession 来操作MyBaties
SqlSession connection = sessionFactory.openSession();
Person person = connection.selectOne("com.Demo1.mapper.selectBlog",1);
} catch (IOException e) {
e.printStackTrace();
}
}