junit
junit
4.11
test
org.mybatis
mybatis
3.5.9
2.配置XML 配置文件中包含了对 MyBatis 系统的核心设置
在resources中创建mybatis.xml文件
新建完成之后将以下代码直接复制进去
注意:修改url,username,password
3.编写utilpackage com.tao.util;
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;
//sqlSessionFactory -->sqlSession
public class mybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//有了sqlSessionFactory,就可以获得sqlsession的实例了
//sqlSession 完全包含了面向数据库执行sql命令所需的所有方法
public static SqlSession getSqlsession(){
return sqlSessionFactory.openSession();
}
}
4.写实体类package com.tao.info;
public class userinfo {
private int id;
private String name;
public userinfo() {
}
public userinfo(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "userInfo{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
5.写接口package com.tao.dao;
import com.tao.info.userinfo;
import java.util.List;
public interface UserDao {
List getUserList();
}
6.在resources下配置mapper.XML
`
namesepace:为接口路径
id:接口中的方法名
resultType:为实体类路径(sql语句返回值)
package org.tao.dao;
import com.tao.dao.UserDao;
import com.tao.info.userinfo;
import com.tao.util.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//获取SqlSession对象
SqlSession sqlsession = mybatisUtils.getSqlsession();
//getMapper
UserDao mapper = sqlsession.getMapper(UserDao.class);
List userList = mapper.getUserList();
for (userinfo userinfo : userList) {
System.out.println(userinfo);
}
//关闭sqlSession
sqlsession.close();
}
}
运行之后报错
资源导出问题,找不到
pom.xml中导入如下代码:
src/main/java
**/*.xml
**/*.properties
src/main/resources
**/*.xml
**/*.properties
8.运行
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)