书写SqlMapConfig.xml
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 加载mapper.xml -->
<mappers>
<mapper resource="sqlmap/User.xml"/>
</mappers>
</configuration>
User.xml, User.java
<?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">
<!-- 命名空间,分类管理sql语句
mapper.xml以Statement为单位管理sql语句
-->
<mapper namespace="test">
<!-- 根据id查用户信息 -->
<!-- id标示一个框架
一个sql封装一个MappedStatement
#{}表示一个占位符,若传入简单类型参数,名称可以任意
parameterType:输入参数类型
resultType输出结果类型:制定映射的单条记录POJO
-->
<select id="findUserById" parameterType="int" resultType="com.mybatis.po.User">
select * from user where id=#{id}
</select>
</mapper>
public class User {
private int id;
private String username;
private String sex;
private Date birthday;
private String address;
建立SqlSessionFactory
//创建会话工厂 声明配置
String resource = "SqlMapConfig.xml";
//加载配置
InputStream inputStream = Resources.getResourceAsStream(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
建立SqlSession
SqlSession session = sessionFactory.openSession();
try {
user = session.selectOne("test.findUserById", 1);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭sqlSession
session.close();
}
System.out.println(user);
运行测试
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1914582232.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@721e34d8]
DEBUG [main] - ==> Preparing: select * from user where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@721e34d8]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@721e34d8]
DEBUG [main] - Returned connection 1914582232 to pool.
User [id=1, username=王五, sex=2, birthday=null, address=null]
表示一个占位符,向占位符输入参数,Mybatis会自动进行MyBatis和JDBC类型的转换
**是拼接串,不能防止sql注入**
表示sql拼接,通过${}接受的参数,将对参数不加修饰
如:#{%${小名}%} 相当于'%小名%'