ibatis && ibatisnet
花了點時間把ibatis用了用,集中起來把入門的示例寫下來。應該還是有很多跟我一樣的初學者為找不到合適的例子而苦惱的。
一直沒有怎麼弄過框架,框架的優點不用說了
在搞清楚了基本原理之後,使用ibatis和ibatisnet是比較方便的。
例子說明(具體可以不關注):
表MAPSALL06用來存放地圖的按圖幅分的地圖名,原來的檔名,
最大最小的x,y座標(每一幅圖為矩形),
和比例尺(scale,1:500或者1:1000或者1:2000)
valid表示是否有效,1為有效,0為失效,2為有新圖替換舊圖,
3為處理中間過程而增加的。
使用資料庫為oracle9i,sql指令碼如下:
create table MAPSALL06
(
ID NUMBER,
ENAME VARCHAR2(30),
IMAGENAME VARCHAR2(50),
XMIN NUMBER,
YMIN NUMBER,
XMAX NUMBER,
YMAX NUMBER,
SCALE VARCHAR2(20),
VALID VARCHAR2(5)
);
1,使用ibatis
建立 project,將ibatis和oracle的驅動加到路徑中
新建MyMaps.java
public class MyMaps {
private int id;
private String ename;
private String imageName;
private int xmin;
private int ymin;
private int xmax;
private int ymax;
private String scale;
private String valid;
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return this.id;
}
public void setEname(String ename)
{
this.ename = ename;
}
public String getEname()
{
return this.ename;
}
public void setImageName(String imageName)
{
this.imageName = imageName;
}
public String getImageName()
{
return this.imageName;
}
public void setXmin(int xmin)
{
this.xmin = xmin;
}
public int getXmin()
{
return this.xmin;
}
public void setYmin(int ymin)
{
this.ymin = ymin;
}
public int getYmin()
{
return this.ymin;
}
public void setXmax(int xmax)
{
this.xmax = xmax;
}
public int getXmax()
{
return this.xmax;
}
public void setYmax(int ymax)
{
this.ymax = ymax;
}
public int getYmax()
{
return this.ymax;
}
public void setScale(String scale)
{
this.scale = scale;
}
public String getScale()
{
return this.scale;
}
public void setValid(String valid)
{
this.valid = valid;
}
public String getValid()
{
return this.valid;
}
}
建立MyAppSqlConfig.java
import java.io.*;
import java.sql.*;
import com.ibatis.common.*;
import com.ibatis.common.resources.*;
import com.ibatis.sqlmap.client.*;
public class MyAppSqlConfig {
private static final SqlMapClient sqlMap;
static
{
try
{
String resource = "SqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader (resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
}
catch (Exception e)
{
Console.debug(e);
throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: "+e);
}
}
public static SqlMapClient getSqlMapInstance()
{
return sqlMap;
}
}
用到的基礎類:Console.java
import java.io.*;
import java.text.DateFormat;
import java.util.Date;
public class Console
{
public static final String SEPARATOR_PATH = System.getProperty("path.separator");
public static final String SEPARATOR_LINE = System.getProperty("line.separator");
public static final String SEPARATOR_FILE = System.getProperty("file.separator");
public static final String USER_DIRECTORY = System.getProperty("user.dir");
public static final int NULL = 0;
public static final int INFO = 1;
public static final int WARN = 2;
public static final int ERROR = 3;
public static final int EVENT = 4;
private static boolean isLog = true;
private static StringBuffer logger = new StringBuffer();
private static DateFormat formatter = DateFormat.getDateTimeInstance();
protected Console()
{
}
public static final void out(Object o)
{
System.out.println(o.toString());
}
public static void debug(Throwable e)
{
e.printStackTrace(System.err);
synchronized(logger)
{
logger.append(e + SEPARATOR_LINE);
StackTraceElement elements[] = e.getStackTrace();
for(int i = 0; i < elements.length; i++)
logger.append("\tat " + elements[i] + SEPARATOR_LINE);
}
}
public static void debug(String s)
{
System.err.println(s);
logger.append(s + SEPARATOR_LINE);
}
public static void log(Object o, int type)
{
String str = getHeader(type) + o.toString();
logger.append(str + SEPARATOR_LINE);
if(isLog)
out(str);
}
private static String getHeader(int type)
{
String head = null;
String date = formatter.format(new Date());
String limit = String.valueOf(System.currentTimeMillis());
switch(type)
{
case 0: // '\0'
head = "";
break;
case 1: // '\001'
head = "INFO: ";
break;
case 2: // '\002'
head = "WARN: ";
break;
case 3: // '\003'
head = "ERROR: ";
break;
case 4: // '\004'
head = "EVENT: ";
break;
default:
head = "";
break;
}
return "| " + date + ".".concat(limit.substring(limit.length() - 3)) + " | " + head;
}
public static StringBuffer getLogs()
{
return logger;
}
public static PrintStream getStream()
{
return System.out;
}
public static void printLogs()
{
System.out.print(getLogs());
}
public static boolean isLog()
{
return isLog;
}
public static void setLog(boolean b)
{
isLog = b;
}
public static void out(InputStream ins)
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
bis = new BufferedInputStream(ins);
bos = new BufferedOutputStream(System.out);
byte buff[] = new byte[2048];
for(int len = 0; (len = bis.read(buff)) > 0;)
bos.write(buff, 0, len);
bos.flush();
}
catch(Throwable e)
{
debug(e);
}
finally
{
try
{
bis.close();
}
catch(Throwable throwable) { }
try
{
bos.close();
}
catch(Throwable e) { }
}
}
}
用到的log類:DebugLog.java
import java.io.*;
import java.util.*;
import java.text.*;
public class DebugLog {
private static String LOGFILE = "logfile.log";
private static String APPLOGINFO = "\r\n應用程式啟動";
private static String APPLOGCLOSE = "\r\n應用程式關閉";
private static String APPLOGSEPARATOR = " ||... ";
private static String APPLOGFOOTER = "\r\n--------------------------------------------------\r\n";
//private static BufferedReader br ;
private static BufferedWriter bw ;
private static File file = new File(LOGFILE);
public static void createAppLog()
{
if(file.exists())
{
try
{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(APPLOGINFO+APPLOGSEPARATOR);
bw.write((new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())));
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
file.createNewFile();
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(APPLOGINFO+APPLOGSEPARATOR);
bw.write((new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))+" ");
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void closeAppLog()
{
try
{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(APPLOGCLOSE+APPLOGSEPARATOR);
bw.write((new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))+" ");
bw.write(APPLOGFOOTER);
bw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void createLog()
{
if(file.exists())
{
try
{
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
file.createNewFile();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void closeLog()
{
try
{
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void writeLog(Object obj)
{
String str = obj.toString();
createLog();
try
{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write("\r\n"+(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))+" "+APPLOGSEPARATOR);
bw.write(str);
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
用到的檔案控制類:FileControl.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class FileControl {
private int total = 0;
private int totalFiles = 0;
private int totalPaths = 0;
//private int FileNumber = 0;
private BufferedWriter sw1;
private BufferedReader sr1;
private String fileName;
private String textString;
private static String DEFAULT_PATH = "\\\\192.168.7.44\\數字地圖";//"\\\\172.27.1.199\\數字地圖";
private File file;
public String getFilePath(File file) {
return file.getAbsolutePath();
}
public String getDefaultPath() {
return DEFAULT_PATH;
}
public int getTotalFiles() {
return this.total;
}
public void setFileName(String str) {
this.fileName = str;
file = new File(fileName);
}
public String getFileName() {
return this.fileName;
}
public File getFile() {
return file;
}
public BufferedReader getSr1() {
return this.sr1;
}
public BufferedWriter getSw1() {
return this.sw1;
}
public void openFile(File fl) throws Exception {
if (fl.exists()) {
sw1 = new BufferedWriter(new FileWriter(fileName, true));
} else {
fl.createNewFile();
sw1 = new BufferedWriter(new FileWriter(fileName, true));
}
}
public void deleteFile(File file) {
try {
file.delete();
} catch (Exception e) {
DebugLog.writeLog(e);
}
}
public void readFile(File fl) throws Exception {
if (fl.exists()) {
sr1 = new BufferedReader(new FileReader(fileName));
} else {
Console.debug("file not exists!");
DebugLog.writeLog("file not exists!");
}
}
public String getNextLine() throws Exception {
return sr1.readLine();
}
public void readAllLine() throws Exception {
String s;
while ((s = sr1.readLine()) != null) {
Console.debug(s);
}
}
public String getFilePathFromPath(String path) {
String temp = path;
int num = temp.lastIndexOf("\\");
temp = temp.substring(0, num);
return temp;
}
public void MutiCopyPath(String pipei, String oraPath, String tarPath) throws Exception
{
String pipeiStr = pipei; //匹配的字串
String raPathStr = oraPath; //路徑
String tarPathStr = tarPath; //路徑
//string indexPathStr = indexPath; //檔名 預設index.txt
String indexFileName = "index.txt";
BufferedReader sr2 = new BufferedReader(new FileReader(indexFileName));
//ArrayList al = new ArrayList ();
String sr2Str;
while ((sr2Str = sr2.readLine()) != null) {
String fileName = sr2Str;
int num = sr2Str.lastIndexOf("\\");
fileName = fileName.substring(num + 1);
String sr1Temp = sr2Str;
int numTemp = sr2Str.lastIndexOf("\\");
sr1Temp = sr1Temp.substring(numTemp + 1);
if (pipeiStr != "" && sr2Str != "") {
try
{
if (sr1Temp.lastIndexOf(pipeiStr) >= 0)
{
copyFile(sr2Str, tarPathStr + "\\" + fileName);
}
}
catch (Exception ex)
{
DebugLog.writeLog(ex);
}
}
}
}
public int getFilesCount(String filePath)
{
int totalFile = 0;
File files[] = (new File(filePath)).listFiles();
for(int i=0;i {
if(files[i].isFile())
{
totalFile ++;
}
}
return totalFile;
}
public int getFolderCount(String filePath)
{
int totalFolder = 0;
File files[] = (new File(filePath)).listFiles();
for(int i=0;i {
if(files[i].isDirectory())
{
totalFolder ++;
}
}
return totalFolder;
}
public int getFilesCountAll(String filePath)
{
File files[] = (new File(filePath)).listFiles();
for(int i=0;i {
if(files[i].isFile())
{
totalFiles ++;
}
else if (files[i].isDirectory())
{
totalPaths ++;
getFilesCountAll(files[i].getPath());
}
}
return totalFiles;
}
public void newFolder(String folderPath) {
try
{
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists())
{
myFilePath.mkdir();
}
}
catch (Exception e)
{
System.out.println("新建目錄操作出錯 ");
e.printStackTrace();
}
}
public void newFile(String filePathAndName, String fileContent) {
try
{
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists())
{
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
resultFile.close();
}
catch (Exception e)
{
System.out.println("新建目錄操作出錯 ");
e.printStackTrace();
}
}
public void delFile(String filePathAndName) {
try
{
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
}
catch (Exception e)
{
System.out.println("刪除檔案操作出錯 ");
e.printStackTrace();
}
}
public void delFolder(String folderPath) {
try
{
delAllFile(folderPath); //刪除完裡面所有內容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //刪除空資料夾
}
catch (Exception e)
{
System.out.println("刪除資料夾操作出錯 ");
e.printStackTrace();
}
}
public void delAllFile(String path) {
File file = new File(path);
if (!file.exists())
{
return;
}
if (!file.isDirectory())
{
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++)
{
if (path.endsWith(File.separator))
{
temp = new File(path + tempList[i]);
}
else
{
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile())
{
temp.delete();
}
if (temp.isDirectory())
{
delAllFile(path + "/ " + tempList[i]);//先刪除資料夾裡面的檔案
delFolder(path + "/ " + tempList[i]);//再刪除空資料夾
}
}
}
public void copyFile(String oldPath, String newPath) {
try
{
int bytesum = 0;
int byteread = 0;
File ldfile = new File(oldPath);
if (oldfile.exists())
{ //檔案存在時
InputStream inStream = new FileInputStream(oldPath); //讀入原檔案
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1)
{
bytesum += byteread; //位元組數 檔案大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e)
{
System.out.println("複製單個檔案操作出錯 ");
e.printStackTrace();
}
}
public void copyFolder(String oldPath, String newPath) {
try
{
(new File(newPath)).mkdirs(); //如果資料夾不存在 則建立新資料夾
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++)
{
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile())
{
FileInputStream input = new FileInputStream(temp);
FileOutputStream utput = new FileOutputStream(newPath
+ "/ " + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1)
{
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory())
{//如果是子資料夾
copyFolder(oldPath + "/ " + file[i], newPath + "/ "
+ file[i]);
}
}
} catch (Exception e) {
System.out.println("複製整個資料夾內容操作出錯 ");
e.printStackTrace();
}
}
public void moveFile(String oldPath, String newPath) {
copyFile(oldPath, newPath);
delFile(oldPath);
}
public void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
}
用到的資源類,用於屬性檔案資源繫結(資料庫連線資訊等)
Resource.java
import java.io.*;
import java.util.*;
public class Resource{
public static final String BASENAME = "resource_cn";
private static Locale locale = null;
private static Properties properties = null;
private static ResourceBundle resourceBundle = null;
protected Resource()
{
}
public static ResourceBundle getResourceBundle()
{
if(resourceBundle == null)
try
{
resourceBundle = getResourceBundle(locale = getLocale());
}
catch(Throwable e)
{
e.printStackTrace();
}
return resourceBundle;
}
public static void setResourceBundle(Locale loc)
{
try
{
resourceBundle = getResourceBundle(locale = loc);
}
catch(Throwable e)
{
e.printStackTrace();
}
}
private static ResourceBundle getResourceBundle(Locale loc)
{
return ResourceBundle.getBundle("resource_cn", loc);
}
public static Locale getLocale()
{
if(locale == null)
locale = Locale.getDefault();
return locale;
}
public static Locale getSystemLocale()
{
return Locale.getDefault();
}
public static String getMessage(String key)
{
String message = null;
try
{
message = getResourceBundle().getString(key);
}
catch(Throwable e)
{
message = key;
Console.log(e.toString(), 3);
}
return message;
}
private static synchronized Properties loadProperties()
{
Properties p = null;
try
{
p = new Properties();
if(Utils.checkFileExist("resource_cn.properties"))
p.load(new FileInputStream("resource_cn.properties"));
else
p.load(ClassLoader.getSystemResourceAsStream("resource_cn.properties"));
}
catch(Throwable e)
{
e.printStackTrace();
}
return p;
}
/*
public static void saveProperties()
{
String header = "tree node test";
saveProperties("resource_cn.properties", header);
}
public static void saveProperties(String file, String header)
{
try
{
setProperty("preferences.local.country", getLocale().getCountry());
setProperty("preferences.local.language", getLocale().getLanguage());
getProperties().store(new FileOutputStream(file), header);
}
catch(Throwable e)
{
e.printStackTrace();
}
}
public static Properties getProperties()
{
if(properties == null)
properties = loadProperties();
return properties;
}
public static Properties getSystemProperties()
{
return System.getProperties();
}
public static String getProperty(String key)
{
return getProperty(key, "");
}
public static String getProperty(String key, String defaultValue)
{
try
{
if(getProperties().containsKey(key))
return getProperties().getProperty(key, defaultValue);
else
throw new Exception("Properties not containsKey(" + key + ")");
}
catch(Throwable e)
{
e.printStackTrace();
}
return defaultValue;
}
public static void setProperty(String key, String value)
{
try
{
if(getProperties().containsKey(key))
getProperties().setProperty(key, value);
else
throw new Exception("Properties not containsKey(" + key + ")");
}
catch(Throwable e)
{
e.printStackTrace();
}
}
public static int getIntProperty(String key, int defaultValue)
{
int value = 0;
try
{
value = Integer.parseInt(getProperty(key));
}
catch(Throwable e)
{
value = defaultValue;
//Console.log("getIntProperty_" + key, 2);
}
return value;
}
public static String getStringProperty(String key, String defaultValue)
{
String value = "";
try
{
value = getProperty(key);
}
catch(Throwable e)
{
value = defaultValue;
//Console.log("getStringProperty_" + key, 2);
}
return value;
}
public static void resetProperties()
{
properties = loadProperties();
}
*/
}
建立Maps.xml,具體業務用了幾個簡單的操作代替,關於sqlMap的具體寫法
可參考http://ibatis.apache.org/
br> "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<!-- Always ensure to use the correct XML header as above! -->
INSERT INTO
mapsall06
(id,imageName,
xmin,ymin,xmax,ymax,
scale,valid)
VALUES
(#id#,#imageName#,
#xmin#,#ymin#,#xmax#,#ymax#,
#scale#,#valid#
)
UPDATE mapsall06 A
SET eName = #ename#,
imageName = #imageName#,
xmin = #xmin#, ymin = #ymin#,
xmax = #xmax#,ymax = #ymax#,
scale=#scale#,valid=#valid#
WHERE id = #id#
DELETE mapsall06
WHERE id = #id#
SqlMapConfig.properties用來配置資料庫連線的資訊
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:emap
username=my
password=my
SqlMapConfig.xml用來配置ibatis和指定sqlMap,這裡、指定的為上面
的Maps.xml
br>PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<!-- Always ensure to use the correct XML header as above! -->
<!-- The properties (name="WebRoot/WEB-INF/classes/SqlMapConfig.xml") in the file specified here can be used placeholders in this
config file (e.g. “${driver}”. The file is relative to the classpath and is completely optional. -->
<!-- These settings control SqlMap configuration details, primarily to do with transaction
management. They are all optional (see the Developer Guide for more). -->
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<!-- Type aliases allow you to use a shorter name for long fully qualified class names. -->
<!-- Configure a datasource to use with this SQL Map using SimpleDataSource.
Notice the use of the properties from the above resource -->
<!-- Identify all SQL Map XML files to be loaded by this SQL map. Notice the paths
are relative to the classpath. For now, we only have one… -->
log4j用簡單的DebugLog和Console代替,也是個人習慣。
Test.java 用來測試ibatis的簡單應用。
import java.io.*;
import com.ibatis.sqlmap.client.SqlMapClient;
public class Test {
public Test()
{
}
public void testIbatis() throws Exception
{
SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance();
Integer myMapsPk = new Integer(5);
MyMaps mm = new MyMaps();
mm.setId(1);
mm.setEname("eName");
mm.setImageName("imageName");
mm.setXmax(2);
mm.setYmax(2);
mm.setXmin(1);
mm.setYmin(1);
mm.setScale("5000");
mm.setValid("0");
MyMaps myMaps = (MyMaps) sqlMap.queryForObject ("getMyMaps");
sqlMap.insert("insertMyMaps",mm);
sqlMap.update("updateMyMaps",mm);
Console.debug(myMaps.getImageName());
//DebugLog.writeLog(myMaps.toString());
}
public static void main(String args[])
{
Test test = new Test();
try
{
test.testIbatis();
}
catch(Exception e)
{
Console.debug(e);
}
}
}
一直沒有怎麼弄過框架,框架的優點不用說了
在搞清楚了基本原理之後,使用ibatis和ibatisnet是比較方便的。
例子說明(具體可以不關注):
表MAPSALL06用來存放地圖的按圖幅分的地圖名,原來的檔名,
最大最小的x,y座標(每一幅圖為矩形),
和比例尺(scale,1:500或者1:1000或者1:2000)
valid表示是否有效,1為有效,0為失效,2為有新圖替換舊圖,
3為處理中間過程而增加的。
使用資料庫為oracle9i,sql指令碼如下:
create table MAPSALL06
(
ID NUMBER,
ENAME VARCHAR2(30),
IMAGENAME VARCHAR2(50),
XMIN NUMBER,
YMIN NUMBER,
XMAX NUMBER,
YMAX NUMBER,
SCALE VARCHAR2(20),
VALID VARCHAR2(5)
);
1,使用ibatis
建立 project,將ibatis和oracle的驅動加到路徑中
新建MyMaps.java
public class MyMaps {
private int id;
private String ename;
private String imageName;
private int xmin;
private int ymin;
private int xmax;
private int ymax;
private String scale;
private String valid;
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return this.id;
}
public void setEname(String ename)
{
this.ename = ename;
}
public String getEname()
{
return this.ename;
}
public void setImageName(String imageName)
{
this.imageName = imageName;
}
public String getImageName()
{
return this.imageName;
}
public void setXmin(int xmin)
{
this.xmin = xmin;
}
public int getXmin()
{
return this.xmin;
}
public void setYmin(int ymin)
{
this.ymin = ymin;
}
public int getYmin()
{
return this.ymin;
}
public void setXmax(int xmax)
{
this.xmax = xmax;
}
public int getXmax()
{
return this.xmax;
}
public void setYmax(int ymax)
{
this.ymax = ymax;
}
public int getYmax()
{
return this.ymax;
}
public void setScale(String scale)
{
this.scale = scale;
}
public String getScale()
{
return this.scale;
}
public void setValid(String valid)
{
this.valid = valid;
}
public String getValid()
{
return this.valid;
}
}
建立MyAppSqlConfig.java
import java.io.*;
import java.sql.*;
import com.ibatis.common.*;
import com.ibatis.common.resources.*;
import com.ibatis.sqlmap.client.*;
public class MyAppSqlConfig {
private static final SqlMapClient sqlMap;
static
{
try
{
String resource = "SqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader (resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
}
catch (Exception e)
{
Console.debug(e);
throw new RuntimeException ("Error initializing MyAppSqlConfig class. Cause: "+e);
}
}
public static SqlMapClient getSqlMapInstance()
{
return sqlMap;
}
}
用到的基礎類:Console.java
import java.io.*;
import java.text.DateFormat;
import java.util.Date;
public class Console
{
public static final String SEPARATOR_PATH = System.getProperty("path.separator");
public static final String SEPARATOR_LINE = System.getProperty("line.separator");
public static final String SEPARATOR_FILE = System.getProperty("file.separator");
public static final String USER_DIRECTORY = System.getProperty("user.dir");
public static final int NULL = 0;
public static final int INFO = 1;
public static final int WARN = 2;
public static final int ERROR = 3;
public static final int EVENT = 4;
private static boolean isLog = true;
private static StringBuffer logger = new StringBuffer();
private static DateFormat formatter = DateFormat.getDateTimeInstance();
protected Console()
{
}
public static final void out(Object o)
{
System.out.println(o.toString());
}
public static void debug(Throwable e)
{
e.printStackTrace(System.err);
synchronized(logger)
{
logger.append(e + SEPARATOR_LINE);
StackTraceElement elements[] = e.getStackTrace();
for(int i = 0; i < elements.length; i++)
logger.append("\tat " + elements[i] + SEPARATOR_LINE);
}
}
public static void debug(String s)
{
System.err.println(s);
logger.append(s + SEPARATOR_LINE);
}
public static void log(Object o, int type)
{
String str = getHeader(type) + o.toString();
logger.append(str + SEPARATOR_LINE);
if(isLog)
out(str);
}
private static String getHeader(int type)
{
String head = null;
String date = formatter.format(new Date());
String limit = String.valueOf(System.currentTimeMillis());
switch(type)
{
case 0: // '\0'
head = "";
break;
case 1: // '\001'
head = "INFO: ";
break;
case 2: // '\002'
head = "WARN: ";
break;
case 3: // '\003'
head = "ERROR: ";
break;
case 4: // '\004'
head = "EVENT: ";
break;
default:
head = "";
break;
}
return "| " + date + ".".concat(limit.substring(limit.length() - 3)) + " | " + head;
}
public static StringBuffer getLogs()
{
return logger;
}
public static PrintStream getStream()
{
return System.out;
}
public static void printLogs()
{
System.out.print(getLogs());
}
public static boolean isLog()
{
return isLog;
}
public static void setLog(boolean b)
{
isLog = b;
}
public static void out(InputStream ins)
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
bis = new BufferedInputStream(ins);
bos = new BufferedOutputStream(System.out);
byte buff[] = new byte[2048];
for(int len = 0; (len = bis.read(buff)) > 0;)
bos.write(buff, 0, len);
bos.flush();
}
catch(Throwable e)
{
debug(e);
}
finally
{
try
{
bis.close();
}
catch(Throwable throwable) { }
try
{
bos.close();
}
catch(Throwable e) { }
}
}
}
用到的log類:DebugLog.java
import java.io.*;
import java.util.*;
import java.text.*;
public class DebugLog {
private static String LOGFILE = "logfile.log";
private static String APPLOGINFO = "\r\n應用程式啟動";
private static String APPLOGCLOSE = "\r\n應用程式關閉";
private static String APPLOGSEPARATOR = " ||... ";
private static String APPLOGFOOTER = "\r\n--------------------------------------------------\r\n";
//private static BufferedReader br ;
private static BufferedWriter bw ;
private static File file = new File(LOGFILE);
public static void createAppLog()
{
if(file.exists())
{
try
{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(APPLOGINFO+APPLOGSEPARATOR);
bw.write((new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())));
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
file.createNewFile();
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(APPLOGINFO+APPLOGSEPARATOR);
bw.write((new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))+" ");
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void closeAppLog()
{
try
{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write(APPLOGCLOSE+APPLOGSEPARATOR);
bw.write((new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))+" ");
bw.write(APPLOGFOOTER);
bw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void createLog()
{
if(file.exists())
{
try
{
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
file.createNewFile();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void closeLog()
{
try
{
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void writeLog(Object obj)
{
String str = obj.toString();
createLog();
try
{
bw = new BufferedWriter(new FileWriter(file,true));
bw.write("\r\n"+(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))+" "+APPLOGSEPARATOR);
bw.write(str);
bw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
用到的檔案控制類:FileControl.java
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class FileControl {
private int total = 0;
private int totalFiles = 0;
private int totalPaths = 0;
//private int FileNumber = 0;
private BufferedWriter sw1;
private BufferedReader sr1;
private String fileName;
private String textString;
private static String DEFAULT_PATH = "\\\\192.168.7.44\\數字地圖";//"\\\\172.27.1.199\\數字地圖";
private File file;
public String getFilePath(File file) {
return file.getAbsolutePath();
}
public String getDefaultPath() {
return DEFAULT_PATH;
}
public int getTotalFiles() {
return this.total;
}
public void setFileName(String str) {
this.fileName = str;
file = new File(fileName);
}
public String getFileName() {
return this.fileName;
}
public File getFile() {
return file;
}
public BufferedReader getSr1() {
return this.sr1;
}
public BufferedWriter getSw1() {
return this.sw1;
}
public void openFile(File fl) throws Exception {
if (fl.exists()) {
sw1 = new BufferedWriter(new FileWriter(fileName, true));
} else {
fl.createNewFile();
sw1 = new BufferedWriter(new FileWriter(fileName, true));
}
}
public void deleteFile(File file) {
try {
file.delete();
} catch (Exception e) {
DebugLog.writeLog(e);
}
}
public void readFile(File fl) throws Exception {
if (fl.exists()) {
sr1 = new BufferedReader(new FileReader(fileName));
} else {
Console.debug("file not exists!");
DebugLog.writeLog("file not exists!");
}
}
public String getNextLine() throws Exception {
return sr1.readLine();
}
public void readAllLine() throws Exception {
String s;
while ((s = sr1.readLine()) != null) {
Console.debug(s);
}
}
public String getFilePathFromPath(String path) {
String temp = path;
int num = temp.lastIndexOf("\\");
temp = temp.substring(0, num);
return temp;
}
public void MutiCopyPath(String pipei, String oraPath, String tarPath) throws Exception
{
String pipeiStr = pipei; //匹配的字串
String raPathStr = oraPath; //路徑
String tarPathStr = tarPath; //路徑
//string indexPathStr = indexPath; //檔名 預設index.txt
String indexFileName = "index.txt";
BufferedReader sr2 = new BufferedReader(new FileReader(indexFileName));
//ArrayList al = new ArrayList ();
String sr2Str;
while ((sr2Str = sr2.readLine()) != null) {
String fileName = sr2Str;
int num = sr2Str.lastIndexOf("\\");
fileName = fileName.substring(num + 1);
String sr1Temp = sr2Str;
int numTemp = sr2Str.lastIndexOf("\\");
sr1Temp = sr1Temp.substring(numTemp + 1);
if (pipeiStr != "" && sr2Str != "") {
try
{
if (sr1Temp.lastIndexOf(pipeiStr) >= 0)
{
copyFile(sr2Str, tarPathStr + "\\" + fileName);
}
}
catch (Exception ex)
{
DebugLog.writeLog(ex);
}
}
}
}
public int getFilesCount(String filePath)
{
int totalFile = 0;
File files[] = (new File(filePath)).listFiles();
for(int i=0;i
if(files[i].isFile())
{
totalFile ++;
}
}
return totalFile;
}
public int getFolderCount(String filePath)
{
int totalFolder = 0;
File files[] = (new File(filePath)).listFiles();
for(int i=0;i
if(files[i].isDirectory())
{
totalFolder ++;
}
}
return totalFolder;
}
public int getFilesCountAll(String filePath)
{
File files[] = (new File(filePath)).listFiles();
for(int i=0;i
if(files[i].isFile())
{
totalFiles ++;
}
else if (files[i].isDirectory())
{
totalPaths ++;
getFilesCountAll(files[i].getPath());
}
}
return totalFiles;
}
public void newFolder(String folderPath) {
try
{
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists())
{
myFilePath.mkdir();
}
}
catch (Exception e)
{
System.out.println("新建目錄操作出錯 ");
e.printStackTrace();
}
}
public void newFile(String filePathAndName, String fileContent) {
try
{
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists())
{
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
resultFile.close();
}
catch (Exception e)
{
System.out.println("新建目錄操作出錯 ");
e.printStackTrace();
}
}
public void delFile(String filePathAndName) {
try
{
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
}
catch (Exception e)
{
System.out.println("刪除檔案操作出錯 ");
e.printStackTrace();
}
}
public void delFolder(String folderPath) {
try
{
delAllFile(folderPath); //刪除完裡面所有內容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //刪除空資料夾
}
catch (Exception e)
{
System.out.println("刪除資料夾操作出錯 ");
e.printStackTrace();
}
}
public void delAllFile(String path) {
File file = new File(path);
if (!file.exists())
{
return;
}
if (!file.isDirectory())
{
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++)
{
if (path.endsWith(File.separator))
{
temp = new File(path + tempList[i]);
}
else
{
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile())
{
temp.delete();
}
if (temp.isDirectory())
{
delAllFile(path + "/ " + tempList[i]);//先刪除資料夾裡面的檔案
delFolder(path + "/ " + tempList[i]);//再刪除空資料夾
}
}
}
public void copyFile(String oldPath, String newPath) {
try
{
int bytesum = 0;
int byteread = 0;
File ldfile = new File(oldPath);
if (oldfile.exists())
{ //檔案存在時
InputStream inStream = new FileInputStream(oldPath); //讀入原檔案
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1)
{
bytesum += byteread; //位元組數 檔案大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e)
{
System.out.println("複製單個檔案操作出錯 ");
e.printStackTrace();
}
}
public void copyFolder(String oldPath, String newPath) {
try
{
(new File(newPath)).mkdirs(); //如果資料夾不存在 則建立新資料夾
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++)
{
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile())
{
FileInputStream input = new FileInputStream(temp);
FileOutputStream utput = new FileOutputStream(newPath
+ "/ " + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1)
{
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory())
{//如果是子資料夾
copyFolder(oldPath + "/ " + file[i], newPath + "/ "
+ file[i]);
}
}
} catch (Exception e) {
System.out.println("複製整個資料夾內容操作出錯 ");
e.printStackTrace();
}
}
public void moveFile(String oldPath, String newPath) {
copyFile(oldPath, newPath);
delFile(oldPath);
}
public void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
}
用到的資源類,用於屬性檔案資源繫結(資料庫連線資訊等)
Resource.java
import java.io.*;
import java.util.*;
public class Resource{
public static final String BASENAME = "resource_cn";
private static Locale locale = null;
private static Properties properties = null;
private static ResourceBundle resourceBundle = null;
protected Resource()
{
}
public static ResourceBundle getResourceBundle()
{
if(resourceBundle == null)
try
{
resourceBundle = getResourceBundle(locale = getLocale());
}
catch(Throwable e)
{
e.printStackTrace();
}
return resourceBundle;
}
public static void setResourceBundle(Locale loc)
{
try
{
resourceBundle = getResourceBundle(locale = loc);
}
catch(Throwable e)
{
e.printStackTrace();
}
}
private static ResourceBundle getResourceBundle(Locale loc)
{
return ResourceBundle.getBundle("resource_cn", loc);
}
public static Locale getLocale()
{
if(locale == null)
locale = Locale.getDefault();
return locale;
}
public static Locale getSystemLocale()
{
return Locale.getDefault();
}
public static String getMessage(String key)
{
String message = null;
try
{
message = getResourceBundle().getString(key);
}
catch(Throwable e)
{
message = key;
Console.log(e.toString(), 3);
}
return message;
}
private static synchronized Properties loadProperties()
{
Properties p = null;
try
{
p = new Properties();
if(Utils.checkFileExist("resource_cn.properties"))
p.load(new FileInputStream("resource_cn.properties"));
else
p.load(ClassLoader.getSystemResourceAsStream("resource_cn.properties"));
}
catch(Throwable e)
{
e.printStackTrace();
}
return p;
}
/*
public static void saveProperties()
{
String header = "tree node test";
saveProperties("resource_cn.properties", header);
}
public static void saveProperties(String file, String header)
{
try
{
setProperty("preferences.local.country", getLocale().getCountry());
setProperty("preferences.local.language", getLocale().getLanguage());
getProperties().store(new FileOutputStream(file), header);
}
catch(Throwable e)
{
e.printStackTrace();
}
}
public static Properties getProperties()
{
if(properties == null)
properties = loadProperties();
return properties;
}
public static Properties getSystemProperties()
{
return System.getProperties();
}
public static String getProperty(String key)
{
return getProperty(key, "");
}
public static String getProperty(String key, String defaultValue)
{
try
{
if(getProperties().containsKey(key))
return getProperties().getProperty(key, defaultValue);
else
throw new Exception("Properties not containsKey(" + key + ")");
}
catch(Throwable e)
{
e.printStackTrace();
}
return defaultValue;
}
public static void setProperty(String key, String value)
{
try
{
if(getProperties().containsKey(key))
getProperties().setProperty(key, value);
else
throw new Exception("Properties not containsKey(" + key + ")");
}
catch(Throwable e)
{
e.printStackTrace();
}
}
public static int getIntProperty(String key, int defaultValue)
{
int value = 0;
try
{
value = Integer.parseInt(getProperty(key));
}
catch(Throwable e)
{
value = defaultValue;
//Console.log("getIntProperty_" + key, 2);
}
return value;
}
public static String getStringProperty(String key, String defaultValue)
{
String value = "";
try
{
value = getProperty(key);
}
catch(Throwable e)
{
value = defaultValue;
//Console.log("getStringProperty_" + key, 2);
}
return value;
}
public static void resetProperties()
{
properties = loadProperties();
}
*/
}
建立Maps.xml,具體業務用了幾個簡單的操作代替,關於sqlMap的具體寫法
可參考http://ibatis.apache.org/
br> "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<!-- Always ensure to use the correct XML header as above! -->
INSERT INTO
mapsall06
(id,imageName,
xmin,ymin,xmax,ymax,
scale,valid)
VALUES
(#id#,#imageName#,
#xmin#,#ymin#,#xmax#,#ymax#,
#scale#,#valid#
)
UPDATE mapsall06 A
SET eName = #ename#,
imageName = #imageName#,
xmin = #xmin#, ymin = #ymin#,
xmax = #xmax#,ymax = #ymax#,
scale=#scale#,valid=#valid#
WHERE id = #id#
DELETE mapsall06
WHERE id = #id#
SqlMapConfig.properties用來配置資料庫連線的資訊
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:emap
username=my
password=my
SqlMapConfig.xml用來配置ibatis和指定sqlMap,這裡、指定的為上面
的Maps.xml
br>PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<!-- Always ensure to use the correct XML header as above! -->
<!-- The properties (name="WebRoot/WEB-INF/classes/SqlMapConfig.xml") in the file specified here can be used placeholders in this
config file (e.g. “${driver}”. The file is relative to the classpath and is completely optional. -->
<!-- These settings control SqlMap configuration details, primarily to do with transaction
management. They are all optional (see the Developer Guide for more). -->
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<!-- Type aliases allow you to use a shorter name for long fully qualified class names. -->
<!-- Configure a datasource to use with this SQL Map using SimpleDataSource.
Notice the use of the properties from the above resource -->
<!-- Identify all SQL Map XML files to be loaded by this SQL map. Notice the paths
are relative to the classpath. For now, we only have one… -->
log4j用簡單的DebugLog和Console代替,也是個人習慣。
Test.java 用來測試ibatis的簡單應用。
import java.io.*;
import com.ibatis.sqlmap.client.SqlMapClient;
public class Test {
public Test()
{
}
public void testIbatis() throws Exception
{
SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance();
Integer myMapsPk = new Integer(5);
MyMaps mm = new MyMaps();
mm.setId(1);
mm.setEname("eName");
mm.setImageName("imageName");
mm.setXmax(2);
mm.setYmax(2);
mm.setXmin(1);
mm.setYmin(1);
mm.setScale("5000");
mm.setValid("0");
MyMaps myMaps = (MyMaps) sqlMap.queryForObject ("getMyMaps");
sqlMap.insert("insertMyMaps",mm);
sqlMap.update("updateMyMaps",mm);
Console.debug(myMaps.getImageName());
//DebugLog.writeLog(myMaps.toString());
}
public static void main(String args[])
{
Test test = new Test();
try
{
test.testIbatis();
}
catch(Exception e)
{
Console.debug(e);
}
}
}
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16179598/viewspace-539591/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- ibatis && ibatisnet (續)BAT
- ibatisBAT
- ibatis 使用文件BAT
- ibatis的CURDBAT
- ibatis配置例子BAT
- ibatis 搭建步驟BAT
- ibatis.net demoBAT
- iBATIS vs Hibernate ?BAT
- Ibatis的疑問BAT
- ibatis中integer型別BAT型別
- iBATIS SQL Map簡介。BATSQL
- iBatis中使用事務BAT
- ibatis列印sql語句BATSQL
- ibatis Order By注入問題BAT
- ibatis分頁問題BAT
- iBatis下 in 的寫法BAT
- 再看ibatis Order By注入問題BAT
- ibatis查詢date型別BAT型別
- ibatis 新增DTD 自動提示BAT
- Ibatis相容性問題BAT
- ibatis sqlmaping的問題BATSQLAPI
- iBatis中對映的疑惑BAT
- 抓狂的ibatis中文問題BAT
- 關於maven import org.apache.ibatis.io.Resources中ibatis包不存在問題MavenImportApacheBAT
- ibatis和myBatis的逆向工程使用MyBatis
- Ibatis與Spring搭建過程BATSpring
- mule進階之ibatis componentBAT
- 熟悉ibatis的請幫幫忙!BAT
- iBatis問題,救命啊!!!急急急!!!BAT
- ibatis in語句引數傳入方法BAT
- EJB+IBatis這種做法合理嗎?BAT
- 使用 iBatis (MyBatis)的元註解AnnotationsMyBatis
- 請教關於ibatis的問題BAT
- 關於spring和ibatis的整合SpringBAT
- Ibatis批量更新資料(mysql資料庫)BATMySql資料庫
- java.lang.NoClassDefFoundError: org/apache/ibatis/session/SqlSessionFactoryJavaErrorApacheBATSessionSQL
- Hibernate和Ibatis區別和比較BAT
- eclipse 的ibatis外掛使用方法EclipseBAT