潇洒紫焰 发表于 2016-11-28 06:52:11

我们一起读文档,学习MyBatis(一)----------- 一个简单demo的实现

  第一步,创建SqlSessionFactory,方法有两种:
  第一种:根据XML配置创建(Building SqlSessionFactory from XML)
  java源代码:

String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
  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>
<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:3306/dxsf?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/BlogMapper.xml"/>
</mappers>
</configuration>
  第二种:不使用XML配置创建SqlSessionFactory ( Building SqlSessionFactory without XML)

DataSource dataSource = new PooledDataSource("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost/dxsf?userUnicode=true&amp;characterEncoding=utf8", "root", "123456");
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
  第二步,获取SqlSession并执行持久化操作
  在MyBatis的文档中执行自定义的方法时有两种方法,但是首先,都得先定义xxxMapper.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="mapper.BlogMapper">
<select id="selectBlog" parameterType="int" resultType="model.Blog">
select * from Blog where id = #{id}
</select>
</mapper>
  以上的XML配置还可以由注解来实现:   自己定义Mapper接口

package org.mybatis.example;
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
  但是,由于注解的限制以及项目的复杂性,官方是不推荐这样使用的。个人认为,在xml配置文件中不仅结构清晰,而且易于维护。
  然后在调用方法执行:
  第一种:

SqlSession session = sqlSessionFactory.openSession();
try {
Blog blog = session.selectOne("model.BlogMapper.selectBlog", 1);
System.out.println(blog+"\n" + blog.getId() + "" + blog.getTitle() + "   " + blog.getContent());
} finally {
session.close();
}
  这个代码很好理解:配置文件中的namaspace+id即可。
  第二种:

BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
  这里看着很清晰,可是我刚看的时候不明白的是编辑器不会自动提示BlogMapper,而且我写上以后还会编辑错误,那么这个BlogMapper是什么呢?经过询问和搜集资料,得知这个是自己定义的一个接口,具体的内容如下:

public interface BlogMapper {
Blog selectBlog(int id);
}
  运行上面的代码即可以查出来数据。
页: [1]
查看完整版本: 我们一起读文档,学习MyBatis(一)----------- 一个简单demo的实现