Java Reference
In-Depth Information
Listing 10.2
A simple example of using a DAO
package org.apache.mapper2.examples.chapter10.dao;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.DaoManagerBuilder;
import com.ibatis.common.resources.Resources;
import java.io.Reader;
import java.io.IOException;
public class DaoService {
private static DaoManager daoManager;
public static synchronized DaoManager getDaoManager(){
String daoXmlResource = "dao.xml";
Reader reader;
if (null == daoManager){
try {
reader =
Resources.getResourceAsReader(daoXmlResource);
daoManager =
DaoManagerBuilder.buildDaoManager(reader);
return daoManager;
} catch (IOException e) {
throw new RuntimeException(
"Unable to create DAO manager.", e);
}
} else {
return daoManager;
}
}
Specifies location
of config file
B
C
Gets a reader for
the builder
Builds DAO
manager
D
public static Dao getDao(Class interfaceClass){
return getDaoManager().getDao(interfaceClass);
}
}
We will look briefly at this listing, because it does have some bits of code that will
prove relevant later. The first in order of importance is the daoXmlResource vari-
able , which contains the location of the dao.xml file we saw in listing 10.1 ear-
lier. That is important because it is not a path, but rather a resource location on
the classpath. For example, if you are working on a web application, it would be in
the WEB-INF/classes directory. The Resources class searches the classpath for
that file, and then we pass it as a Reader to the DaoManagerBuilder
b
C
D
to get our
DaoManager instance. Now, for our DAO , we can simply call this:
Search WWH ::




Custom Search