。
iBATIS 3内的新特性:将iBATIS用作应用程序内的一种持久框架(5)
时间:2011-11-11 IBM Nathan A. Good
创建示例 Java 项目
要测试本文中的这些例子,需要创建一个空的 Java 项目。在这个新的 Java 项目内,创建一个包括 了 main() 方法的类,如清单 6 所示。
清单 6. Main 类
package com.ibm.developerWorks.examples.ibatis;
import java.io.IOException;
import javax.sql.DataSource;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.derby.jdbc.EmbeddedDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import com.ibm.developerWorks.examples.ibatis.data.AutomobileMapper;
import com.ibm.developerWorks.examples.ibatis.model.Automobile;
public class Main {
private static final String CREATE = "create";
private static final String DELETE = "delete";
private static final String IBATIS_CONFIG = "ibatis-config.xml";
private static final String SHOW = "show";
@SuppressWarnings("static-access")
private static Options createOptions() {
Options options = new Options();
options.addOption(CREATE, false, "creates the objects in the database");
options.addOption(OptionBuilder.withArgName(SHOW).hasArg().withDescription (
"shows the specified automobile").withLongOpt(SHOW).create());
options.addOption(DELETE, false, "deletes all of the objects in database");
return options;
}
private static SqlSessionFactory createSqlMapper() throws IOException {
Reader reader = Resources.getResourceAsReader(IBATIS_CONFIG);
return new SqlSessionFactoryBuilder().build(reader);
}
public static void main(final String[] args) {
Options options = createOptions();
try {
CommandLine cmd = new GnuParser().parse(options, args);
SqlSession session = createSqlMapper().openSession();
try {
if (cmd.hasOption(CREATE)) {
System.out.println("Creating the objects in the database...");
// Create the automobiles
session.insert(Automobile.class.getName() + ".insert", new
Automobile(1, "Toyota", "Tercel", 1993));
session.insert(Automobile.class.getName() + ".insert", new
|