1. 加载配置文件
public static void main(String[] args) throws IOException { //mybatis的配置文件 String resource = "conf.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件) //Reader reader = Resources.getResourceAsReader(resource); //构建sqlSession的工厂 //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //创建能执行映射文件中sql的sqlSession SqlSession session = sessionFactory.openSession(); /** * 映射sql的标识字符串, * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值, * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL */ String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串 //执行查询返回一个唯一user对象的sql User user = session.selectOne(statement, 1); System.out.println(user); }
详见: http://www.cnblogs.com/xdp-gacl/p/4261895.html
2.扫描包
public SqlSessionFactory SqlSessionFactory(){ DataSource dataSource ;//数据库连接池,使用第三方即可 TransactionFactory transactionFactory = new JdbcTransactionFactory();//事物,使用默认。也可以配合spring,使用spring自带的 Environment environment = new Environment("development", transactionFactory, dataSource);//环境配置即 开发或者生产 Configuration configuration = new Configuration(environment);//配置中心 configuration.addMappers("conge.wang.sqlmappers");//加载mappers xml package,及扫描conge.wang.sqlmappers下面的xml配置 //configuration.addMapper(TestSqlMapper.class);//或者加载mappers class。不过不推荐使用 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);//从SqlSessionFactoryBuilder构建 return sqlSessionFactory; }
详见:http://haoran-10.iteye.com/blog/2257417