简单的Mybatis程序
1.新建一个普通Maven项目,导入 mybatis、mysql、junit(用于测试)3个依赖
Mybatis
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
Mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
Junit
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
</dependency>
2.编写一个mybatis工具类MybatisUtils,方便后续使用
package com.zy.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource=”mybatis-config.xml”;
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSessionFactory(){
return sqlSessionFactory.openSession();
}
}
4.引入MySQL数据库 testmybatis,新建实体类 User
package com.zy.pojo;
//实体类
public class User {
private int id;
private String name;
private String pwd;
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
5.UserMapper接口及其XML文件
UserMapper.java:
package com.zy.dao;
import com.zy.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> getUserList();
}
UserMapper.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=”com.zy.dao.UserMapper”>
<select id=”getUserList” resultType=”com.zy.pojo.User”>
select * from testmybatis.user
</select>
</mapper>
6.使用junit进行测试
package com.zy.dao;
import com.zy.pojo.User;
import com.zy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
//获取sqkSession对象
SqlSession sqlSession = MybatisUtils.getSqlSessionFactory();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//无论成功与否,都必须关闭
sqlSession.close();
}
}
效果截图