Java数据库连接-集成第三方ORM框架-iBatis(三)

2014-11-24 02:08:33 · 作者: · 浏览: 9
, and also demarcate transactions and work with batches. Once you have an SqlMapClient instance, everything you need to work with SQL Maps is easily available.

The SqlMapClient can either be worked with directly as a multi-threaded client (internal session management), or you can get a single threaded session and work with that. There may be a slight performance increase if you explicitly get a session (using the openSession() method), as it saves the SqlMapClient from having to manage threads contexts. But for most cases it won't make much of a difference, so choose whichever paradigm suits your needs or preferences.

An SqlMapClient instance can be safely made static or applied as a Singleton. Generally it's a good idea to make a simple configuration class that will configure the instance (using SqlMapClientBuilder) and provide access to it.

9.3.3 数据库操作示例
a)读取数据全局配置文件
b) 获取数据库操作句柄
c) 查询操作并返回结果

String filePath = "com/iteye/jarg/resources/sql-map-config.xml";
InputStream inputStream = IbatisDbUtil.class.getClassLoader().getResourceAsStream(filePath);

sqlMapper = SqlMapClientBuilder.buildSqlMapClient(inputStream);

int id = 2;
User user = (User)sqlMapper.queryForObject("user.queryUserById", id);

System.out.println("id:\t\t" + user.getId());
System.out.println("username:\t" + user.getUsername());
System.out.println("password:\t" + user.getPassword());