import com.tyhxzy.entity.User; import com.tyhxzy.mapper.UserMApper; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import sun.security.util.Resources; import java.io.InputStream; import java.util.List; public class mybatis { @Test public void chaxun(){ InputStream inputStream = Resources.getResourceAsSteream("mybatis-config.xml"); SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder (); SqlSessionFactory sqlSessionFactory=builder.build ( inputStream ); SqlSession con=sqlSessionFactory.openSession (); UserMApper cc=con.getMapper ( UserMApper.class ); List<User> list=cc.findall (); for (User item:list){ System.out.println (item); } } }哪里错了
时间: 2023-06-20 09:08:45 浏览: 169
您的代码存在几个问题:
1. `Resources` 类在当前 Java 版本中已经被废弃,建议使用其他替代方案。
2. `SqlSessionFactoryBuilder` 类的 `build()` 方法需要传入一个 `Reader` 类型的参数,而您传入的是 `InputStream` 类型的参数,需要将其转换为 `Reader` 类型。
3. `mybatis-config.xml` 文件需要放置在类路径下,以便正确读取。
下面是修改后的代码示例:
```
import com.tyhxzy.entity.User;
import com.tyhxzy.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
public class MyBatisTest {
@Test
public void test() throws IOException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("mybatis-config.xml");
Reader reader = new java.io.InputStreamReader(inputStream, StandardCharsets.UTF_8);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.findAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
```
阅读全文