第一步:创建工程
第二步:引入jar包
第三步:数据库建表
第四步:创建于数据库表对应的实体类
@Setter@Getter
public class Customer {
private Integer cust_id;
private String cust_name;
private String cust_profession;
private String cust_phone;
private String email;
@Override
public String toString() {
return "Customer{" +
"cust_id=" + cust_id +
", cust_name='" + cust_name + '\'' +
", cust_profession='" + cust_profession + '\'' +
", cust_phone='" + cust_phone + '\'' +
", email='" + email + '\'' +
'}';
}
}
第五步:创建核心配置文件SqlMappingConfig.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>
<!-- spring整合后 environments配置将废除 使用spring中的连接池 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
</configuration>
第六步:创建类的映射文件Customer.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="myTest">
<!--根据cust_id查询客户-->
<select id="queryCustomerById" parameterType="Int" resultType="com.ctbu.domain.Customer">
SELECT * FROM `customer` WHERE cust_id = #{cust_id}
</select>
</mapper>
第七步:将创建的映射文件引入核心配置文件中
<!--加载映射文件-->
<mappers>
<mapper resource="com/ctbu/domain/Customer.xml"></mapper>
</mappers>
第八步:编写测试类测试工程
public class TestOne {
@Test
public void test1() throws IOException {
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
//加载核心配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMappingConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = factoryBuilder.build(inputStream);
//创建session对象
SqlSession session = sqlSessionFactory.openSession();
//执行sqlsession对象执行查询
//第一个参数是customer.xml的statement的id
//第二额参数是执行sql需要的参数
Customer customer = session.selectOne("queryCustomerById", 1);
System.out.println(customer);
session.close();
}
}