@Override
public String toString() {
return “User{” +
“id=” + id +
“, username=’” + username + ‘’’ +
“, birthday=” + birthday +
“, sex=’” + sex + ‘’’ +
“, address=’” + address + ‘’’ +
‘}’;
}
}
配置持久层接口IUserDao:
public interface IUserDao {
/**
查询所有
@return
*/
//@Select(“select * from”)
List findAll();
}
配置接口映射文件IUserDao.xml:
select * from user
配置SqlMapConfig.xml:
创建MybatisTest类测试方法:
public class MybatisTest {
/**
*入门案例
*/
public static void main(String [] args) throws Exception {
//1.读取配置文件
InputStream in= Resources.getResourceAsStream(“SqlMapConfig.xml”);
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session=factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
IUserDao userDao=session.getMapper(IUserDao.class);
//5.使用代理对象执行方法
List users=userDao.findAll();
for (User user :users){
System.out.println(user);
}
//6.释放资源
session.close();
in.close();
}
}
这是我们没有导入mybatis依赖时,测试类MybatisTest的代码,从中我们可以看到我们需要创建的有:class Resources、class SqlSessionFactoryBuilder、Interface SqlSessionFactory、Interface SqlSession
自定义Mybatis
配置使用类加载器读取文件的类Resources
public class Resources {
public static InputStream getResourceAsStream(String filePath){
/**
*/
//返回:本类的字节码的类加载器读取的filePath
return Resources.class.getClassLoader().getResourceAsStream(filePath);
}
}
用于创建SqlSessionFactory对象的类
public class Sq