mybati入门

1.mybatis架构

mybati入门

2.配置mybatis全局文件(在这之前需要书写bean类和建立数据库)

//头文件

<?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配置将废除 -->
<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="root" />
</dataSource>
</environment>
</environments>

//引入对应的每个bean对应的配置文件,改文件主要用于写sql语句
<mappers>

//包名全路径
<mapper resource="com/neusoft/mapper/user.xml"/>
</mappers>
</configuration>

3.书写bean类对应的配置文件

//固定的头部

<?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里用来书写sql语句
<mapper namespace="test">

//parameterType参数类型,resultType返回值类型
<select id="findUserById" parameterType="Integer" resultType="com.neusoft.pojo.User">
//#{}占位符

select * from user where id=#{v}

</select>
</mapper>

4.测试

InputStream is=null;
try {
//加载配置文件
is = Resources.getResourceAsStream("mybatis/mybatis_config.xml");
//获取sessionFactory对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);

//生成sqlSession对象
SqlSession sqlSession = build.openSession();

//查询到的结果
User user = (User)sqlSession.selectOne("findUserById", 10);
System.out.println(user);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}