1.mybatis约等于接口实现类的功能
2.简单的mybatis实例
根据id查询单条数据
a.路径
b.创建全局配置文件mybatis-config.xml
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3333/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 包+xml名 这里没有在包下就直接写名就可了 -->
<mapper resource="Mapper.xml"/>
</mappers>
</configuration>
c.创建Mapper.xml
<mapper namespace="Mapper">
<!-- 包+类 -->
<select id="selectBlog" resultType="pojo.User">
select * from user where id = #{id}
</select>
</mapper>
d.创建实体类User
public class User {
private int id;
private String name;
private String pwd;
//set和get方法省略
}
e.在mybatisTest.java类中
@Test
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取sqlSessionFactory实例,能直接执行映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
// Mapper的id
User user = openSession.selectOne("selectBlog", 2);
System.out.println(user);
openSession.close();
}
小结:
由SqlSessionFactory获取到SqlSession
且SqlSession能直接执行映射的sql语句!
//1.绑定全局配置文件mybatis-config.xml并且创建SqlssionFactory
//(这步在mybatis文档中有)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.根据上步获取到的SqlSessionFatory对象来获取SqlSession对象
// 获取sqlSessionFactory实例,能直接执行映射的sql语句
SqlSession openSession = sqlSessionFactory.openSession();
//3.然后由openSession的方法实现就行了