Mybatis的使用主要有两种方式:
- 使用Mapper进行数据库操作;
- 使用SqlSession进行数据库操作;
实际上第1种只是在第2种的基础上封装了一下,主要提供接口方法的提取和参数的转换,后面仍然是使用SqlSession进行数据库的增、删、改、查操作。
下面是不集成Spring的使用例子:
(1) 承载数据的User bean:com/mybatis/demo1/User.javapackage com.mybatis.demo1;
public class User {
/** 用户ID */
private int id;
/** 用户名称 */
private String name;
/** 用户密码 */
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
(2) Mapper接口类:com/mybatis/demo1/UserMapper.java
(只需提供接口方法,应用中mybatis会使用动态反射的方式提供查询的实际逻辑)
package com.mybatis.demo1;
public interface UserMapper {
public User findByName(String name);
}
(3) 数据源properties文件:com/mybatis/demo1/mysql.properties
(提供数据库连接所需要的参数)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/bookstore
username=root
password=123456
(4) Mybatis的配置文件:com/mybatis/demo1/mybatis_config.xml
(不与Spring集成时,该配置文件配置的内容很丰富,可参考官方的文件来作更多配置)
<?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>
<properties resource="com/mybatis/demo1/mysql.properties" />
<settings>
<setting name="cacheEnabled" value="true" />
</settings>
<typeAliases>
<typeAlias alias="User" type="com.mybatis.demo1.User" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/demo1/UserMappers.xml" />
</mappers>
</configuration>
(5) Mapper.xml配置文件:com/mybatis/demo1/UserMappers.xml
(该文件需要在Mybatis中的配置文件中进行映射,以便在加载Mybatis时就可以加载到;当然也可以在代码中手动加载然后再塞到Mybatis的配置中)
<?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的类路径;直接使用SqlSession时可配可不配 -->
<mapper namespace="com.mybatis.demo1.UserMapper">
<resultMap id="userMap" type="User">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="password" column="password" />
</resultMap>
<select id="findByName" parameterType="String" resultMap="userMap">
select * from users where name=#{name}
</select>
</mapper>
(6) 测试类:com/mybatis/demo1/UserManagerPrgm.java
(主要先获取到Mapper或者SqlSession来进行操作)
package com.mybatis.demo1;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class UserManagerPrgm {
private SqlSession session;
public static void main(String[] args) {
UserManagerPrgm prgm = new UserManagerPrgm();
prgm.openSession();
prgm.testFindUserByName("admin");
prgm.closeSession();
}
private void testFindUserByName(String name)
{
User user = null;
// 使用Mapper来查询,接口的方法名必须与SQL对应的ID一致
UserMapper userMapper = session.getMapper(UserMapper.class);
user = userMapper.findByName(name);
System.out.println(user);
// 直接使用SqlSession查询,此时需要手动指定SQL所对应的ID
user = (User)session.selectOne("findByName", name);
System.out.println(user);
}
/**
* 创建SqlSession
*/
private void openSession() {
String resource = "com/mybatis/demo1/mybatis_config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
session = sessionFactory.openSession();
} catch (Exception e) {
e.printStackTrace();
closeSession();
}
finally
{
if(inputStream != null)
{
try
{
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 关闭SqlSession
*/
private void closeSession()
{
if(session != null)
{
try
{
session.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
}