first commit

This commit is contained in:
2025-02-20 14:59:35 +08:00
parent d7be84fac6
commit d4a3bb8ffc
2541 changed files with 336536 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="test"/>
<classpathentry kind="lib" path="lib/zhiqim.jar" sourcepath="libsrc/zhiqim-src.jar"/>
<classpathentry kind="lib" path="libext/hsqldb.jar"/>
<classpathentry kind="lib" path="libext/ojdbc14.jar"/>
<classpathentry kind="lib" path="libext/postgresql-9.4.1211.jre7.jar"/>
<classpathentry kind="lib" path="libext/sqljdbc4.jar"/>
<classpathentry kind="lib" path="libext/zhiqim_mysql5.0.8.jar"/>
<classpathentry kind="lib" path="libext/zhiqim_sqlite3.8.6_native.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>
+2
View File
@@ -0,0 +1,2 @@
/bin
/logs
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>zhiqim_orm</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,13 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8
File diff suppressed because one or more lines are too long
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
+835
View File
@@ -0,0 +1,835 @@
### 什么是“知启蒙数据库映射”?
---------------------------------------
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;“知启蒙数据库映射(ZhiqimORM)”是Zhiqim Development Kit面向数据库开发的多例服务,包括ZSQL规范和三大映射关系(表映射、字段映射和指令映射),有比MyBatis更简单的动态SQL,和比Hibernate更彻底的对象关系映射:<br>
1、数据库二维表和Java对象之间的注解定义映射,表和视图分别对应Java的_Table、_View<br>
2、数据库表列和Java字段的数据格式映射,支持6种数据库的9种数据格式;<br>
3、数据库SQL语句和Java指令映射,基于ZTable、ZView的创建、清空、存在、分页、列表、单条、数目、求和、插入、更新、替换、删除等指令。<br>
<br>
### 知启蒙数据库映射有哪些优点?
---------------------------------------
1、ZhiqimORM仅依赖JDK1.7+和ZhiqimKernel。15年的坚持,值得信赖。<br>
2、ZhiqimORM是基于ZhiqimKernel设计的多例服务,支持配置多个数据库,且自带JDBC连接池。<br>
3、ZhiqimORM的ZSQL语句可以通过XML配置,和Java代码分离,更易查看和检查,支持不同后缀适配不同的数据库;<br>
4、ZhiqimORM的ZSQL/ZDBO规范通过(?、##、$$)三个通配符建立SQL语句和Java对象的映射关联,简洁清晰。<br>
5、ZhiqimORM提供了标准的ZTable规则,对应数据库表设计,大量的基于表的增、删、改、查、列表、分页、统计无需编写SQL语句;<br>
6、ZhiqimORM提供了标签的ZTView规则,对应多表关联设计,大量基于视图的查询、列表、分页和统计无需编写SQL语句。<br>
<br>
### 知启蒙数据库映射目前支持的6种数据库
---------------------------------------
<table style="border-collapse:collapse; border:1px solid #333; height:400px; width:100%">
<tr bgcolor="#f5f5f5">
<td width="8%" align="center">编号</td>
<td width="13%">数据库名称</td>
<td width="28%">常用的驱动</td>
<td width="*">连接URL</td>
</tr>
<tr>
<td align="center">1</td>
<td class="zi-px20 z-bold">mysql</td>
<td>com.mysql.jdbc.Driver</td>
<td>jdbc:mysql://127.0.0.1:3306/zhiqim?useUnicode=true&amp;amp;characterEncoding=UTF-8</td>
</tr>
<tr>
<td align="center">2</td>
<td class="zi-px20 z-bold">oracle</td>
<td>oracle.jdbc.driver.OracleDriver</td>
<td>jdbc:oracle:thin:@127.0.0.1:1521:zhiqim</td>
</tr>
<tr >
<td align="center">3</td>
<td class="zi-px20 z-bold">mssql</td>
<td>com.microsoft.jdbc.sqlserver.SQLServerDriver</td>
<td>jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=zhiqim</td>
</tr>
<tr>
<td align="center">4</td>
<td class="zi-px20 z-bold">postpresql</td>
<td>org.postgresql.Driver</td>
<td>jdbc:postgresql://127.0.0.1:5432/zhiqim</td>
</tr>
<tr>
<td align="center">5</td>
<td>sqlite</td>
<td>org.sqlite.JDBC</td>
<td>jdbc:sqlite:./db/zhiqim.db</td>
</tr>
<tr>
<td align="center">6</td>
<td>hsql</td>
<td>org.hsqldb.jdbc.JDBCDriver</td>
<td>jdbc:hsqldb:./db/zhiqim</td>
</tr>
</table>
<br>
### 知启蒙数据库映射支持的9种数据格式映射
---------------------------------------
<table style="border-collapse:collapse; border:1px solid #333; height:400px; width:100%">
<tr bgcolor="#f5f5f5">
<td width="7%" align="center">编号</td>
<td width="10%">名称</td>
<td width="*">JAVA类型</td>
<td width="11%">MySQL</td>
<td width="13%">Oracle</td>
<td width="11%">MSSQL</td>
<td width="12%">PostpreSQL</td>
<td width="11%">SQLite</td>
<td width="11%">HSQL</td>
</tr>
<tr>
<td colspan="9">基本类型5种</td>
</tr>
<tr>
<td align="center">1</td>
<td>boolean</td>
<td>boolean</td>
<td>tinyint(1)</td>
<td>NUMBER(1)</td>
<td>bit</td>
<td>bool</td>
<td>integer</td>
<td>boolean</td>
</tr>
<tr>
<td align="center">2</td>
<td class="zi-px16 z-bold">byte</td>
<td>int</td>
<td>tinyint(4)</td>
<td>NUMBER(4)</td>
<td>tinyint</td>
<td>int2</td>
<td>integer</td>
<td>tinyint</td>
</tr>
<tr>
<td align="center">3</td>
<td>short</td>
<td>int</td>
<td>smallint(6)</td>
<td>NUMBER(6)</td>
<td>smallint</td>
<td>int2</td>
<td>integer</td>
<td>smalli<br>nt</td>
</tr>
<tr>
<td align="center">4</td>
<td>int</td>
<td>int</td>
<td>int</td>
<td>NUMBER(11)</td>
<td>int</td>
<td>int4</td>
<td>integer</td>
<td>integer</td>
</tr>
<tr>
<td align="center">5</td>
<td>long</td>
<td>long</td>
<td>bigint</td>
<td>NUMBER(20)</td>
<td>bigint</td>
<td>int8</td>
<td>integer</td>
<td>bigint</td>
</tr>
<tr>
<td colspan="9">对象类型2种</td>
</tr>
<tr>
<td align="center">6</td>
<td>string</td>
<td>java.lang.<br>String</td>
<td>varchar<br>char<br>text<br>mediumtext<br>longtext</td>
<td>VARCHAR2<br>CHAR<br>CLOB</td>
<td>varchar<br>char<br>text</td>
<td>varchar<br>char<br>text</td>
<td>varchar<br>char<br>text</td>
<td>varchar<br>char<br>clob</td>
</tr>
<tr >
<td align="center">7</td>
<td>datetime</td>
<td>java.sql.<br>Timestamp</td>
<td>datetime</td>
<td>DATE</td>
<td>datetime</td>
<td>timestamp</td>
<td>datetime</td>
<td>timestamp</td>
</tr>
<tr>
<td colspan="9">特殊类型2种</td>
</tr>
<tr>
<td align="center">8</td>
<td>decimal</td>
<td>double</td>
<td>decimal(m,n)</td>
<td>NUMBER(m,n)</td>
<td>decimal(m,n)</td>
<td>decimal(m,n)</td>
<td>numeric(m,n)</td>
<td>decimal<br>(m,n)</td>
</tr>
<tr>
<td align="center">9</td>
<td>binary</td>
<td>byte[]</td>
<td>mediumblob</td>
<td>BLOB</td>
<td>image</td>
<td>bytea</td>
<td>blob</td>
<td>blob</td>
</tr>
</table>
<br>
### 知启蒙数据库映射使用举例&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/zhiqim-com/V1.5.0/raw/master/ZhiqimExample/zhiqim_guestbook.zip">下载留言本示例</a>
```
/**
* 首页
*
* @version v1.0.0 @author zouzhigang 2016-9-1 新建与整理
*/
public class IndexAction implements Action
{
@Override
public void execute(HttpRequest request) throws Exception
{
int page = request.getParameterInt("page", 1);
int pageSize = request.getContextAttributeInt("page.size", 10);
Selector selector = new Selector();
selector.addOrderbyDesc("messageTime");
PageResult<Message> result = Global.get(ZTable.class).page(Message.class, page, pageSize, selector);
request.setAttribute("result", result);
}
}
```
<br>
### 知启蒙数据库映射指令集
```
/********************************************************************************************/
//exist 表是否存在
/********************************************************************************************/
/**
* 是否存在[表类]对应的[实际表]
*
* @param clazz 表类
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(Class<?> clazz) throws ORMException, SQLException;
/**
* 是否存在[表类]对应的[实际表]月表,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param clazz 表类
* @param month 月份
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean existMonth(Class<?> clazz, String month) throws ORMException, SQLException;
/**
* 是否存在[表类]对应的[实际表],支持表名中有一个替换字段,如LOG_TRACE$ID$
*
* @param clazz 表类
* @param replaceKey 替换键
* @param replaceValue 替换值
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(Class<?> clazz, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 是否存在[表类]对应的[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param clazz 表类
* @param replaceMap 可替换字段表
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(Class<?> clazz, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//create 创建表
/********************************************************************************************/
/**
* 创建[表类]对应的[实际表]
*
* @param clazz 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(Class<?> clazz) throws ORMException, SQLException;
/**
* 创建[表类]对应的[实际表]月表
*
* @param clazz 表类
* @param month 月份
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void createMonth(Class<?> clazz, String month) throws ORMException, SQLException;
/**
* 创建[表类]对应的[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param clazz 表类
* @param replaceMap 可替换字段表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(Class<?> clazz, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//truncate 清空表
/********************************************************************************************/
/**
* 清空[表类]对应的[实际表]
*
* @param clazz 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(Class<?> clazz) throws ORMException, SQLException;
/**
* 清空[表类]对应的[实际表],支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param clazz 表类
* @param month 分月表时使用
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncateMonth(Class<?> clazz, String month) throws ORMException, SQLException;
/**
* 清空[表类]对应的[实际表],支持表名中有一个替换字段,如LOG_TRACE$ID$
*
* @param clazz 表类
* @param replaceKey 替换键
* @param replaceValue 替换值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(Class<?> clazz, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 清空[表类]对应的[实际表],支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param clazz 表类
* @param replaceMap 替换表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(Class<?> clazz, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//insert 插入数据
/********************************************************************************************/
/**
* 增加数据,传入标准[表类]对象
*
* @param data 表对象
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(Object data) throws ORMException, SQLException;
/**
* 增加数据,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param data 表类
* @param month 月份
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insertMonth(Object data, String month) throws ORMException, SQLException;
/**
* 增加数据,支持表或字段中有一个替换字段,如LOG_TRACE$ID$
*
* @param data 表对象
* @param replaceKey 替换键
* @param replaceValue 替换值
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(Object data, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(Object data, MapSS replaceMap) throws ORMException, SQLException;
/**
* 替换数据,传入标准[表类]对象和更新器(取fieldMap和replaceMap)当存在时指定修改的值
*
* @param data 表对象
* @param updater 更新器
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insertOrUpdate(Object data, Updater updater) throws ORMException, SQLException;
/**
* 批量增加数据
*
* @param dataList 表对象列表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] insertBatch(List<?> dataList) throws ORMException, SQLException;
/**
* 批量增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] insertBatch(List<?> dataList, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//replace 替换数据,MYSQL支持,如果有数据先删除后增加
/********************************************************************************************/
/**
* 替换数据,传入标准[表类]对象
*
* @param data 表对象
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(Object data) throws ORMException, SQLException;
/**
* 替换数据,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param data 表对象
* @param month 月份
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replaceMonth(Object data, String month) throws ORMException, SQLException;
/**
* 替换数据,支持表或字段中有一个替换字段,如LOG_TRACE$ID$
*
* @param data 表对象
* @param replaceKey 替换键
* @param replaceValue 替换值
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(Object data, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 替换数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(Object data, MapSS replaceMap) throws ORMException, SQLException;
/**
* 批量替换数据
*
* @param dataList 表对象列表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] replaceBatch(List<?> dataList) throws ORMException, SQLException;
/**
* 批量替换数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] replaceBatch(List<?> dataList, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//update 更新数据
/********************************************************************************************/
/**
* 更新数据,指定更新器需要更新的字段、条件和可替换表
*
* @param clazz 表类
* @param updater 更新器
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Class<?> clazz, Updater updater) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新
*
* @param data 表对象
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Object data) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param data 表对象
* @param month 月份
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int updateMonth(Object data, String month) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持表或字段中有一个替换字段,如LOG_TRACE$ID$
*
* @param data 表对象
* @param replaceKey 替换键
* @param replaceValue 替换值
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Object data, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持可替换表
*
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Object data, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//delete 删除数据
/********************************************************************************************/
/**
* 删除数据,多个主键时使用
*
* @param clazz 表类
* @param ids 关键属性为数组,多个主键
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(Class<?> clazz, Object... ids) throws ORMException, SQLException;
/**
* 删除数据, 根据条件
*
* @param clazz 表类
* @param selector 对象选择器
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(Class<?> clazz, Selector selector) throws ORMException, SQLException;
/********************************************************************************************/
//count 查询数目
/********************************************************************************************/
/**
* 查询数目,多个主键时使用
*
* @param clazz 表类
* @param ids 关键属性值,支持多个
* @return 存在的数目
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> clazz, Object... ids) throws ORMException, SQLException;
/**
* 查询数目,整表查询
*
* @param clazz 表类
* @return int 数目值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> clazz) throws ORMException, SQLException;
/**
* 查询数目,根据条件、可替换表查询
*
* @param clazz 表类
* @param selector 对象查询器
* @return int 数目值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> clazz, Selector selector)throws ORMException, SQLException;
/********************************************************************************************/
//sum 计算总和
/********************************************************************************************/
/**
* 计算总和
*
* @param clazz 表类
* @param field 表字段
* @return 计算总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(Class<?> clazz, String field) throws ORMException, SQLException;
/**
* 计算总和
*
* @param clazz 表类
* @param selector 对象查询器
* @param field 表字段
* @return 计算总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(Class<?> clazz, Selector selector, String field) throws ORMException, SQLException;
/**
* 计算多个总和
*
* @param clazz 表类
* @param selector 对象查询器
* @param fields 多个表字段
* @return 计算多个总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long[] sum(Class<?> clazz, Selector selector, String... fields) throws ORMException, SQLException;
/********************************************************************************************/
//item 查询一条数据
/********************************************************************************************/
/**
* 查询一个表对象,支持多个主键
*
* @param clazz 表类
* @param ids 关键属性值
* @return 返回表对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> clazz, Object... ids) throws ORMException, SQLException;
/**
* 查询一个表对象,并指定返回属性,查询第一行
*
* @param clazz 表类
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> clazz) throws ORMException, SQLException;
/**
* 查询一个表对象,并指定返回属性,查询条件和排序条件
*
* @param clazz 表类
* @param selector 对象查询器
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> clazz, Selector selector) throws ORMException, SQLException;
/********************************************************************************************/
//list 查询列表
/********************************************************************************************/
/**
* 查询表对象列表,全表查询
*
* @param clazz 表类
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz) throws ORMException, SQLException;
/**
* 查询表对象列表,并指定返回属性,查询条件和排序条件
*
* @param clazz 表类
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, Selector selector) throws ORMException, SQLException;
/**
* 查询表对象列表,查询指定的位置的数据
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询表对象列表,并指定位置的,条件和排序条件
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
/********************************************************************************************/
//page 分页显示
/********************************************************************************************/
/**
* 查询表对象分页信息
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> clazz, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询表对象分页信息
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> clazz, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
```
<br>
### 知启蒙数据库映射ZhiqimSQL示例
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ZHIQIM-SQL PUBLIC "-//ZHIQIM //DTD Zhiqim-Sql Configuration 1.5.0//EN" "http://zhiqim.org/xmldtds/zhiqim_sql_1_5_0.dtd">
<zhiqim-sql>
<!-- 插入数据 -->
<sql id="insert_user_info">
<![CDATA[
insert into USER_INFO (USER_ID, USER_NAME, USER_PASS, USER_EMAIL, USER_NICK, USER_AVATAR)
values (#USER_ID#, #USER_NAME#, #USER_PASS#, #USER_EMAIL#, #USER_NICK#, #USER_AVATAR#)
]]>
</sql>
<!-- 删除数据 -->
<sql id="delete_user_info">
<![CDATA[
delete from USER_INFO where USER_ID=#USER_ID#
]]>
</sql>
<!-- 更新全部数据 -->
<sql id="update_user_info">
<![CDATA[
update USER_INFO set USER_NAME=#USER_NAME#, USER_PASS=#USER_PASS#, USER_EMAIL=#USER_EMAIL#, USER_NICK=#USER_NICK#, USER_AVATAR=#USER_AVATAR#
where USER_ID=#USER_ID#
]]>
</sql>
<!-- 查询指定数据 -->
<sql id="select_user_info">
<![CDATA[
select USER_NAME, USER_NICK from USER_INFO
where USER_NICK like '%#USER_NICK#%' and USER_EMAIL=#USER_EMAIL#
]]>
</sql>
<!-- 按月存储日志,查指定MONTH的日志列表 -->
<sql id="query_user_log">
<![CDATA[
select * from USER_LOG_$MONTH$ where USER_ID=?
]]>
</sql>
</zhiqim-sql>
```
<br>
### 知启蒙技术框架与交流
---------------------------------------
![知启蒙技术框架架构图](https://images.gitee.com/uploads/images/2018/0907/171951_230c3a33_2134900.png "知启蒙技术框架架构图.png")
<br><br>
QQ群:加入QQ交流群,请点击[【458171582】](https://jq.qq.com/?_wv=1027&k=5DWlB3b) <br><br>
教程:欲知更多知启蒙数据库映射,[【请戳这里】](https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm/tutorial/index.htm)
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ZHIQIM-CONFIG PUBLIC "-//ZHIQIM //DTD Zhiqim-Config Configuration 1.5.0//EN" "http://zhiqim.org/xmldtds/zhiqim_config_1_5_0.dtd">
<zhiqim-config>
<group id="logging" desc="日志配置">
<item key="logging.info" value="debug-info" type="protected" desc="信息日志配置" />
<item key="logging.error" value="error-fatal" type="protected" desc="错误日志配置" />
</group>
<group id="logging.info" desc="信息日志配置">
<item key="console.out" value="true" type="protected" desc="是否输出到控制台" />
<item key="file.out" value="true" type="protected" desc="是否输出到文件" />
<item key="file.path" value="./logs/info.log" type="protected" desc="输出到文件路径" />
</group>
<group id="logging.error" desc="错误日志配置">
<item key="console.out" value="true" type="protected" desc="是否输出到控制台" />
<item key="file.out" value="true" type="protected" desc="是否输出到文件" />
<item key="file.path" value="./logs/error.log" type="protected" desc="输出到文件路径" />
</group>
</zhiqim-config>
+47
View File
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ZHIQIM-SQL PUBLIC "-//ZHIQIM //DTD Zhiqim-Sql Configuration 1.5.0//EN" "http://zhiqim.org/xmldtds/zhiqim_sql_1_5_0.dtd">
<zhiqim-sql>
<!-- 插入数据 -->
<sql id="insert_user_info2">
<![CDATA[
insert into USER_INFO (USER_ID, USER_NAME, USER_PASS, USER_EMAIL, USER_NICK, USER_AVATAR)
values (#USER_ID#, #USER_NAME#, #USER_PASS#, #USER_EMAIL#, #USER_NICK#, #USER_AVATAR#)
]]>
</sql>
<!-- 更新全部数据 -->
<sql id="update_user_info2">
<![CDATA[
update USER_INFO set USER_NAME=#USER_NAME#, USER_PASS=#USER_PASS#, USER_EMAIL=#USER_EMAIL#, USER_NICK=#USER_NICK#, USER_AVATAR=#USER_AVATAR#
where USER_ID=#USER_ID#
]]>
</sql>
<!-- 更新指定数据 -->
<sql id="update_user_name">
<![CDATA[
update USER_INFO set USER_NAME=#USER_NAME#
where USER_ID=#USER_ID#
]]>
</sql>
<!-- 删除数据 -->
<sql id="delete_user_info2">
<![CDATA[
delete from USER_INFO where USER_ID=#USER_ID#
]]>
</sql>
<sql id="query_a_user_info2">
<![CDATA[
select * from USER_INFO where USER_ID=?
]]>
</sql>
<sql id="query_list_user_info2">
<![CDATA[
select * from USER_INFO where USER_NAME like '%?%'
]]>
</sql>
</zhiqim-sql>
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ZHIQIM-CONFIG PUBLIC "-//ZHIQIM //DTD Zhiqim-Config Configuration 1.5.0//EN" "http://zhiqim.org/xmldtds/zhiqim_config_1_5_0.dtd">
<zhiqim-config>
<group id="boot" desc="系统启动配置">
<item key="name" value="知启蒙" type="protected" desc="系统名称" />
<item key="version" value="1.4.1" type="protected" desc="系统版本" />
<item key="port" value="50080" type="private" desc="系统监听端口,用于启动监听和命令关闭工程" />
<item key="include" value="./lib/*,*/bin" type="protected" desc="扫描包含库模式,多个用逗号隔开,星号表示通配符" />
<item key="libext" value="./libext" type="protected" desc="加载的库目录" />
</group>
<group id="config" desc="系统其他配置文件,./开头表示工程相对路径下,绝对路径使用/或d:/等(Windows也使用顺斜杠作路径)">
<item key="logging" value="./conf/logging.xml" type="protected" desc="日记配置"/>
</group>
<group id="service" desc="系统服务配置,有依赖时注意顺序,系统按顺序加载,按倒序销毁">
<item key="logging" value="org.zhiqim.kernel.logging.LogServer" type="protected" desc="日志服务"/>
<item key="logcutter" value="org.zhiqim.kernel.logging.LogLinuxNohupCutter" type="protected" desc="日志LinuxNohup切割服务"/>
<item key="orm" value="org.zhiqim.orm.ORMServer" type="protected" desc="数据库服务"/>
</group>
<group id="orm" desc="数据库映射服务">
<item key="dbType" value="mysql" type="protected" desc="数据库类型,支持oracle|mysql|mssql|hsql|sqlite" />
<item key="driver" value="com.mysql.jdbc.Driver" type="protected" desc="数据库驱动" />
<item key="url" value="jdbc:mysql://127.0.0.1:3306/zhiqim_manager?useUnicode=true&amp;characterEncoding=UTF-8" type="protected" desc="数据库Url" />
<item key="user" value="root" type="protected" desc="数据库用户名" />
<item key="pass" value="root" type="private" desc="数据库密码" />
<item key="minPoolSize" value="2" type="protected" desc="线程池最小值" />
<item key="maxPoolSize" value="10" type="protected" desc="线程池最大值" />
<item key="maxIdleTime" value="maxKeepTime" type="protected" desc="每连接最大空闲时间,大于该值将重建连接" />
<item key="preConnCheckAvailable" value="false" type="protected" desc="每连接获取或释放时都检查是否可以" />
<item key="isQuerySqlLog" value="true" type="protected" desc="是否输出查询SQL日志" />
<item key="isUpdateSqlLog" value="true" type="protected" desc="是否输出更新SQL日志" />
</group>
<group id="orm.sql" desc="数据库映射服务">
<item key="/org/zhiqim/orm/test/data/sql/test.sql.xml" value="classpath" type="protected" desc="测试SQL类文件" />
<item key="/org/zhiqim/orm/test/data/sql2/" value="package" type="protected" desc="测试SQL类包" />
<item key="./conf/orm2.sql.xml" value="file" type="protected" desc="测试SQL文件" />
<item key="./sql" value="folder" type="protected" desc="测试SQL目录" />
</group>
<group id="sqliteORM" desc="数据库映射服务">
<item key="dbType" value="sqlite" type="protected" desc="数据库类型,支持oracle|mysql|mssql|hsql|sqlite" />
<item key="driver" value="org.sqlite.JDBC" type="protected" desc="数据库驱动" />
<item key="url" value="jdbc:sqlite:./db/abc.db" type="protected" desc="数据库Url" />
<item key="user" value="root" type="protected" desc="数据库用户名" />
<item key="pass" value="taobug2012" type="protected" desc="数据库密码" />
<item key="minPoolSize" value="2" type="protected" desc="线程池最小值" />
<item key="maxPoolSize" value="10" type="protected" desc="线程池最大值" />
<item key="initPoolSize" value="2" type="protected" desc="线程池初始值" />
<item key="checkTime" value="61" type="protected" desc="检查数据库是否断开时间间隔" />
<item key="maxIdleTime" value="13600" type="protected" desc="每连接最大空闲时间,大于该值将重建连接" />
<item key="preConnCheckAvailable" value="false" type="protected" desc="每连接获取或释放时都检查是否可以" />
</group>
</zhiqim-config>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
/*C1*/SET SCHEMA SYSTEM_LOBS
INSERT INTO BLOCKS VALUES(0,2147483647,0)
COMMIT
/*C3*/SET SCHEMA PUBLIC
create table if not exists T_INTEGER ( T_ID bigint NOT NULL, T_BOOLEAN boolean NOT NULL, T_BYTE tinyint NOT NULL, T_SHORT smallint NOT NULL, T_INT integer NOT NULL, T_LONG bigint NOT NULL, primary key (T_ID) )
create table if not exists T_STRING ( T_ID bigint NOT NULL, T_CHAR char(19) NULL, T_VARCHAR varchar(32) NULL, T_STRING2000 varchar(2000) NULL, T_STRING4000 varchar(4000) NULL, T_STRING8000 varchar(8000) NULL, T_STRING16000 clob NULL, primary key (T_ID) )
create table if not exists T_DATETIME ( T_ID bigint NOT NULL, T_DATETIME timestamp NOT NULL, T_DATETIME2 timestamp NOT NULL, primary key (T_ID) )
create table if not exists T_DECIMAL ( T_ID bigint NOT NULL, T_DM5_2 decimal(5,2) NOT NULL, T_DM10_3 decimal(10,3) NOT NULL, T_DM15_4 decimal(15,4) NOT NULL, primary key (T_ID) )
/*C2*/SET SCHEMA PUBLIC
DISCONNECT
/*C3*/DISCONNECT
/*C4*/SET SCHEMA PUBLIC
DISCONNECT
/*C5*/SET SCHEMA PUBLIC
DISCONNECT
/*C6*/SET SCHEMA PUBLIC
DISCONNECT
/*C7*/SET SCHEMA PUBLIC
DISCONNECT
+5
View File
@@ -0,0 +1,5 @@
#HSQL Database Engine 2.3.4
#Sat Dec 24 17:58:13 CST 2016
version=2.3.4
modified=yes
tx_timestamp=0
+43
View File
@@ -0,0 +1,43 @@
SET DATABASE UNIQUE NAME HSQLDB59304433B3
SET DATABASE GC 0
SET DATABASE DEFAULT RESULT MEMORY ROWS 0
SET DATABASE EVENT LOG LEVEL 0
SET DATABASE TRANSACTION CONTROL LOCKS
SET DATABASE DEFAULT ISOLATION LEVEL READ COMMITTED
SET DATABASE TRANSACTION ROLLBACK ON CONFLICT TRUE
SET DATABASE TEXT TABLE DEFAULTS ''
SET DATABASE SQL NAMES FALSE
SET DATABASE SQL REFERENCES FALSE
SET DATABASE SQL SIZE TRUE
SET DATABASE SQL TYPES FALSE
SET DATABASE SQL TDC DELETE TRUE
SET DATABASE SQL TDC UPDATE TRUE
SET DATABASE SQL TRANSLATE TTI TYPES TRUE
SET DATABASE SQL TRANSLATE TTI TYPES TRUE
SET DATABASE SQL CONCAT NULLS TRUE
SET DATABASE SQL UNIQUE NULLS TRUE
SET DATABASE SQL CONVERT TRUNCATE TRUE
SET DATABASE SQL AVG SCALE 0
SET DATABASE SQL DOUBLE NAN TRUE
SET FILES WRITE DELAY 500 MILLIS
SET FILES BACKUP INCREMENT TRUE
SET FILES CACHE SIZE 10000
SET FILES CACHE ROWS 50000
SET FILES SCALE 32
SET FILES LOB SCALE 32
SET FILES DEFRAG 0
SET FILES NIO TRUE
SET FILES NIO SIZE 256
SET FILES LOG TRUE
SET FILES LOG SIZE 50
CREATE USER SA PASSWORD DIGEST 'd41d8cd98f00b204e9800998ecf8427e'
ALTER USER SA SET LOCAL TRUE
CREATE SCHEMA PUBLIC AUTHORIZATION DBA
ALTER SEQUENCE SYSTEM_LOBS.LOB_ID RESTART WITH 1
SET DATABASE DEFAULT INITIAL SCHEMA PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.SQL_IDENTIFIER TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.YES_OR_NO TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.TIME_STAMP TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.CARDINAL_NUMBER TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.CHARACTER_DATA TO PUBLIC
GRANT DBA TO SA
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<section name="zhiqim">
<section name="ExportJar">
<item value="logs/*" key="excludeDirs"/>
<item value="dbo,test" key="excludePackages"/>
<item value="false" key="isDivided"/>
<item value="true" key="isExportAndZipProject"/>
<item value="true" key="isExportJavaSource"/>
<item value="false" key="isIncludeJavaFile"/>
<item value="zhiqim_orm" key="jarName"/>
<item value="D:/_gitcan/ZhiqimDK/zhiqim_orm/document/metainfo" key="metaInfoPath"/>
<item value="zhiqim_orm_v1.5.0" key="projectSourceName"/>
<item value="D:/_gitee/zhiqim/V1.5.0/ZhiqimDK" key="releasePath"/>
</section>
</section>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<section name="zhiqim">
<section name="ExportJar">
<item value="logs/*" key="excludeDirs"/>
<item value="dbo,test" key="excludePackages"/>
<item value="false" key="isDivided"/>
<item value="true" key="isExportAndZipProject"/>
<item value="true" key="isIncludeJavaFile"/>
<item value="zhiqim_orm" key="jarName"/>
<item value="D:/_gitcan/ZhiqimDK/zhiqim_orm/document/metainfo" key="metaInfoPath"/>
<item value="zhiqim_orm_v1.5.1" key="projectSourceName"/>
<item value="D:/_gitee/zhiqim/V1.5.1/ZhiqimDK" key="releasePath"/>
</section>
</section>
+16
View File
@@ -0,0 +1,16 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: ZhiqimORM
Bundle-SymbolicName: zhiqim_orm
Bundle-Version: 1.5.0
Export-Package: org.zhiqim.orm,
org.zhiqim.orm.annotation,
org.zhiqim.orm.config,
org.zhiqim.orm.datasource,
org.zhiqim.orm.dbo,
org.zhiqim.orm.dbo.condition,
org.zhiqim.orm.dbo.defined,
org.zhiqim.orm.executor,
org.zhiqim.orm.policy
Require-Bundle: zhiqim
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
+90
View File
@@ -0,0 +1,90 @@
V1.0.1.R2014022701
1)版本创建、整理
2)版本内部发布测试
3)版本内部测试完成,发布
V1.0.3.R2014060101
1)20140521修改"初始化DBO和STMT失败",改成"初始化DBO和SQL失败"
2)20140521增加FREL对表是否存在进行检查,如果不存在则创建加入缓存,下次认为存在
3)20140527增加Updater时对表达式的支持如updater.addFieldExpression("buyNum", "buyNum+1");表示在原值上加1
4)20140601修改FDBOExecutor.create中对replace表的BUG。原没有作replaceMap处理
V1.0.5.R2014081201
1)fadfox.jar增加JSON功能和HTTPC功能,涉及到ORM要求调整
2)对返回的ArrayList数据,作timeToSize()处理,优化内存
3)修改ORMServer中对多例配置的错误
V1.0.6.R2015011201
1)调整StringBuffer成StringBuilder
2)修改TransactionManager.beginTransaction()方法为获取第一个ORMServer,以前有BUG,并增加通过index和name获取ORMServer
3)修改FDBOExecutor中FDBO["+dbo.getName()+"]配置中未找到["+field.getField()+"]字段,的描述,原来的表达不正确
4)fadfox.jar调整DateTimes类方法,有影响,要求版本在V1.0.6R2015011201以上
V1.0.7.R2015052501
1)拆分FDataSource中getConnection时同步锁connList为两步,防止锁太大带来死锁
2)支持连接耗尽时,配置等待时长和重试次数,系统默认是5秒和1次
3)修改等待时长打印日志的错误
4)fadfox.jar修改了queryEndsWithFile方法
V1.1.0.R2015072901
1)根据fadfox整理成统一该版本
V1.1.1.R2015091401版本:
1)使用JDK1.7编译,增加ORMServer加载.xml时文件时否存在检查
V1.1.2.R2015102601
1)要求使用V1.1.2版本的fadfox.jar
2)修改FDbo为FTable,后期进行调整
3)修改for调用方式,合并Documents到Xmlx中
V1.1.3.R2016020301
1)春节前整理版本号
2)根据FTimer改动修改的版本
V1.2.0.R2016072101
1)调整FSQL配置,删除原来的<executeQuery>和<executeUpdate>,改成<sql id="id">content</sql>,更简单且更好理解
2)调整FSQL实现,对配置中删除的param和result两个配置,改成通过实时传入验证
3)调整FDBO成FTable,类似于表,更好记和理解
4)调整FREHL成FView,类似于视图,更好记和理解
5)调整Selector和Updater中的addWhere成addMaybe,表示如果且为null就不作为条件,与addMust必须不能为空,更好理解。
6)修改原throw new IlleglParameterException为throw Asserts.exception()和Asserts.asserts()
V1.2.1.R2016100801
1)增加对SQLite的支持,删除对Access的支持
2)修改SQL文件加载方式,以前是在classpath逐个查找,可能会碰到类或jar不允许加载,修改为通过orm.sql进行配置,配置支持file,folder,classpath,package四种
3)增加policy接口,以便支持6种数据库的适配
V1.2.2.R2017010101
1)配合fadfox.jar调整HashMap<String, Object>为FHashMapSO
2)增加FTabler对非持久化表(运行时增加的表)处理
3)增加FSQLer对DDL语句的处理,如修改表名,修改列名,修改列类型,增删列
V1.3.0.R2017022701
1)增加insertOrUpdate方法,是mysql特有的根据条件指定更新一些字段,而replace是更新所有字段
2)增加list读取指定位置的数据,支持pageNo和pageSize两个参数
3)增加对selector和updater的字段值和数据库要求进行强制检查,不一致不允许操作
4)增加对自连表、多表关联的视图时的别名的支持
5)修改判断字段的值是否合法,增加允许为null时传入null值
V1.3.1.R2017052801
1)修改Asserts.asserts为Asserts.as()方法,使用三目运算断言,防止断言为真时需要初始化无意义的断言失败字符串
2)增加ORMI18n类,实现国际化字符串静态字符串展示,当前用于断言失败字符串
3)增加select @@IDENTITY的处理方法Global.get(FSQL.class).identityInt()和identityLong()获取事务线程中的自增ID
4)修改isValidSelector和isValidUpdater方法,显示错误的字段信息
5)修复SQL中转义字符组装SQL时的BUG
6)修改连接池中,获取连接时,先检查是否活动中,活动中的连接优先跳过,以前是先判断是否有效,可能导致最后一次有效时被删除。
V1.3.2.R2017080501
1)修改boolean型的判断方法,如isTest字段,设置方法为void setTest(boolean isTest),判断方法为boolean isTest()
2)增加not like的支持,并修改方法中value值为Object,方便传入整型和长整型
3)增加orm.cache缓存表类的配置和实现,注意count/sum方法还是直接查数据库,item/list/page查缓存,insert/insertBatch/replace/update/delete更新缓存
4)增加FSQL.execute方法对SQLite数据时修改truncate为delete from
V1.3.3.R2017110601
1)增加selector表达式条件
2)增加selector左右联left join,right jon支持增加条件selector.addJoin(FDbo.class, new Selector("field", value));
3)修改原HashMap<String, Object>为FHashMapSO
V1.4.0.R2018010101
1)正式启用ZhiqimORM名称,原所有Fadfox改为Zhiqim,原所有fadfox改为zhiqim,原所有FADFOX改为ZHIQIM,原com.zhiqim.fadfox改为org.zhiqim.kernel
2)修改包结构,整理F前缀,更改ZSQLer为ZDDL
3)增加MySQL启动时对wait_timeout的检查,要求大于配置的3分钟
4)增加ZDDL.toColumnType(String fieldType, String fieldLength)
5)增加对SQLite的主键修改的独立处理功能
6)修改当服务关闭时没有从Global移除ZTable等实例的BUG
7)Class.forName修改成Classes.forName,防止ClassLoader不准确
V1.4.1.R2018072501
1)优化配置中当maxIdleTime未配置时取maxKeepTime
2)修改表缓存,支持@AnAlias别名作为key,增加表缓存定时刷新缓存,格式采用scheduler的格式
3)优化表缓存,修改排序不准确的BUG
V1.5.0.R2019010101
1)修改工程名为zhiqim_orm,使用zhiqim_kernel_v1.5.0_r2019010101库
2)增加IsEmpty和IsNotEmpty条件,由于MySQL中null和空字符串''不相等
3)增加存储过程的ZSQL支持,通过CallParam和CallResult传参和读取多结果,结果支持MAP和DBO
4)修复ORMServer关闭时没有把testConnnectioner关闭的的BUG
5)修复ZTabler未实现多例模式的BUG(导致多数据库配置失败)
6)根据zhiqim_kernel修改继承自Tasker到实现TaskEvery/Timer修改为Interval,修改为Threadx的处理方式
+129
View File
@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="UTF-8"?>
<zhiqim-dbo>
<config version="1.2.0" dbType="mysql" folder="../test" initDataWidth="1000">
<![CDATA[
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
]]>
</config>
<package name="org.zhiqim.orm.test.dbo" type="true" desc="系统配置表">
<table name="T_INTEGER" desc="整型测试表" key="T_ID" type="InnoDB">
<field column="T_ID" type="long" length="" notNull="true" desc="测试编号"/>
<field column="T_BOOLEAN" type="boolean" length="" notNull="true" desc="布尔型"/>
<field column="T_BYTE" type="byte" length="" notNull="true" desc="字节型"/>
<field column="T_SHORT" type="short" length="" notNull="true" desc="短整型"/>
<field column="T_INT" type="int" length="" notNull="true" desc="整型"/>
<field column="T_LONG" type="long" length="" notNull="true" desc="长整型"/>
<data PARAM_UPDATE="0" PARAM_DESC="是否使用管理页登录退出功能" GROUP_ID="zhiqim.manager" PARAM_POS="1" PARAM_VALUE="false" PARAM_KEY="hasManageLogin"/>
<data PARAM_UPDATE="1" PARAM_DESC="是否使用操作员组功能" GROUP_ID="zhiqim.manager" PARAM_POS="2" PARAM_VALUE="false" PARAM_KEY="hasOperatorGroup"/>
</table>
<table name="T_STRING" desc="测试字符串" key="T_ID" type="InnoDB">
<field column="T_ID" type="long" length="" notNull="true" desc="测试编号"/>
<field column="T_CHAR" type="string" length="19,char" notNull="false" desc="定长字符串"/>
<field column="T_VARCHAR" type="string" length="32" notNull="false" desc="变长字符串"/>
<field column="T_STRING2000" type="string" length="2000" notNull="false" desc="变成2000长度"/>
<field column="T_STRING4000" type="string" length="4000" notNull="false" desc="变长4000长度"/>
<field column="T_STRING8000" type="string" length="8000" notNull="false" desc="变长8000长度"/>
<field column="T_STRING16000" type="string" length="16000" notNull="false" desc="变长16000长度"/>
</table>
<table name="T_DATETIME" desc="测试日期格式" key="T_ID" type="InnoDB">
<field column="T_ID" type="long" length="" notNull="true" desc="测试编号"/>
<field column="T_DATETIME" type="datetime" length="" notNull="true" desc="测试日期"/>
<field column="T_DATETIME2" type="datetime" length="" notNull="true" desc="测试日期"/>
</table>
<table name="T_DECIMAL" desc="测试小数格式" key="T_ID" type="InnoDB">
<field column="T_ID" type="long" length="" notNull="true" desc="测试编号"/>
<field column="T_DM5_2" type="decimal" length="5,2" notNull="true" desc="测试5位长度,小数2位"/>
<field column="T_DM10_3" type="decimal" length="10,3" notNull="true" desc="测试10位长度,小数3位"/>
<field column="T_DM15_4" type="decimal" length="15,4" notNull="true" desc="测试15位长度,小数4位"/>
</table>
<table name="T_AUTO" desc="测试自增长字段" key="T_ID" type="InnoDB">
<field column="T_ID" type="long" length="" notNull="true" desc="测试编号"/>
<field column="T_VARCHAR" type="string" length="32" notNull="false" desc="变长字符串"/>
</table>
<table name="MESSAGE" desc="留言表" key="MESSAGE_ID" type="InnoDB">
<field column="MESSAGE_ID" type="long" length="" notNull="true" desc="留言编号"/>
<field column="MESSAGE_NAME" type="string" length="32" notNull="true" desc="访客称呼"/>
<field column="MESSAGE_CONTACTING" type="string" length="50" notNull="false" desc="访客联系方式"/>
<field column="MESSAGE_CONTENT" type="string" length="1000" notNull="true" desc="访客留言内容"/>
<field column="MESSAGE_TIME" type="string" length="19,char" notNull="true" desc="访客留言时间"/>
<field column="MESSAGE_RTIME" type="string" length="19,char" notNull="false" desc="管理员回复时间"/>
<field column="MESSAGE_REPLY" type="string" length="1000" notNull="false" desc="管理员回复内容"/>
</table>
<table name="ADMIN" desc="管理员表" key="ADMIN_NAME" type="InnoDB">
<field column="ADMIN_NAME" type="string" length="32" notNull="true" desc="管理员名称"/>
<field column="ADMIN_PASS" type="string" length="32" notNull="true" desc="管理员密码"/>
<field column="ADMIN_TIME" type="string" length="19,char" notNull="true" desc="管理员时间"/>
<data ADMIN_NAME="admin" ADMIN_PASS="111111"/>
</table>
<table name="ORDER" desc="订单表" key="ORDER_ID" type="InnoDB">
<field column="ORDER_ID" type="long" length="" notNull="true" desc="订单编号"/>
</table>
</package>
<package name="org.zhiqim.orm.test.dboext" type="true" desc="系统配置表">
<view name="T_INTEGER_STRING" type="true" desc="整型和字符串视图" table="T_INTEGER,T_STRING">
<join type="EQUAL" lTable="T_INTEGER" lColumn="T_ID" rTable="T_STRING" rColumn="T_ID"/>
<field column="*" table="T_INTEGER"/>
<field column="T_CHAR" table="T_STRING"/>
<field column="T_VARCHAR" table="T_STRING"/>
</view>
<view name="T_INTEGER_DATETIME" type="true" desc="整型和时间视图" table="T_INTEGER,T_DATETIME">
<join type="EQUAL" lTable="T_INTEGER" lColumn="T_ID" rTable="T_DATETIME" rColumn="T_ID"/>
<field column="*" table="T_INTEGER"/>
<field column="T_DATETIME" table="T_DATETIME"/>
</view>
<view name="T_INTEGER_DECIMAL" type="true" desc="整型和小数视图" table="T_INTEGER,T_DECIMAL">
<join type="EQUAL" lTable="T_INTEGER" lColumn="T_ID" rTable="T_DECIMAL" rColumn="T_ID"/>
<field column="T_ID" table="T_INTEGER"/>
<field column="T_BOOLEAN" table="T_INTEGER"/>
<field column="T_DM5_2" table="T_DECIMAL"/>
<field column="T_DM10_3" table="T_DECIMAL"/>
</view>
<view name="T_INTEGER_STRING_LEFT" type="true" desc="整型和字符串左联视图" table="T_INTEGER,T_STRING">
<join type="LEFT" lTable="T_INTEGER" lColumn="T_ID" rTable="T_STRING" rColumn="T_ID"/>
<field column="*" table="T_INTEGER"/>
<field column="T_CHAR" table="T_STRING"/>
<field column="T_VARCHAR" table="T_STRING"/>
</view>
</package>
</zhiqim-dbo>
@@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<zhiqim-dbo>
<config version="1.2.0" dbType="postgresql" folder="../test" initDataWidth="820">
<![CDATA[
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
]]>
</config>
<package name="org.zhiqim.orm.test.qc.dbo" type="true" desc="问答定义表">
<table name="QC_QUESTION$ID$" desc="问答问题表" key="QUESTION_ID" type="InnoDB">
<field column="QUESTION_ID" type="long" length="" notNull="true" desc="问题编号"/>
<field column="QUESTION_TYPE" type="int" length="" notNull="true" desc="问题类型: 0技术疑问 1职业疑惑 2生活杂谈 3资讯动态 4其他"/>
<field column="QUESTION_STATUS" type="int" length="" notNull="true" desc="问题状态:0表示正常,1表示停用"/>
<field column="QUESTION_TITLE" type="string" length="100" notNull="true" desc="问题标题"/>
<field column="QUESTION_DESC" type="string" length="4000" notNull="true" desc="问题描述"/>
<field column="QUESTION_USER_ID" type="long" length="" notNull="true" desc="问题作者编号"/>
<field column="QUESTION_CREATE_TIME" type="string" length="19,char" notNull="true" desc="问题发表时间"/>
<field column="QUESTION_REPLY_NUM" type="int" length="" notNull="true" desc="问题评论数"/>
<field column="QUESTION_READ_NUM" type="int" length="" notNull="true" desc="问题阅读数"/>
</table>
<table name="QC_COMMENT" desc="问答评论表" key="QUESTION_ID,COMMENT_ID" type="InnoDB">
<field column="QUESTION_ID" type="long" length="" notNull="true" desc="问题编号"/>
<field column="COMMENT_ID" type="long" length="" notNull="true" desc="评论编号"/>
<field column="COMMENT_CONTENT" type="string" length="4000" notNull="true" desc="评论内容"/>
<field column="COMMENT_USER_ID" type="long" length="" notNull="true" desc="评论作者编号"/>
<field column="COMMENT_GOOD_NUM" type="int" length="" notNull="true" desc="点赞数"/>
<field column="COMMENT_CREATE_TIME" type="string" length="19,char" notNull="true" desc="评论发表时间"/>
</table>
<table name="QC_ANSWER" desc="回复表" key="COMMENT_ID,ANSWER_ID" type="InnoDB">
<field column="QUESTION_ID" type="long" length="" notNull="true" desc="问题编号"/>
<field column="COMMENT_ID" type="long" length="" notNull="true" desc="评论编号"/>
<field column="ANSWER_ID" type="long" length="" notNull="true" desc="回复编号"/>
<field column="COMMENT_USER_ID" type="long" length="" notNull="true" desc="评论作者编号"/>
<field column="ANSWER_CONTENT" type="string" length="2000" notNull="true" desc="回复内容"/>
<field column="ANSWER_USER_ID" type="long" length="" notNull="true" desc="回复作者编号"/>
<field column="ANSWER_TIME" type="string" length="19,char" notNull="true" desc="回复时间"/>
</table>
<table name="QC_GOOD" desc="点赞表" key="COMMENT_ID,GOOD_USER_ID" type="InnoDB">
<field column="COMMENT_ID" type="long" length="" notNull="true" desc="评论编号"/>
<field column="GOOD_USER_ID" type="long" length="" notNull="true" desc="点赞人编号"/>
</table>
<table name="USER_ACCOUNT" desc="用户表" key="USER_ID" type="InnoDB">
<field column="USER_ID" type="long" length="" notNull="true" desc="用户编号"/>
<field column="USER_NICK" type="string" length="32" notNull="false" desc="用户昵称"/>
<field column="USER_AVATAR_50" type="string" length="200" notNull="false" desc="用户头像"/>
</table>
</package>
<package name="org.zhiqim.orm.test.qc.ex" type="true" desc="问答扩展表">
<view name="QUESTION_EX" type="true" desc="问题扩展表" table="QC_QUESTION$ID$,USER_ACCOUNT">
<join type="EQUAL" lTable="QC_QUESTION$ID$" lColumn="QUESTION_USER_ID" rTable="USER_ACCOUNT" rColumn="USER_ID"/>
<field column="USER_NICK" table="USER_ACCOUNT"/>
<field column="USER_AVATAR_50" table="USER_ACCOUNT"/>
<field column="*" table="QC_QUESTION$ID$"/>
</view>
<view name="COMMENT_EX" type="true" desc="评论扩展表" table="QC_COMMENT,USER_ACCOUNT">
<join type="EQUAL" lTable="QC_COMMENT" lColumn="COMMENT_USER_ID" rTable="USER_ACCOUNT" rColumn="USER_ID"/>
<field column="USER_NICK" table="USER_ACCOUNT"/>
<field column="USER_AVATAR_50" table="USER_ACCOUNT"/>
<field column="*" table="QC_COMMENT"/>
</view>
<view name="ANSWER_EX" type="true" desc="回复扩展表" table="QC_ANSWER,USER_ACCOUNT a,USER_ACCOUNT b">
<join type="EQUAL" lTable="QC_ANSWER" lColumn="ANSWER_USER_ID" rTable="a" rColumn="USER_ID"/>
<join type="LEFT" lTable="QC_ANSWER" lColumn="COMMENT_USER_ID" rTable="b" rColumn="USER_ID"/>
<field column="USER_NICK ANSWER_USER_NICK" table="a"/>
<field column="USER_AVATAR_50 ANSWER_USER_AVATAR_50" table="a"/>
<field column="USER_NICK COMMENT_USER_NICK" table="b"/>
<field column="USER_AVATAR_50 COMMENT_USER_AVATAR_50" table="b"/>
<field column="*" table="QC_ANSWER"/>
</view>
</package>
</zhiqim-dbo>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+42
View File
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ZHIQIM-SQL PUBLIC "-//ZHIQIM //DTD Zhiqim-Sql Configuration 1.5.0//EN" "http://zhiqim.org/xmldtds/zhiqim_sql_1_5_0.dtd">
<zhiqim-sql>
<!-- 插入数据 -->
<sql id="insert_user_info3">
<![CDATA[
insert into USER_INFO (USER_ID, USER_NAME, USER_PASS, USER_EMAIL, USER_NICK, USER_AVATAR)
values (#USER_ID#, #USER_NAME#, #USER_PASS#, #USER_EMAIL#, #USER_NICK#, #USER_AVATAR#)
]]>
</sql>
<!-- 删除数据 -->
<sql id="delete_user_info3">
<![CDATA[
delete from USER_INFO where USER_ID=#USER_ID#
]]>
</sql>
<!-- 更新全部数据 -->
<sql id="update_user_info3">
<![CDATA[
update USER_INFO set USER_NAME=#USER_NAME#, USER_PASS=#USER_PASS#, USER_EMAIL=#USER_EMAIL#, USER_NICK=#USER_NICK#, USER_AVATAR=#USER_AVATAR#
where USER_ID=#USER_ID#
]]>
</sql>
<!-- 查询指定数据 -->
<sql id="select_user_info3">
<![CDATA[
select USER_NAME, USER_NICK from USER_INFO
where USER_NICK like '%#USER_NICK#%' and USER_EMAIL=#USER_EMAIL#
]]>
</sql>
<!-- 按月存储日志,查指定MONTH的日志列表 -->
<sql id="query_user_log3">
<![CDATA[
select * from USER_LOG_$MONTH$ where USER_ID=?
]]>
</sql>
</zhiqim-sql>
+270
View File
@@ -0,0 +1,270 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.control.Configurable;
import org.zhiqim.kernel.util.Asserts;
/**
* ORM工具类,简化获取ORMServer的方法
*
* @version v1.0.0 @author zouzhigang 2018-11-26 新建与整理
*/
@AnAlias("ORM")
public class ORM implements ORMConstants
{
/***********************************************************************************/
//ORM通用对象
/***********************************************************************************/
/** 获取ORM中的第一个对象 */
public static <T> T get(Class<T> cls)
{
return get(cls, 0);
}
/** 获取ORM中指定可配置对象 */
public static <T> T get(Class<T> cls, Configurable config)
{
return get(cls, config.getConfiguration());
}
/** 获取ORM中指定ID的对象 */
@SuppressWarnings("unchecked")
public static <T> T get(Class<T> cls, String id)
{
if (cls == ZTable.class)
return (T)table(id);
else if (cls == ZView.class)
return (T)view(id);
else if (cls == ZSQL.class)
return (T)sql(id);
else if (cls == ZDDL.class)
return (T)ddl(id);
else if (cls == ZTabler.class)
return (T)tabler(id);
else if (cls == ORMServer.class)
return (T)server(id);
else
throw Asserts.exception("不支持的ORM对象");
}
/** 获取ORM中指定索引的对象 */
@SuppressWarnings("unchecked")
public static <T> T get(Class<T> cls, int idx)
{
if (cls == ZTable.class)
return (T)table(idx);
else if (cls == ZView.class)
return (T)view(idx);
else if (cls == ZSQL.class)
return (T)sql(idx);
else if (cls == ZDDL.class)
return (T)ddl(idx);
else if (cls == ZTabler.class)
return (T)tabler(idx);
else if (cls == ORMServer.class)
return (T)server(idx);
else
throw Asserts.exception("不支持的ORM对象");
}
/***********************************************************************************/
//ORM服务对象
/***********************************************************************************/
/** 获取第一个ORM服务 */
public static ORMServer server()
{
return Global.getService(ORMServer.class);
}
/** 获取指定ID的ORM服务 */
public static ORMServer server(String id)
{
return Global.getService(ORMServer.class, id);
}
/** 获取指定索引的ORM服务 */
public static ORMServer server(int idx)
{
return Global.getService(ORMServer.class, idx);
}
/** 获取指定可配置对象的ORM服务 */
public static ORMServer server(Configurable config)
{
return server(config.getConfiguration());
}
/***********************************************************************************/
//表指令对象
/***********************************************************************************/
/** 获取第一个表指令对象 */
public static ZTable table()
{
return Global.getService(ORMServer.class).table();
}
/** 获取指定ID的表指令对象 */
public static ZTable table(String id)
{
return Global.getService(ORMServer.class, id).table();
}
/** 获取指定索引的表指令对象 */
public static ZTable table(int idx)
{
return Global.getService(ORMServer.class, idx).table();
}
/** 获取指定可配置对象的表指令对象 */
public static ZTable table(Configurable config)
{
return table(config.getConfiguration());
}
/***********************************************************************************/
//视图指令对象
/***********************************************************************************/
/** 获取第一个视图指令对象 */
public static ZView view()
{
return Global.getService(ORMServer.class).view();
}
/** 获取指定ID的视图指令对象 */
public static ZView view(String id)
{
return Global.getService(ORMServer.class, id).view();
}
/** 获取指定索引的视图指令对象 */
public static ZView view(int idx)
{
return Global.getService(ORMServer.class, idx).view();
}
/** 获取指定可配置对象的视图指令对象 */
public static ZView view(Configurable config)
{
return view(config.getConfiguration());
}
/***********************************************************************************/
//SQL指令对象
/***********************************************************************************/
/** 获取第一个SQL指令对象 */
public static ZSQL sql()
{
return Global.getService(ORMServer.class).sql();
}
/** 获取指定ID的SQL指令对象 */
public static ZSQL sql(String id)
{
return Global.getService(ORMServer.class, id).sql();
}
/** 获取指定索引的SQL指令对象 */
public static ZSQL sql(int idx)
{
return Global.getService(ORMServer.class, idx).sql();
}
/** 获取指定可配置对象的SQL指令对象 */
public static ZSQL sql(Configurable config)
{
return sql(config.getConfiguration());
}
/***********************************************************************************/
//DDL指令对象
/***********************************************************************************/
/** 获取第一个DDL指令对象 */
public static ZDDL ddl()
{
return Global.getService(ORMServer.class).ddl();
}
/** 获取指定ID的DDL指令对象 */
public static ZDDL ddl(String id)
{
return Global.getService(ORMServer.class, id).ddl();
}
/** 获取指定索引的DDL指令对象 */
public static ZDDL ddl(int idx)
{
return Global.getService(ORMServer.class, idx).ddl();
}
/** 获取指定可配置对象的DDL指令对象 */
public static ZDDL ddl(Configurable config)
{
return ddl(config.getConfiguration());
}
/***********************************************************************************/
//表管理指令对象
/***********************************************************************************/
/** 获取第一个表管理指令对象 */
public static ZTabler tabler()
{
return Global.getService(ORMServer.class).tabler();
}
/** 获取指定ID的表管理指令对象 */
public static ZTabler tabler(String id)
{
return Global.getService(ORMServer.class, id).tabler();
}
/** 获取指定索引的表管理指令对象 */
public static ZTabler tabler(int idx)
{
return Global.getService(ORMServer.class, idx).tabler();
}
/** 获取指定可配置对象的表管理指令对象 */
public static ZTabler tabler(Configurable config)
{
return tabler(config.getConfiguration());
}
/***********************************************************************************/
//表批量处理
/***********************************************************************************/
public static int[] batch()
{
return null;
}
}
@@ -0,0 +1,149 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import org.zhiqim.kernel.constants.CodeConstants;
import org.zhiqim.kernel.constants.SignConstants;
import org.zhiqim.kernel.constants.TypeConstants;
import org.zhiqim.kernel.util.consts.Int;
/**
* ORM常量定义
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public interface ORMConstants extends SignConstants, TypeConstants, CodeConstants
{
public enum CALL_TYPE {IN, INOUT, OUT};
/*****************************************************************************/
//目前支持的6种数据库类型
/*****************************************************************************/
public String Z_ORM_ID = "orm.id";
public Int Z_ORM_MYSQL = new Int(1, "mysql");
public Int Z_ORM_ORACLE = new Int(2, "oracle");
public Int Z_ORM_MSSQL = new Int(3, "mssql");
public Int Z_ORM_PSQL = new Int(4, "postgresql");
public Int Z_ORM_SQLITE = new Int(5, "sqlite");
public Int Z_ORM_HSQL = new Int(6, "hsql");
public int Z_ORM_MYSQL_INT = 1;
public int Z_ORM_ORACLE_INT = 2;
public int Z_ORM_MSSQL_INT = 3;
public int Z_ORM_PSQL_INT = 4;
public int Z_ORM_SQLITE_INT = 5;
public int Z_ORM_HSQL_INT = 6;
/*****************************************************************************/
//目前支持的9种列类型
/*****************************************************************************/
public Int Z_ORM_STRING = new Int(1, "string");
public Int Z_ORM_INT = new Int(2, "int");
public Int Z_ORM_LONG = new Int(3, "long");
public Int Z_ORM_BOOLEAN = new Int(4, "boolean");
public Int Z_ORM_BYTE = new Int(5, "byte");
public Int Z_ORM_SHORT = new Int(6, "short");
public Int Z_ORM_DATETIME = new Int(7, "datetime");
public Int Z_ORM_DECIMAL = new Int(8, "decimal");
public Int Z_ORM_BINARY = new Int(9, "binary");
public int Z_ORM_STRING_INT = 1;
public int Z_ORM_INT_INT = 2;
public int Z_ORM_LONG_INT = 3;
public int Z_ORM_BOOLEAN_INT = 4;
public int Z_ORM_BYTE_INT = 5;
public int Z_ORM_SHORT_INT = 6;
public int Z_ORM_DATETIME_INT = 7;
public int Z_ORM_DECIMAL_INT = 8;
public int Z_ORM_BINARY_INT = 9;
/*****************************************************************************/
//zhiqim-sql配置信息
/*****************************************************************************/
public String Z_SQL_CONFIG_DTD_PUBLIC_ID = "-//ZHIQIM //DTD Zhiqim-Sql Configuration 1.5.0//EN";
public String Z_SQL_CONFIG_DTD_PATH = "/org/zhiqim/orm/config/zhiqim_sql_1_5_0.dtd";
public String Z_SQL_CONFIG_DTD_URL = "http://zhiqim.org/xmldtds/zhiqim_sql_1_5_0.dtd";
public String Z_SQL_CONFIG_XML_DOCTYPE = "<!DOCTYPE ZHIQIM-SQL PUBLIC \"" + Z_SQL_CONFIG_DTD_PUBLIC_ID + "\" \"" + Z_SQL_CONFIG_DTD_URL + "\">";
public String Z_SQL_CONFIG_XML_HEAD = "<zhiqim-sql>";
public String Z_SQL_CONFIG_XML_TAIL = "</zhiqim-sql>";
public String Z_SQL_ENDSWITH = ".sql.xml";
//zhiqim-sql所在的位置
public int Z_SQL_FILE_INT = 0;
public int Z_SQL_FOLDER_INT = 1;
public int Z_SQL_CLASS_INT = 2;
public int Z_SQL_PACKAGE_INT = 3;
public String Z_SQL_FILE = "file";
public String Z_SQL_FOLDER = "folder";
public String Z_SQL_CLASS = "classpath";
public String Z_SQL_PACKAGE = "package";
/*****************************************************************************/
//SQL条件
/*****************************************************************************/
public int EQUAL = 0;//= 等于
public int NOT_EQUAL = 1;//<> 不等
public int OR = 2;//or 否则
public int LIKE = 10;//'%value%' 两边都LIKE
public int LIKE_LEFT = 11;//'%value' 左LIKE
public int LIKE_RIGHT = 12;//'value%' 右LIKE
public int THEN_G = 21;//> 大于
public int THEN_GE = 22;//>= 大于等于
public int THEN_L = 23;//< 小于
public int THEN_LE = 24;//<= 小于等于
public int IS_NULL = 31;//is null 为空
public int IS_NOT_NULL = 32;//is not null 不为空
public int IN = 33;//in 包含
public int NOT_IN = 34;//not in 不包含
public String ASC = "asc";//顺序
public String DESC = "desc";//倒序
public String JOIN_EQUAL = "EQUAL";//内连接inner join
public String JOIN_LEFT = "LEFT";//左连接left join
public String JOIN_RIGHT = "RIGHT";//右连接right join
/*****************************************************************************/
//表是否存在的SQL语句
/*****************************************************************************/
public String T_EXISTS_MYSQL = "select count(*) from information_schema.tables where table_schema='%s' and table_name='%s'";
public String T_EXISTS_ORACLE = "select count(*) from tab where tabtype='TABLE' and tname='%s'";
public String T_EXISTS_MSSQL = "select count(*) from sysobjects where type='U' and name='%s'";
public String T_EXISTS_PSQL = "select count(*) from pg_tables where tablename='%s'";
public String T_EXISTS_SQLITE = "select count(*) from sqlite_master where type='table' and name='%s'";
public String T_EXISTS_HSQL = "select count(*) from information_schema.tables where table_name='%s';";
public String T_COLUMN_MYSQL = "select COLUMN_TYPE,IS_NULLABLE from information_schema.columns where table_schema=? and table_name=? and column_name=?";
public String T_SELECT_IDENTITY = "select @@IDENTITY";
}
@@ -0,0 +1,64 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import org.zhiqim.kernel.util.Strings;
/**
* ORM异常定义
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ORMException extends Exception
{
private static final long serialVersionUID = 1L;
public ORMException()
{
super();
}
public ORMException(String message)
{
super(message);
}
public ORMException(String message, Object...arguments)
{
super(Strings.format(message, arguments));
}
public ORMException(String message, Throwable e)
{
super(message, e);
}
public ORMException(Throwable e)
{
super(e);
}
public ORMException(String message, Throwable e, Object...arguments)
{
super(Strings.format(message, arguments), e);
}
}
@@ -0,0 +1,50 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import org.zhiqim.kernel.util.Resources;
/**
* 国际化定义
*
* @version v1.0.0 @author zouzhigang 2017-6-1 新建与整理
*/
public class ORMI18n
{
static
{//初始化静态属性
Resources.buildStaticProperties(ORMI18n.class);
}
/** ORM字段类型[%s]不正确 */
public static String ormFieldTypeIncorrect1;
/** ORM表[%s]中未找到字段[%s] */
public static String ormTableNotFoundField2;
/** ORM视图[%s]中未找到表[%s] */
public static String ormViewNotFountTable2;
/** ORM视图[%s]中未找到字段[%s] */
public static String ormViewNotFoundField2;
}
@@ -0,0 +1,5 @@
#
ormFieldTypeIncorrect1=ORM\u5B57\u6BB5\u7C7B\u578B[%s]\u4E0D\u6B63\u786E
ormTableNotFoundField2=ORM\u8868[%s]\u4E2D\u672A\u627E\u5230\u5B57\u6BB5[%s]
ormViewNotFountTable2=ORM\u89C6\u56FE[%s]\u4E2D\u672A\u627E\u5230\u8868[%s]
ormViewNotFoundField2=ORM\u89C6\u56FE[%s]\u4E2D\u672A\u627E\u5230\u5B57\u6BB5[%s]
@@ -0,0 +1,472 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.io.File;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.config.Group;
import org.zhiqim.kernel.config.Item;
import org.zhiqim.kernel.extend.HashMapSS;
import org.zhiqim.kernel.extend.HashMapSV;
import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.kernel.util.Resources;
import org.zhiqim.kernel.util.Systems;
import org.zhiqim.kernel.util.codes.Base64;
import org.zhiqim.kernel.util.codes.HEX;
import org.zhiqim.orm.datasource.ZDataSource;
/**
* ORM服务需要配置的参数
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ORMParameter implements ORMConstants
{
private String id;
//必填五项
private String dbType;
private String driver;
private String url;
private String user;
private String pass;
private int level;
//常用配置三项
private int minPoolSize = 2;
private int maxPoolSize = 10;
private int maxKeepTime = 7001;
//连接时效两项
private int maxIdleTime = 7001;
//密码类型
private String passType = null;
//检查连接三项
private boolean isChkConnOnTimer = false;
private boolean isChkConnOnGet = false;
private boolean isChkConnOnRelease = false;
//耗尽重试两项
private int outOfConnWaitTime = 5;
private int outOfConnRetryCount = 1;
//SQL输出日志两项
private boolean isUpdateSqlLog = false;
private boolean isQuerySqlLog = false;
//sql文件表
private HashMapSV<Integer> sqlMap = new HashMapSV<>();
private HashMapSS cacheMap = new HashMapSS();
/***********************************************************************************/
//构造函数
/***********************************************************************************/
/** 空构造,然后手动设置参数 */
public ORMParameter()
{
}
/** 通过配置生成参数对象 */
public ORMParameter(Group group)
{
this.id = group.getId();
//5项必须
this.dbType = group.getString("dbType");
this.driver = group.getString("driver");
this.url = group.getString("url");
this.user = group.getString("user");
this.pass = group.getString("pass");
this.level = group.getInt("level", -1);
//其他有默认值
this.passType = group.getString("passType");
this.minPoolSize = group.getInt("minPoolSize", 2);
this.maxPoolSize = group.getInt("maxPoolSize", 10);
this.maxKeepTime = group.getInt("maxKeepTime", 7001);
this.maxIdleTime = group.getInt("maxIdleTime", this.maxKeepTime);
this.isChkConnOnTimer = group.isTrue("isChkConnOnTimer", false);
this.isChkConnOnGet = group.isTrue("isChkConnOnGet", false);
this.isChkConnOnRelease = group.isTrue("isChkConnOnRelease", false);
this.outOfConnWaitTime = group.getInt("outOfConnWaitTime", 5);
this.outOfConnRetryCount = group.getInt("outOfConnRetryCount", 1);
this.isUpdateSqlLog = group.isTrue("isUpdateSqlLog", false);
this.isQuerySqlLog = group.isTrue("isQuerySqlLog", false);
//SQL文件
Group grp = Global.getGroup(group.getId()+".sql");
if (grp != null)
{
for (Item item : grp.list())
{
addSqlConfig(item.getKey(), item.getString());
}
}
//表缓存
grp = Global.getGroup(group.getId()+".cache");
if (grp != null)
{
for (Item item : grp.list())
{
addCacheConfig(item.getKey(), item.getString());
}
}
}
/** 初始化连接池 */
public ZDataSource newDatabase()
{
//对密码支持简单加密,HEX/Base64两种
if (_HEX_.equalsIgnoreCase(passType))
pass = HEX.decrypt(pass);
else if (_BASE64_.equalsIgnoreCase(passType))
pass = Base64.decodeUTF8(pass);
return new ZDataSource(id, driver, url, user, pass, level,
minPoolSize, maxPoolSize, maxKeepTime, maxIdleTime,
isChkConnOnTimer, isChkConnOnGet, isChkConnOnRelease,
outOfConnWaitTime, outOfConnRetryCount);
}
/***********************************************************************************/
//判断数据库类型
/***********************************************************************************/
/** 获取数据库类型 */
public int getDatabaseType()
{
return ORMType.getDatabaseType(dbType).value();
}
/** 判断是否是Oracle数据库 */
public boolean isOracle()
{
return getDatabaseType() == Z_ORM_ORACLE.value();
}
/** 判断是否是Microsoft SQLServer数据库 */
public boolean isMssql()
{
return getDatabaseType() == Z_ORM_MSSQL.value();
}
/** 判断是否是SQLite数据库 */
public boolean isSqlite()
{
return getDatabaseType() == Z_ORM_SQLITE.value();
}
/** 判断是否是Hsql数据库 */
public boolean isHsql()
{
return getDatabaseType() == Z_ORM_HSQL.value();
}
/** 判断是否是MySql数据库 */
public boolean isMysql()
{
return getDatabaseType() == Z_ORM_MYSQL.value();
}
/** 获取数据库名 */
public String getDbName()
{
if (isMysql())
{
if ("jndi".equalsIgnoreCase(driver))
return user;//JNDI 时配置成用户
String dbUrl = url;
int ind = dbUrl.indexOf("?");
if (ind != -1)
dbUrl = dbUrl.substring(0, ind);
int ind2 = dbUrl.lastIndexOf("/");
return dbUrl.substring(ind2+1);
}
return null;
}
/***********************************************************************************/
//SQL文件表
/***********************************************************************************/
public HashMapSV<Integer> getSqlConfig()
{
return sqlMap;
}
public void addSqlConfig(String key, String value)
{
int type = Z_SQL_FILE.equals(value)?Z_SQL_FILE_INT:
Z_SQL_FOLDER.equals(value)?Z_SQL_FOLDER_INT:
Z_SQL_CLASS.equals(value)?Z_SQL_CLASS_INT:
Z_SQL_PACKAGE.equals(value)?Z_SQL_PACKAGE_INT:-1;
addSqlConfig(key, type);
}
public void addSqlConfig(String key, int type)
{
Asserts.notNull(key, _KEY_);
Asserts.as((type >= 0 && type <= 3)?null:"增加ORM的SQL配置["+key+"]的类型不正确");
switch (type)
{
case Z_SQL_FILE_INT:
{
Asserts.as(key.endsWith(Z_SQL_ENDSWITH)?null:"增加ORM的SQL配置["+key+"]必须以[.sql.xml]结尾的SQL配置文件名");
File file = new File(key);
Asserts.as((file.isFile() && file.canRead())?null:"增加ORM的SQL配置["+key+"]必须是文件并可读");
break;
}
case Z_SQL_FOLDER_INT:
{
File folder = new File(key);
Asserts.as((folder.isDirectory() && folder.canRead())?null:"增加ORM的SQL配置["+key+"]必须是文件夹并可读");
break;
}
case Z_SQL_CLASS_INT:
{
Asserts.as(key.endsWith(Z_SQL_ENDSWITH)?null:"增加ORM的SQL配置["+key+"]必须以[.sql.xml]结尾的SQL配置文件名");
Asserts.as(Resources.exists(ORMServer.class, key)?null:"增加ORM的SQL配置["+key+"]必须是文件并可读");
break;
}
case Z_SQL_PACKAGE_INT:
{
Asserts.as(Resources.exists(ORMServer.class, key)?null:"增加ORM的SQL配置["+key+"]必须是存在");
break;
}
}
key = Systems.replacePropertyPath(key);
sqlMap.put(key, type);
}
/***********************************************************************************/
//Cache配置表
/***********************************************************************************/
public void addCacheConfig(String key, String value)
{
cacheMap.put(key, value);
}
public HashMapSS getCacheConfig()
{
return cacheMap;
}
/***********************************************************************************/
//参数的设置和获取
/***********************************************************************************/
public String getDbType()
{
return dbType;
}
public void setDbType(String dbType)
{
this.dbType = dbType;
}
public boolean isUpdateSqlLog()
{
return isUpdateSqlLog;
}
public void setUpdateSqlLog(boolean isUpdateSqlLog)
{
this.isUpdateSqlLog = isUpdateSqlLog;
}
public boolean isQuerySqlLog()
{
return isQuerySqlLog;
}
public void setQuerySqlLog(boolean isQuerySqlLog)
{
this.isQuerySqlLog = isQuerySqlLog;
}
public String getDriver()
{
return driver;
}
public void setDriver(String driver)
{
this.driver = driver;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getPass()
{
return pass;
}
public void setPass(String pass)
{
this.pass = pass;
}
public String getPassType()
{
return passType;
}
public void setPassType(String passType)
{
this.passType = passType;
}
public int getLevel()
{
return level;
}
public void setLevel(int level)
{
this.level = level;
}
public int getMinPoolSize()
{
return minPoolSize;
}
public void setMinPoolSize(int minPoolSize)
{
this.minPoolSize = minPoolSize;
}
public int getMaxPoolSize()
{
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize)
{
this.maxPoolSize = maxPoolSize;
}
public int getMaxKeepTime()
{
return maxKeepTime;
}
public void setMaxKeepTime(int maxKeepTime)
{
this.maxKeepTime = maxKeepTime;
}
public int getMaxIdleTime()
{
return maxIdleTime;
}
public void setMaxIdleTime(int maxIdleTime)
{
this.maxIdleTime = maxIdleTime;
}
public boolean isChkConnOnTimer()
{
return isChkConnOnTimer;
}
public void setChkConnOnTimer(boolean isChkConnOnTimer)
{
this.isChkConnOnTimer = isChkConnOnTimer;
}
public boolean isChkConnOnGet()
{
return isChkConnOnGet;
}
public void setChkConnOnGet(boolean isChkConnOnGet)
{
this.isChkConnOnGet = isChkConnOnGet;
}
public boolean isChkConnOnRelease()
{
return isChkConnOnRelease;
}
public void setChkConnOnRelease(boolean isChkConnOnRelease)
{
this.isChkConnOnRelease = isChkConnOnRelease;
}
public int getOutOfConnWaitTime()
{
return outOfConnWaitTime;
}
public void setOutOfConnWaitTime(int outOfConnWaitTime)
{
this.outOfConnWaitTime = outOfConnWaitTime;
}
public int getOutOfConnRetryCount()
{
return outOfConnRetryCount;
}
public void setOutOfConnRetryCount(int outOfConnRetryCount)
{
this.outOfConnRetryCount = outOfConnRetryCount;
}
}
@@ -0,0 +1,191 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.SQLException;
import java.util.List;
import org.zhiqim.kernel.extend.MapSS;
import org.zhiqim.orm.dbo.defined._Table;
import org.zhiqim.orm.dbo.defined._TableField;
/**
* ORM数据库策略
*
* @version v1.0.0 @author zouzhigang 2016-9-18 新建与整理
*/
public interface ORMPolicy extends ORMConstants
{
/**
* 检查保持时长是否正确
*
* @param maxKeepTime 保持时长
* @return =true正确,数据库定义的比该值大
*/
public boolean chkKeepTime(int maxKeepTime);
/**
* 生成表是否存在的SQL
*
* @param databaseName 数据库名
* @param tableName 表名
* @return SQL语句
*/
public String toExistsSQL(String databaseName, String tableName);
/**
* 增加表的一列,支持类型和是否为null
*
* @param table 表名
* @param column 列名
* @param columnType 列类型
* @param notNull 是否不允许为null
* @return SQL语句
*/
public String toAlertColumnAdd(String table, String column, String columnType, boolean notNull);
/**
* ORM定义的类型,转化为SQL类型,如string,15转化为varchar(15)
*
* @param type ORM定义的类型如string,15
* @return SQL类型,如varchar(15)
*/
public String toColumnType(String type);
/**
* 生成字段字符串
*
* @param field 表字段对象
* @return 生成字符串
*/
public String toColumnString(_TableField field);
/**
* 生成创建表字符串
*
* @param _table 表对象
* @param replaceMap 可替换表
* @return 得到创建表的SQL列表
*/
public List<String> toTableString(_Table _table, MapSS replaceMap);
/**
* 生成查询一条数据的SQL语句
*
* @param fieldSQL 字段SQL
* @param tableName 表名
* @param whereSQL 条件SQL
* @param orderbySQL 排序SQL
* @param groupbySQL 分组SQL
* @return 完整ZSQL
*/
public String toItemSQL(String fieldSQL, String tableName, String whereSQL, String orderbySQL, String groupbySQL);
/**
* 生成分页显示的SQL语句
*
* @param fieldSQL 字段SQL
* @param tableName 表名
* @param whereSQL 条件SQL
* @param orderbySQL 排序SQL
* @param groupbySQL 分组SQL
* @param maxNum 最大数目
* @param pageNo 页码
* @return 完整SQL
*/
public String toPageSQL(String fieldSQL, String tableName, String whereSQL, String orderbySQL, String groupbySQL, int maxNum, int pageNo);
/**
* 生成视图关联分页显示的SQL语句
*
* @param innerTableSQL 内部表SQL
* @param maxNum 最大数目
* @param pageNo 页码
* @return 完整ZSQL
*/
public String toPageViewSQL(StringBuilder innerTableSQL, int maxNum, int pageNo);
/**************************************************************************************************/
//不同的数据库处理
/**************************************************************************************************/
/**
* 删除表的一列
*
* @param table 表名
* @param column 列名
* @throws SQLException 数据库异常
*/
public void executeAlertColumnDrop(String table, String column) throws ORMException, SQLException;
/**
* 修改表的一列值
*
* @param table 表名
* @param newColumnType 新类型
* @param newNotNull 新列是否不为null
* @param ORMException ORM异常
* @throws SQLException 数据库异常
*/
public void executeAlertColumnType(String table, String column, String newColumnType, boolean newNotNull) throws ORMException, SQLException;
/**
* 修改表的一列名
*
* @param table 表名
* @param column 列名
* @param newColumn 新列名
* @throws ORMException ORM异常
* @throws SQLException 数据库异常
*/
public void executeAlertColumnName(String table, String column, String newColumn) throws ORMException, SQLException;
/**
* 修改表的一列
*
* @param table 表名
* @param column 列名
* @param newColumn 新列名
* @param newColumnType 新类型
* @param newNotNull 新列是否不为null
* @throws ORMException ORM异常
* @throws SQLException 数据库异常
*/
public void executeAlertColumnInfo(String table, String column, String newColumn, String newColumnType, boolean newNotNull) throws ORMException, SQLException;
/**
* 增加表的主键
*
* @param table 表名
* @param columns 列名,多个用逗号隔开如AAA_AAA,BBB_BBB
* @throws SQLException 数据库异常
*/
public void executeAlertPrimaryKeyAdd(String table, String columns) throws ORMException, SQLException;
/**
* 删除表的主键
*
* @param table 表名
* @throws SQLException 数据库异常
*/
public void executeAlertPrimaryKeyDrop(String table) throws ORMException, SQLException;
}
@@ -0,0 +1,321 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.util.Map;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.Servicer;
import org.zhiqim.kernel.extend.HashMapCV;
import org.zhiqim.kernel.extend.HashMapSO;
import org.zhiqim.kernel.extend.HashMapSS;
import org.zhiqim.kernel.extend.LinkedMapSO;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.extend.TreeMapSO;
import org.zhiqim.kernel.schedule.TaskThreader;
import org.zhiqim.kernel.util.Types;
import org.zhiqim.orm.annotation.AnDbo;
import org.zhiqim.orm.annotation.AnTable;
import org.zhiqim.orm.annotation.AnView;
import org.zhiqim.orm.dbo.Dbo;
import org.zhiqim.orm.executor.BatchExecutor;
import org.zhiqim.orm.executor.BatchExecutorBase;
import org.zhiqim.orm.executor.BatchExecutorClass;
import org.zhiqim.orm.executor.BatchExecutorMap;
import org.zhiqim.orm.executor.CallExecutor;
import org.zhiqim.orm.executor.QueryExecutor;
import org.zhiqim.orm.executor.QueryExecutorBaseBase;
import org.zhiqim.orm.executor.QueryExecutorBaseClass;
import org.zhiqim.orm.executor.QueryExecutorBaseMap;
import org.zhiqim.orm.executor.QueryExecutorClassBase;
import org.zhiqim.orm.executor.QueryExecutorClassClass;
import org.zhiqim.orm.executor.QueryExecutorClassMap;
import org.zhiqim.orm.executor.QueryExecutorMapBase;
import org.zhiqim.orm.executor.QueryExecutorMapClass;
import org.zhiqim.orm.executor.QueryExecutorMapMap;
import org.zhiqim.orm.executor.UpdateExecutor;
import org.zhiqim.orm.executor.UpdateExecutorBase;
import org.zhiqim.orm.executor.UpdateExecutorClass;
import org.zhiqim.orm.executor.UpdateExecutorMap;
import org.zhiqim.orm.impl.ZDDLImplement;
import org.zhiqim.orm.impl.ZSQLImplement;
import org.zhiqim.orm.impl.ZTableImplement;
import org.zhiqim.orm.impl.ZTablerImplement;
import org.zhiqim.orm.impl.ZViewImplement;
/**
* ORM预处理,从ORMServer中独立出来一个抽象类,这样ORMServer就不会太大,易管理
*
* @version v1.0.0 @author zouzhigang 2018-11-26 新建与整理
*/
public abstract class ORMPredefinded extends Servicer
{
//SQL处理器
protected final HashMapCV<CallExecutor> callMap = new HashMapCV<>();
protected final HashMapCV<UpdateExecutor> updateMap = new HashMapCV<>();
protected final HashMapCV<BatchExecutor> batchMap = new HashMapCV<>();
protected final HashMapCV<QueryExecutor> queryMap = new HashMapCV<>();
//SQL表和缓存表
protected final HashMapSS sqlMap = new HashMapSS();
protected final HashMapCV<TaskThreader> cacheMap = new HashMapCV<>();
//ORM指令对象
protected ZSQLImplement zSQL;
protected ZDDLImplement zDDL;
protected ZTableImplement zTable;
protected ZTablerImplement zTabler;
protected ZViewImplement zView;
/***********************************************************************************/
//ORM预开启&关闭
/***********************************************************************************/
/** 开启 */
protected void open()
{
//call
callMap.put(CallExecutor.class, new CallExecutor());
//update
updateMap.put(UpdateExecutorBase.class, new UpdateExecutorBase());
updateMap.put(UpdateExecutorClass.class, new UpdateExecutorClass());
updateMap.put(UpdateExecutorMap.class, new UpdateExecutorMap());
//batch
batchMap.put(BatchExecutorBase.class, new BatchExecutorBase());
batchMap.put(BatchExecutorClass.class, new BatchExecutorClass());
batchMap.put(BatchExecutorMap.class, new BatchExecutorMap());
//query
queryMap.put(QueryExecutorBaseBase.class, new QueryExecutorBaseBase());
queryMap.put(QueryExecutorBaseClass.class, new QueryExecutorBaseClass());
queryMap.put(QueryExecutorBaseMap.class, new QueryExecutorBaseMap());
queryMap.put(QueryExecutorClassBase.class, new QueryExecutorClassBase());
queryMap.put(QueryExecutorClassClass.class, new QueryExecutorClassClass());
queryMap.put(QueryExecutorClassMap.class, new QueryExecutorClassMap());
queryMap.put(QueryExecutorMapBase.class, new QueryExecutorMapBase());
queryMap.put(QueryExecutorMapClass.class, new QueryExecutorMapClass());
queryMap.put(QueryExecutorMapMap.class, new QueryExecutorMapMap());
}
/** 关闭 */
protected void close()
{
sqlMap.clear();
updateMap.clear();
batchMap.clear();
queryMap.clear();
}
/***********************************************************************************/
//获取ORM指令对象,目前共5个(sql,ddl,table,tabler,view
/***********************************************************************************/
public ZSQL sql()
{
return zSQL;
}
public ZDDL ddl()
{
return zDDL;
}
public ZTable table()
{
return zTable;
}
public ZView view()
{
return zView;
}
public ZTabler tabler()
{
return zTabler;
}
/***********************************************************************************/
//获取ORM指令对象,目前共5个(sql,ddl,table,tabler,view
/***********************************************************************************/
public String getSQL(String id)
{
return sqlMap.get(id);
}
public CallExecutor getCallExecutor()
{
return callMap.get(CallExecutor.class);
}
public UpdateExecutor getUpdateExecutor(Class<?> clazz)
{
return updateMap.get(clazz);
}
public UpdateExecutor getUpdateExecutor(Object param)
{
if (isParamBase(param))
{//基本类型和数组
return updateMap.get(UpdateExecutorBase.class);
}
else if (param instanceof Map<?, ?> || param instanceof MapSO)
{//MAP
return updateMap.get(UpdateExecutorMap.class);
}
else if (this.isDbo(param.getClass()))
{//DBO
return updateMap.get(UpdateExecutorClass.class);
}
else
{//其他的不支持
return null;
}
}
public BatchExecutor getBatchExecutor(Object param)
{
if (isParamBase(param))
{//基本类型和数组
return batchMap.get(BatchExecutorBase.class);
}
else if (param instanceof Map<?, ?> || param instanceof MapSO)
{//MAP
return batchMap.get(BatchExecutorMap.class);
}
else if (this.isDbo(param.getClass()))
{//DBO
return batchMap.get(BatchExecutorClass.class);
}
else
{//其他的不支持
return null;
}
}
public QueryExecutor getQueryExecutor(Object param, Class<?> resultClass)
{
if (isParamBase(param))
{//基础类型
if (isResultBase(resultClass))
return queryMap.get(QueryExecutorBaseBase.class);
if (resultClass == Map.class || resultClass == MapSO.class || resultClass == HashMapSO.class || resultClass == LinkedMapSO.class || resultClass == TreeMapSO.class)
return queryMap.get(QueryExecutorBaseMap.class);
if (isDbo(resultClass))
return queryMap.get(QueryExecutorBaseClass.class);
return null;
}
if (param instanceof Map<?, ?> || param instanceof MapSO)
{//MAP
if (isResultBase(resultClass))
return queryMap.get(QueryExecutorMapBase.class);
if (resultClass == Map.class || resultClass == MapSO.class || resultClass == HashMapSO.class || resultClass == LinkedMapSO.class || resultClass == TreeMapSO.class)
return queryMap.get(QueryExecutorMapMap.class);
if (isDbo(resultClass))
return queryMap.get(QueryExecutorMapClass.class);
return null;
}
if (isDbo(param.getClass()))
{//DBO
if (isResultBase(resultClass))
return queryMap.get(QueryExecutorClassBase.class);
if (resultClass == Map.class || resultClass == MapSO.class || resultClass == HashMapSO.class || resultClass == LinkedMapSO.class || resultClass == TreeMapSO.class)
return queryMap.get(QueryExecutorClassMap.class);
if (isDbo(resultClass))
return queryMap.get(QueryExecutorClassClass.class);
return null;
}
return null;
}
public BatchExecutor getBatchExecutor(Class<?> clazz)
{
return batchMap.get(clazz);
}
public QueryExecutor getQueryExecutor(Class<?> clazz)
{
return queryMap.get(clazz);
}
public boolean isParamBase(Object param)
{
return (param == null || param instanceof Integer || param instanceof Long || param instanceof String || Types.isArray(param));
}
public boolean isResultBase(Class<?> resultClass)
{
return resultClass == int.class || resultClass == Integer.class || resultClass == long.class || resultClass == Long.class || resultClass == String.class;
}
public boolean isDbo(String name)
{
return isDbo(Global.forName(name));
}
public boolean isDbo(Class<?> clazz)
{
if (clazz == null)
return false;
else if (clazz.isAnnotationPresent(AnTable.class))
return true;
else if (clazz.isAnnotationPresent(AnView.class))
return true;
else if (clazz.isAnnotationPresent(AnDbo.class))
return true;
else
return false;
}
public Dbo getDbo(String name)
{
Class<?> clazz = Global.forName(name);
if (clazz == null)
return null;
else
return getDbo(clazz);
}
public Dbo getDbo(Class<?> clazz)
{
if (clazz.isAnnotationPresent(AnTable.class))
return zTable.getTable(clazz);
else if (clazz.isAnnotationPresent(AnView.class))
return zView.getView(clazz);
else if (clazz.isAnnotationPresent(AnDbo.class))
return zSQL.getDbo(clazz);
else
return null;
}
}
@@ -0,0 +1,376 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.config.Group;
import org.zhiqim.kernel.extend.HashMapCV;
import org.zhiqim.kernel.extend.HashMapSS;
import org.zhiqim.kernel.extend.HashMapSV;
import org.zhiqim.kernel.extend.MapSS;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.schedule.ScheduleFactory;
import org.zhiqim.kernel.schedule.Task;
import org.zhiqim.kernel.schedule.TaskThreader;
import org.zhiqim.kernel.transaction.Transaction;
import org.zhiqim.kernel.transaction.TransactionManager;
import org.zhiqim.kernel.transaction.TransactionService;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Files;
import org.zhiqim.kernel.util.Resources;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.orm.cache.ZTableCacheTask;
import org.zhiqim.orm.config.ZSQLConfig;
import org.zhiqim.orm.datasource.ZDataSource;
import org.zhiqim.orm.dbo.defined._Table;
import org.zhiqim.orm.impl.ZDDLImplement;
import org.zhiqim.orm.impl.ZSQLImplement;
import org.zhiqim.orm.impl.ZTableImplement;
import org.zhiqim.orm.impl.ZTablerImplement;
import org.zhiqim.orm.impl.ZViewImplement;
/**
* ORM服务器,实现系统定义的服务、多例接口,支持配置创建和手动创建<br><br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ORMServer extends ORMPredefinded implements TransactionService, ORMConstants
{
private static final Log log = LogFactory.getLog(ORMServer.class);
private ORMParameter parameter;
private ORMPolicy policy;
private ZDataSource dataSource;
/***********************************************************************************/
//服务创建&销毁
/***********************************************************************************/
@Override /** 服务配置方式创建 */
public boolean create() throws Exception
{
if (id == null)
return false;
Group group = Global.getGroup(id);
if (group == null)
return false;
return create(new ORMParameter(group));
}
/**
* 数据库映射服务构造函数,由业务创建,如果配置创建直接调用无参数构造函数
*
* @param parameter 数据库参数
* @throws Exception 创建异常
*/
public boolean create(ORMParameter parameter) throws Exception
{
this.parameter = parameter;
log.info("初始化[数据库映射:%s]开始...", id);
//1.判断是否支持的数据库
String dbType = parameter.getDbType();
policy = ORMType.getDatabasePolicy(this, dbType);
if (policy == null)
{
log.fatal("不支持的数据库类型[%s]", dbType);
return false;
}
//2.初始化数据库连接池
dataSource = parameter.newDatabase();
if (!dataSource.open())
{
log.fatal("初始化连接池失败[%s]", dbType);
return false;
}
//3.开启SQL处理器
super.open();
//4.初始化SQL数据
if (!isInitSQLMapping())
{
log.fatal("初始化DBO和SQL失败[%s]", dbType);
return false;
}
//5.创建指令对象,要注意创建顺序SQL-DDL-Table-View
zSQL = new ZSQLImplement(this);
zDDL = new ZDDLImplement(this);
zTabler = new ZTablerImplement(this);
zTable = new ZTableImplement(this);
zView = new ZViewImplement(this);
//6.初始化缓存
initCacheConfig();
//7.注册服务到事务管理中
TransactionManager.addTransactionService(this);
//8.检查设置的保持时长要求少于数据库设置的时长
if (!policy.chkKeepTime(parameter.getMaxKeepTime()))
{
log.info("初始化[数据库映射:%s]检查到保持时长小于配置的maxKeepTime+3分钟", id);
return false;
}
log.info("初始化[数据库映射:%s]完成!!!\r\n", id);
return true;
}
@Override
public void destroy() throws Exception
{
//从全局对象表和事务管理中移除
TransactionManager.removeTransactionService(this);
//关闭SQL处理器
super.close();
//销毁数据源
if (dataSource != null)
{
dataSource.close();
dataSource = null;
}
}
/** 初始化所有.sql.xml文件数据 */
private boolean isInitSQLMapping() throws Exception
{
HashMapSV<Integer> sqlConfigMap = parameter.getSqlConfig();
for (Map.Entry<String, Integer> entry : sqlConfigMap.entrySet())
{
String key = entry.getKey();
int type = entry.getValue();
switch (type)
{
case Z_SQL_FILE_INT:
{
addSQLConfig(key, new FileInputStream(key));
break;
}
case Z_SQL_FOLDER_INT:
{
File folder = new File(key);
File[] fileList = folder.listFiles();
for (File file : fileList)
{
if (!file.isFile() || !file.canRead())
continue;
String name = Files.toLinuxPath(file.getPath());
if (!name.endsWith(".sql.xml"))
continue;
addSQLConfig(name, new FileInputStream(file));
}
break;
}
case Z_SQL_CLASS_INT:
{
addSQLConfig(key, Resources.getResourceStream(ORMServer.class, key));
break;
}
case Z_SQL_PACKAGE_INT:
{
List<String> fileList = Resources.getResourceFileNameList(ORMServer.class, key);
for (String name : fileList)
{
if (!name.endsWith(".sql.xml"))
continue;
String className = Strings.addEndsWith(key, "/") + name;
addSQLConfig(className, Resources.getResourceStream(ORMServer.class, className));
}
break;
}
}
}
return true;
}
/** 加载SQL到内存表中 */
private void addSQLConfig(String name, InputStream is) throws Exception
{
ZSQLConfig sqlConfig = new ZSQLConfig(name);
sqlConfig.load(is);
for (Map.Entry<String, String> sqlEntry : sqlConfig.getSQLMap().entrySet())
{
if (sqlMap.containsKey(sqlEntry.getKey()))
throw new ORMException("映射文件:[%s]配置异常,有相同的ID[%s]存在", name, sqlEntry.getKey());
sqlMap.put(sqlEntry.getKey(), sqlEntry.getValue());
}
log.info("映射文件[%s]加载成功", name);
}
/** 初始化需要缓存的表加载数据到内存 */
private void initCacheConfig() throws Exception
{
HashMapSS cacheConfigMap = parameter.getCacheConfig();
for (String className : cacheConfigMap.keySet())
{
Class<?> clazz = Classes.forName(Global.getClassName(className));
if (clazz == null)
throw new ORMException("缓存类[%s]配置异常,未找到该类", className);
_Table table = zTable.getTable(clazz);
if (table == null)
throw new ORMException("缓存类[%s]配置异常,该类不是标准表DBO对象", className);
Task task = new ZTableCacheTask(zTable, clazz);
MapSS paramMap = Jsons.toMapSS(cacheConfigMap.get(className));
TaskThreader taskThreader = ScheduleFactory.getTaskThreader(task, paramMap);
if (taskThreader == null)
throw new ORMException("缓存类[%s]配置异常,时钟格式不正常", className);
cacheMap.put(clazz, taskThreader);
}
zTable.schedule();
}
/***********************************************************************************/
//获取服务的属性,参数&连接&缓存&事务等
/***********************************************************************************/
/** 获取数据库参数 */
public ORMParameter getParameter()
{
return parameter;
}
/** 获取数据库类型 */
public int getDatabaseType()
{
return parameter.getDatabaseType();
}
/** 获取数据库名称 */
public String getDatabaseName()
{
return parameter.getDbName();
}
/** 是否打印更新日志 */
public boolean isUpdateSqlLog()
{
return parameter.isUpdateSqlLog();
}
/** 是否打印查询日志 */
public boolean isQuerySqlLog()
{
return parameter.isQuerySqlLog();
}
/** 判断是否是Oracle数据库 */
public boolean isOracle()
{
return parameter.isOracle();
}
/** 判断是否是Microsoft SQLServer数据库 */
public boolean isMssql()
{
return parameter.isMssql();
}
/** 判断是否是SQLite数据库 */
public boolean isSqlite()
{
return parameter.isSqlite();
}
/** 判断是否是Hsql数据库 */
public boolean isHsql()
{
return parameter.isHsql();
}
/** 判断是否是MySql数据库 */
public boolean isMysql()
{
return parameter.isMysql();
}
/** 获取一个数据库资源 */
public ZDataSource getDateSource()
{
return dataSource;
}
/** 获取一个连接 */
public Connection getConnection() throws SQLException
{
return dataSource.getConnection();
}
/** 获取ORM不同数据库的策略封装对象 */
public ORMPolicy getPolicy()
{
return policy;
}
/** 判断表是否是缓存表 */
public boolean isCache(Class<?> clazz)
{
return cacheMap.containsKey(clazz);
}
/** 获取缓存表 */
public HashMapCV<TaskThreader> getCacheMap()
{
return cacheMap;
}
@Override /** 获取事务实例 */
public Connection getTransactionInstance() throws SQLException
{
return getConnection();
}
@Override /** 开始事务实例 */
public Transaction beginTransaction(Object instance) throws SQLException
{
return new ORMTransaction(id, (Connection)instance).begin();
}
}
@@ -0,0 +1,77 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.Connection;
import java.sql.SQLException;
import org.zhiqim.kernel.transaction.Transaction;
import org.zhiqim.kernel.transaction.TransactionAbstracter;
/**
* 实现事务接口,包括提交、回滚、关闭以及判断是否已提交和已回滚,该类只由事务管理器创建
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ORMTransaction extends TransactionAbstracter
{
private Connection conn = null;
private boolean autoCommit = true;
public ORMTransaction(String id, Connection conn)
{
super(id);
this.conn = conn;
}
/** 开始一个事务 */
public Transaction begin() throws SQLException
{
autoCommit = conn.getAutoCommit();
if (autoCommit)
conn.setAutoCommit(false);
return this;
}
/** 提交一个事务 */
public void commit() throws SQLException
{
conn.commit();
super.setCommitted();
}
/** 回滚一个事务 */
public void rollback() throws SQLException
{
conn.rollback();
super.setRollbacked();
}
/** 关闭一个事务 */
public void close() throws SQLException
{
conn.setAutoCommit(autoCommit);
conn.close();
super.setClosed();
}
}
+256
View File
@@ -0,0 +1,256 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.util.ArrayList;
import java.util.List;
import org.zhiqim.kernel.extend.LinkedMapSV;
import org.zhiqim.kernel.extend.MapSV;
import org.zhiqim.kernel.util.consts.Int;
import org.zhiqim.orm.policy._HSQL;
import org.zhiqim.orm.policy._MSSQL;
import org.zhiqim.orm.policy._MySQL;
import org.zhiqim.orm.policy._Oracle;
import org.zhiqim.orm.policy._PostgetSQL;
import org.zhiqim.orm.policy._SQLite;
/**
* ORM支持的数据库类型,当前支持6种,分别为ORACLE|MYSQL|MSSQL|HSQL|SQLite|PostgreSQL
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ORMType implements ORMConstants
{
private static final MapSV<Int> DB_TYPE_MAP = new LinkedMapSV<>();
private static final MapSV<Int> DC_TYPE_MAP = new LinkedMapSV<>();
static
{
//支持的6六种数据库类型
DB_TYPE_MAP.put(Z_ORM_MYSQL.desc(), Z_ORM_MYSQL);
DB_TYPE_MAP.put(Z_ORM_ORACLE.desc(), Z_ORM_ORACLE);
DB_TYPE_MAP.put(Z_ORM_MSSQL.desc(), Z_ORM_MSSQL);
DB_TYPE_MAP.put(Z_ORM_PSQL.desc(), Z_ORM_PSQL);
DB_TYPE_MAP.put(Z_ORM_SQLITE.desc(), Z_ORM_SQLITE);
DB_TYPE_MAP.put(Z_ORM_HSQL.desc(), Z_ORM_HSQL);
//支持的9种数据字段类型
DC_TYPE_MAP.put(Z_ORM_STRING.desc(), Z_ORM_STRING);
DC_TYPE_MAP.put(Z_ORM_INT.desc(), Z_ORM_INT);
DC_TYPE_MAP.put(Z_ORM_LONG.desc(), Z_ORM_LONG);
DC_TYPE_MAP.put(Z_ORM_BOOLEAN.desc(), Z_ORM_BOOLEAN);
DC_TYPE_MAP.put(Z_ORM_BYTE.desc(), Z_ORM_BYTE);
DC_TYPE_MAP.put(Z_ORM_SHORT.desc(), Z_ORM_SHORT);
DC_TYPE_MAP.put(Z_ORM_DATETIME.desc(), Z_ORM_DATETIME);
DC_TYPE_MAP.put(Z_ORM_DECIMAL.desc(), Z_ORM_DECIMAL);
DC_TYPE_MAP.put(Z_ORM_BINARY.desc(), Z_ORM_BINARY);
}
/**********************************************************************/
//数据库类型
/**********************************************************************/
public static ORMPolicy getDatabasePolicy(ORMServer server, String dbType)
{
Int value = DB_TYPE_MAP.get(dbType);
if (value == null)
return null;
switch (value.value())
{
case Z_ORM_MYSQL_INT:return new _MySQL(server);
case Z_ORM_ORACLE_INT:return new _Oracle(server);
case Z_ORM_MSSQL_INT:return new _MSSQL(server);
case Z_ORM_PSQL_INT:return new _PostgetSQL(server);
case Z_ORM_SQLITE_INT:return new _SQLite(server);
case Z_ORM_HSQL_INT:return new _HSQL(server);
default:return null;
}
}
public static Int getDatabaseType(String dbType)
{
return DB_TYPE_MAP.get(dbType);
}
public static boolean isDatabaseTypeSql(String name, String dbType)
{
boolean isSpecified = false;
for (String s : DB_TYPE_MAP.keySet())
{
if (name.endsWith("." + s + Z_SQL_ENDSWITH))
{
isSpecified = true;
break;
}
}
//未特别指定的通用支持
if (!isSpecified)
return true;
//指定的则和当前进行匹配
return name.endsWith("." + dbType + Z_SQL_ENDSWITH);
}
public static List<String> getDatabaseTypeList()
{
List<String> list = new ArrayList<>(DB_TYPE_MAP.size());
for (String key : DB_TYPE_MAP.keySet())
{
list.add(key);
}
return list;
}
public static String[] getDatabaseTypes()
{
String[] types = new String[DB_TYPE_MAP.size()];int i=0;
for (String key : DB_TYPE_MAP.keySet())
{
types[i++] = key;
}
return types;
}
/**********************************************************************/
//字段类型
/**********************************************************************/
public static boolean isSupportColumn(String columnType)
{
return DC_TYPE_MAP.containsKey(columnType);
}
public static boolean hasColumnLength(String columnType)
{
Int value = DC_TYPE_MAP.get(columnType);
return value==null?false:hasColumnLength(value.value());
}
public static boolean hasColumnLength(int columnType)
{
return (columnType == Z_ORM_STRING_INT || columnType == Z_ORM_DECIMAL_INT);
}
public static int getColumnTypeMaybeLength(String columnTypeMaybeLength)
{
int ind = columnTypeMaybeLength.indexOf(",");
if (ind == -1)
return getColumnType(columnTypeMaybeLength).value();
String ctype = columnTypeMaybeLength.substring(0, ind);
return getColumnType(ctype).value();
}
public static Int getColumnType(String columnType)
{
return DC_TYPE_MAP.get(columnType);
}
public static List<String> getColumnTypeList()
{
List<String> list = new ArrayList<>(DC_TYPE_MAP.size());
for (String key : DC_TYPE_MAP.keySet())
{
list.add(key);
}
return list;
}
public static String[] getColumnTypes()
{
String[] types = new String[DC_TYPE_MAP.size()];int i=0;
for (String key : DC_TYPE_MAP.keySet())
{
types[i++] = key;
}
return types;
}
/**
* 把带下划线的名称转为表名,如FMR_PARAM转换为FmrParam
*
* @param name 名称
* @return 表名
*/
public static String toUpperName(String name)
{
return name.substring(0, 1).toUpperCase() + toTableFieldName(name.substring(1));
}
/**
* 把带下划线的列名转为字段名,如PARAM_NAME转换为paramName
*
* @param name 名称
* @return 字段名
*/
public static String toLowerName(String name)
{
return name.substring(0, 1).toLowerCase() + toTableFieldName(name.substring(1));
}
/** 去除表名字段名第一个字母的数据处理 */
private static String toTableFieldName(String name)
{
StringBuilder strb = new StringBuilder();
//3.遇到下划线则下一字母大写,遇到$$中间的字母大写,并把$替换成_
boolean nextWord = false;
boolean nextReplace = false;
for (int i=0;i<name.length();i++)
{
char c = name.charAt(i);
if (c == '_')
{
nextWord = true;
continue;
}
if (c == '$')
{//把$转化为_
nextReplace = !nextReplace;
strb.append("_");
continue;
}
if (nextWord)
{
strb.append(String.valueOf(c).toUpperCase());
nextWord = false;
}
else if (nextReplace)
{
strb.append(String.valueOf(c).toUpperCase());
}
else
{
strb.append(String.valueOf(c).toLowerCase());
}
}
return strb.toString();
}
}
+139
View File
@@ -0,0 +1,139 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.SQLException;
import org.zhiqim.kernel.MultiInstance;
import org.zhiqim.kernel.annotation.AnAlias;
/**
* DDL调用,支持(alter)<br><br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
@AnAlias("ZDDL")
public interface ZDDL extends MultiInstance
{
/*****************************************************/
//字段和列类型之间的转换
/*****************************************************/
/**
* ORM定义的类型,转化为SQL类型,如string,15转化为varchar(15)
*
* @param type ORM定义的类型如string,15
* @return SQL类型,如varchar(15)
*/
public String toColumnType(String type);
/**
* ORM定义的类型,转化为SQL类型,如string,15转化为varchar(15)
*
* @param fieldType ORM定义的类型如string,int
* @param fieldLength ORM定义的类型长度,string和decimal时有效,如19,char | 10,2
* @return SQL类型,如varchar(15)
*/
public String toColumnType(String fieldType, String fieldLength);
/*****************************************************/
//alter DDL语句
/*****************************************************/
/**
* 修改一个表的名称
*
* @param table 表名
* @param newTable 新表名
* @throws SQLException 数据库异常
*/
public void alterTableName(String table, String newTable) throws SQLException;
/**
* 增加一个表的一列
*
* @param table 表名
* @param column 列名
* @param columnType 列类型
* @param notNull 是否允许为null
* @throws SQLException 数据库异常
*/
public void alterColumnAdd(String table, String column, String columnType, boolean notNull) throws SQLException;
/**
* 删除一个表的一列
*
* @param table 表名
* @param column 列名
* @throws SQLException 数据库异常
*/
public void alterColumnDrop(String table, String column) throws ORMException, SQLException;
/**
* 修改一个表的一列信息
*
* @param table 表名
* @param column 列名
* @param newColumn 新列名
* @param newColumnType 新列类型
* @param newNotNull 新列是否不为null
* @throws SQLException 数据库异常
*/
public void alterColumnInfo(String table, String column, String newColumn, String newColumnType, boolean newNotNull) throws ORMException, SQLException;
/**
* 修改一个表的列名
*
* @param table 表名
* @param column 列名
* @param newColumn 新列名
* @throws SQLException 数据库异常
*/
public void alterColumnName(String table, String column, String newColumn) throws ORMException, SQLException;
/**
* 修改一个表的一列类型
*
* @param table 表名
* @param column 列名
* @param newType 新类型
* @throws SQLException 数据库异常
*/
public void alterColumnType(String table, String column, String newColumnType, boolean newNotNull) throws ORMException, SQLException;
/**
* 增加表的主键
*
* @param table 表名
* @param columns 列名,多个用逗号隔开如AAA_AAA,BBB_BBB
* @throws SQLException 数据库异常
*/
public void alertPrimaryKeyAdd(String table, String columns) throws ORMException, SQLException;
/**
* 删除表的主键
*
* @param table 表名
* @throws SQLException 数据库异常
*/
public void alertPrimaryKeyDrop(String table) throws ORMException, SQLException;
}
+364
View File
@@ -0,0 +1,364 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.SQLException;
import java.util.List;
import org.zhiqim.kernel.MultiInstance;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.extend.LinkedMapSO;
import org.zhiqim.kernel.extend.MapSS;
import org.zhiqim.orm.dbo.CallParam;
import org.zhiqim.orm.dbo.CallResult;
/**
* 标准SQL调用,支持(executeUpdate, executeBatch, executeQuery)<br><br>
* executeUpdate, 执行更新SQL语句,支持insert,replace,update,delete等<br>
* executeBatch, 批量执行更新SQL语句,支持insert,replace,update,delete等<br>
* executeQuery, 执行查询SQL语句,<br>
* 返回结果可以是boolean,byte,short,int,long,String,Timestamp,double,byte[]等9种类型<br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
@AnAlias("ZSQL")
public interface ZSQL extends MultiInstance
{
/************************************************************************************************/
//select @@IDENTITY 查自增ID
/************************************************************************************************/
/**
* 查询当前自增ID值
*
* @return 整型
* @throws SQLException 数据库异常
*/
public int identityInt() throws SQLException;
/**
* 查询当前自增ID值
*
* @return 长整型
* @throws SQLException 数据库异常
*/
public long identityLong() throws SQLException;
/************************************************************************************************/
//exist 查询是否存在表或字段
/************************************************************************************************/
/**
* 查询表是否存在
*
* @param table 表名
* @return boolean存在是否
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean existTable(String table) throws ORMException, SQLException;
/************************************************************************************************/
//execute
/************************************************************************************************/
/**
* 执行标准SQL语句,不带参数,如DDL,DML语句
*
* @param sql SQL语句
* @throws SQLException 数据库异常
*/
public void execute(String sql) throws SQLException;
/**
* 批执行标准SQL语句,不带参数,如DDL,DML语句
*
* @param sqlList SQL语句列表
* @throws SQLException 数据库异常
*/
public void execute(List<String> sqlList) throws SQLException;
/************************************************************************************************/
//executeUpdate
/************************************************************************************************/
/**
* 无参数executeUpdate执行
*
* @param id SQL配置编号
* @return int 执行条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int executeUpdateId(String id) throws ORMException, SQLException;
/**
* executeUpdate执行
*
* @param id SQL配置编号
* @param param 参数,需和executeUpdate配置对应,否则将报错
* @return int 执行条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int executeUpdateId(String id, Object param) throws ORMException, SQLException;
/**
* executeUpdate执行
*
* @param id SQL配置编号
* @param param 参数,需和executeUpdate配置对应,否则将报错
* @param replaceMap 字符替换表
* @return int 执行条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int executeUpdateId(String id, Object param, MapSS replaceMap) throws ORMException, SQLException;
/**
* executeUpdate执行
*
* @param sql SQL语句
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int executeUpdate(String sql) throws ORMException, SQLException;
/**
* executeUpdate执行
*
* @param sql SQL语句
* @param param 参数,需和update配置对应,否则将报错
* @return int 执行条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int executeUpdate(String sql, Object param) throws ORMException, SQLException;
/**
* executeUpdate执行
*
* @param sql SQL语句
* @param param 参数,需和update配置对应,否则将报错
* @param replaceMap 字符替换表
* @return int 执行条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int executeUpdate(String sql, Object param, MapSS replaceMap) throws ORMException, SQLException;
/************************************************************************************************/
//executeBatch
/************************************************************************************************/
/**
* executeBatch执行
*
* @param id SQL配置编号
* @param paramList 参数列表
* @return int[] 执行结果数组
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] executeBatchId(String id, List<?> paramList) throws ORMException, SQLException;
/**
* executeBatch执行
*
* @param id SQL配置编号
* @param paramList 参数列表
* @param replaceMap 字符替换表
* @return int[] 执行结果数组
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] executeBatchId(String id, List<?> paramList, MapSS replaceMap) throws ORMException, SQLException;
/**
* executeBatch执行
*
* @param sql SQL语句
* @param paramList 参数列表
* @return int[] 执行结果数组
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] executeBatch(String sql, List<?> paramList) throws ORMException, SQLException;
/**
* executeBatch执行
*
* @param sql SQL语句
* @param paramList 参数列表
* @param replaceMap 字符替换表
* @return int[] 执行结果数组
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] executeBatch(String sql, List<?> paramList, MapSS replaceMap) throws ORMException, SQLException;
/************************************************************************************************/
//executeQuery
/************************************************************************************************/
/**
* executeQuery执行
*
* @param id SQL配置编号
* @param resultClass 结果类结构
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> executeQueryId(String id, Class<T> resultClass) throws ORMException, SQLException;
/**
* executeQuery执行
*
* @param id SQL配置编号
* @param resultClass 结果类结构
* @param param 参数
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> executeQueryId(String id, Class<T> resultClass, Object param) throws ORMException, SQLException;
/**
* executeQuery执行
*
* @param id SQL配置编号
* @param resultClass 结果类结构
* @param param 参数
* @param replaceMap 字符替换表
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> executeQueryId(String id, Class<T> resultClass, Object param, MapSS replaceMap) throws ORMException, SQLException;
/**
* executeQuery执行
*
* @param sql SQL语句
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public List<LinkedMapSO> executeQuery(String sql) throws ORMException, SQLException;
/**
* executeQuery执行
*
* @param sql SQL语句
* @param resultClass 结果类结构
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> executeQuery(String sql, Class<T> resultClass) throws ORMException, SQLException;
/**
* executeQuery执行
*
* @param sql SQL语句
* @param resultClass 结果类结构
* @param param 参数
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> executeQuery(String sql, Class<T> resultClass, Object param) throws ORMException, SQLException;
/**
* executeQuery执行
*
* @param sql SQL语句
* @param resultClass 结果类结构
* @param param 参数
* @param replaceMap 字符替换表
* @return 结果集
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> executeQuery(String sql, Class<T> resultClass, Object param, MapSS replaceMap) throws ORMException, SQLException;
/************************************************************************************************/
//call(函数&存储过程调用)
/************************************************************************************************/
/**
* call 函数&存储过程执行,无结果集,一般用于函数或count/sum等简单的存储过程
*
* @param sql SQL语句
* @param paramList 参数列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void call(String sql, List<CallParam> paramList) throws ORMException, SQLException;
/**
* call 函数&存储过程执行,支持替换表,无结果集,一般用于函数或count/sum等简单的存储过程
*
* @param sql SQL语句
* @param paramList 参数列表
* @param replaceMap 字符替换表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void call(String sql, List<CallParam> paramList, MapSS replaceMap) throws ORMException, SQLException;
/**
* call 存储过程执行,返回一个结果集
*
* @param sql SQL语句
* @param paramList 参数列表
* @param replaceMap 字符替换表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> call(String sql, List<CallParam> paramList, Class<T> resultClass) throws ORMException, SQLException;
/**
* call 函数&存储过程执行,支持多结果集
*
* @param sql SQL语句
* @param paramList 参数列表
* @param resultList 结果集列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void call(String sql, List<CallParam> paramList, List<CallResult> resultList) throws ORMException, SQLException;
/**
* call 函数&存储过程执行,支持多结果集
*
* @param sql SQL语句
* @param paramList 参数列表
* @param resultList 结果集列表
* @param replaceMap 字符替换表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void call(String sql, List<CallParam> paramList, List<CallResult> resultList, MapSS replaceMap) throws ORMException, SQLException;
}
+610
View File
@@ -0,0 +1,610 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.SQLException;
import java.util.List;
import org.zhiqim.kernel.MultiInstance;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.extend.MapSS;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.orm.dbo.Batcher;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;
import org.zhiqim.orm.dbo.defined._Table;
/**
* 标准类与数据库表映射调用,支持(truncate,exist,insert,replace,update,delete,count,sum,item,list,page)<br><br>
* truncate, 清除表类对应的表<br>
* exist, 检查表类对应的表是否存在<br>
* create 创建表类对应的表
* insert, 插入表类对应的表一条数据<br>
* replace, 替换表类对应的表一条数据,根据主键<br>
* update, 更新表类对应的表一条数据或根据条件更新数据<br>
* delete, 删除表类对应的表一条数据或根据条件删除数据<br>
* count, 统计表类对应的表数目<br>
* sum, 总计表类对应的表数目<br>
* item, 查询表类对应的表一条数据,根据主键,或根据条件排序取第一条<br>
* list, 查询表类对应的表列表,或根据条件排序<br>
* pag, 分页查询表类对应的表列表,指定分页页码和页数目<br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
* @version v1.2.0 @author zouzhigang 2016-6-27 修改原类名FDBO为ZTable,正式使用表类名称
*/
@AnAlias("ZTable")
public interface ZTable extends MultiInstance
{
/**
* 通过表名获取表对象
*
* @param tableName 表名
* @return 表对象
*/
public _Table getTableByTableName(String tableName);
/**
* 更新数据到缓存
*
* @param cls 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> void cache(Class<T> cls) throws ORMException, SQLException;
/**
* 批量处理插入/更新/删除数据
*
* @param batcherList 批量表
* @return 响应表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] batch(List<Batcher> batcherList) throws ORMException, SQLException;
/********************************************************************************************/
//exist 表是否存在
/********************************************************************************************/
/**
* 是否存在[表类]对应的[实际表]
*
* @param cls 表类
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(Class<?> cls) throws ORMException, SQLException;
/**
* 是否存在[表类]对应的[实际表]分表编号,支持表名中替换字段指定为$ID$,如LOG_TRACE$ID$
*
* @param cls 表类
* @param id 分表编号
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(Class<?> cls, String id) throws ORMException, SQLException;
/**
* 是否存在[表类]对应的[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param cls 表类
* @param replaceMap 可替换字段表
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(Class<?> cls, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//create 创建表
/********************************************************************************************/
/**
* 创建[表类]对应的[实际表]
*
* @param cls 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(Class<?> cls) throws ORMException, SQLException;
/**
* 创建[表类]对应的[实际表]ID分表
*
* @param cls 表类
* @param id 分表编号
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(Class<?> cls, String id) throws ORMException, SQLException;
/**
* 创建[表类]对应的[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param cls 表类
* @param replaceMap 可替换字段表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(Class<?> cls, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//drop 删除表
/********************************************************************************************/
/**
* 创建[表类]对应的[实际表]
*
* @param cls 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void drop(Class<?> cls) throws ORMException, SQLException;
/**
* 创建[表类]对应的[实际表]分表
*
* @param cls 表类
* @param id 分表编号
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void drop(Class<?> cls, String id) throws ORMException, SQLException;
/**
* 创建[表类]对应的[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param cls 表类
* @param replaceMap 可替换字段表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void drop(Class<?> cls, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//truncate 清空表
/********************************************************************************************/
/**
* 清空[表类]对应的[实际表]
*
* @param cls 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(Class<?> cls) throws ORMException, SQLException;
/**
* 清空[表类]对应的[实际表]分表,支持表名中替换字段指定为$ID$,如LOG_TRACE$ID$
*
* @param cls 表类
* @param id 分表编号
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(Class<?> cls, String id) throws ORMException, SQLException;
/**
* 清空[表类]对应的[实际表],支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param cls 表类
* @param replaceMap 替换表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(Class<?> cls, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//insert 插入数据
/********************************************************************************************/
/**
* 增加数据,传入标准[表类]对象
*
* @param data 表对象
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(Object data) throws ORMException, SQLException;
/**
* 增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(Object data, MapSS replaceMap) throws ORMException, SQLException;
/**
* 替换数据,传入标准[表类]对象和更新器(取fieldMap和replaceMap)当存在时指定修改的值
*
* @param data 表对象
* @param updater 更新器
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insertOrUpdate(Object data, Updater updater) throws ORMException, SQLException;
/**
* 批量增加数据
*
* @param dataList 表对象列表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] insertBatch(List<?> dataList) throws ORMException, SQLException;
/**
* 批量增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] insertBatch(List<?> dataList, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//replace 替换数据,MYSQL支持,如果有数据先删除后增加
/********************************************************************************************/
/**
* 替换数据,传入标准[表类]对象
*
* @param data 表对象
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(Object data) throws ORMException, SQLException;
/**
* 替换数据,支持表或字段中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(Object data, MapSS replaceMap) throws ORMException, SQLException;
/**
* 批量替换数据
*
* @param dataList 表对象列表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] replaceBatch(List<?> dataList) throws ORMException, SQLException;
/**
* 批量替换数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] replaceBatch(List<?> dataList, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//update 更新数据
/********************************************************************************************/
/**
* 更新数据,指定更新器需要更新的字段、条件和可替换表
*
* @param cls 表类
* @param updater 更新器
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Class<?> cls, Updater updater) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新
*
* @param data 表对象
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Object data) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持可替换表
*
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(Object data, MapSS replaceMap) throws ORMException, SQLException;
/********************************************************************************************/
//delete 删除数据
/********************************************************************************************/
/**
* 删除数据,多个主键时使用
*
* @param cls 表类
* @param ids 关键属性为数组,多个主键
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(Class<?> cls, Object... ids) throws ORMException, SQLException;
/**
* 删除数据,多个主键时使用
*
* @param cls 表类
* @param replaceMap 替换表
* @param ids 关键属性为数组,多个主键
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(Class<?> cls, MapSS replaceMap, Object... ids) throws ORMException, SQLException;
/**
* 删除数据, 根据条件
*
* @param cls 表类
* @param selector 对象选择器
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(Class<?> cls, Selector selector) throws ORMException, SQLException;
/**
* 批量删除数据,根据主键删除
*
* @param cls 表名
* @param idsList 关键属性为数组的列表,多个主键列表
* @param replaceMap 替换表
* @return 返回删除结果列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] deleteBatch(Class<?> cls, List<Object[]> idsList) throws ORMException, SQLException;
/**
* 批量删除数据,根据主键删除
*
* @param cls 表名
* @param replaceMap 替换表
* @param idsList 关键属性为数组的列表,多个主键列表
* @return 返回删除结果列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] deleteBatch(Class<?> cls, MapSS replaceMap, List<Object[]> idsList) throws ORMException, SQLException;
/********************************************************************************************/
//count 查询数目
/********************************************************************************************/
/**
* 查询数目,多个主键时使用
*
* @param cls 表类
* @param ids 关键属性值,支持多个
* @return 存在的数目
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> cls, Object... ids) throws ORMException, SQLException;
/**
* 查询数目,整表查询
*
* @param cls 表类
* @return int 数目值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> cls) throws ORMException, SQLException;
/**
* 查询数目,根据条件、可替换表查询
*
* @param cls 表类
* @param selector 对象查询器
* @return int 数目值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> cls, Selector selector)throws ORMException, SQLException;
/********************************************************************************************/
//sum 计算总和
/********************************************************************************************/
/**
* 计算总和
*
* @param cls 表类
* @param field 表字段
* @return 计算总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(Class<?> cls, String field) throws ORMException, SQLException;
/**
* 计算总和
*
* @param cls 表类
* @param selector 对象查询器
* @param field 表字段
* @return 计算总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(Class<?> cls, Selector selector, String field) throws ORMException, SQLException;
/**
* 计算多个总和
*
* @param cls 表类
* @param selector 对象查询器
* @param fields 多个表字段
* @return 计算多个总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long[] sum(Class<?> cls, Selector selector, String... fields) throws ORMException, SQLException;
/********************************************************************************************/
//item 查询一条数据
/********************************************************************************************/
/**
* 查询一个表对象,支持多个主键
*
* @param cls 表类
* @param ids 关键属性值
* @return 返回表对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> cls, Object... ids) throws ORMException, SQLException;
/**
* 查询一个表对象,并指定返回属性,查询第一行
*
* @param cls 表类
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> cls) throws ORMException, SQLException;
/**
* 查询一个表对象,并指定返回属性,查询条件和排序条件
*
* @param cls 表类
* @param selector 对象查询器
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> cls, Selector selector) throws ORMException, SQLException;
/********************************************************************************************/
//list 查询列表
/********************************************************************************************/
/**
* 查询表对象列表,全表查询
*
* @param cls 表类
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> cls) throws ORMException, SQLException;
/**
* 查询表对象列表,并指定返回属性,查询条件和排序条件
*
* @param cls 表类
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> cls, Selector selector) throws ORMException, SQLException;
/**
* 查询表对象列表,查询指定的位置的数据
*
* @param cls 表类
* @param pageNo 页码
* @param pageSize 页数
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> cls, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询表对象列表,并指定位置的,条件和排序条件
*
* @param cls 表类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> cls, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
/********************************************************************************************/
//page 分页显示
/********************************************************************************************/
/**
* 查询表对象分页信息
*
* @param cls 表类
* @param pageNo 页码
* @param pageSize 页数
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> cls, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询表对象分页信息
*
* @param cls 表类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> cls, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
}
+631
View File
@@ -0,0 +1,631 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.SQLException;
import java.util.List;
import org.zhiqim.kernel.MultiInstance;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.extend.LinkedMapSO;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.extend.MapSS;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;
import org.zhiqim.orm.dbo.defined._Table;
/**
* 自建表与数据库表映射调用
*
* @version v1.0.0 @author zouzhigang 2016-10-26 新建与整理
*/
@AnAlias("ZTabler")
public interface ZTabler extends MultiInstance
{
/**************************************************************************/
//exist 表是否存在
/**************************************************************************/
/**
* 是否存在[实际表]可替换表
*
* @param table 表类
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(_Table _table) throws ORMException, SQLException;
/**
* 是否存在[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param table 表类
* @param replaceMap 可替换字段表
* @return =true表示存在,=false表示不存在
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public boolean exist(_Table table, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//create 创建表
/**************************************************************************/
/**
* 创建[实际表]可替换表
*
* @param _table 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(_Table _table) throws ORMException, SQLException;
/**
* 创建[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表类
* @param replaceMap 可替换字段表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void create(_Table _table, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//drop 删除表
/**************************************************************************/
/**
* 删除[实际表]可替换表
*
* @param _table 表类
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void drop(_Table _table) throws ORMException, SQLException;
/**
* 删除[实际表]可替换表,支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表类
* @param replaceMap 可替换字段表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void drop(_Table _table, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//truncate 清空表
/**************************************************************************/
/**
* 清空[实际表]
*
* @param _table 表对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(_Table _table) throws ORMException, SQLException;
/**
* 清空[实际表],支持表名中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表对象
* @param replaceMap 替换表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public void truncate(_Table _table, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//insert 插入数据
/**************************************************************************/
/**
* 增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表定义对象
* @param data 表数据对象
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(_Table _table, LinkedMapSO data) throws ORMException, SQLException;
/**
* 增加数据,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param _table 表定义对象
* @param data 表类
* @param month 月份
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insertMonth(_Table _table, LinkedMapSO data, String month) throws ORMException, SQLException;
/**
* 增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表定义对象
* @param data 表数据对象
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insert(_Table _table, LinkedMapSO data, MapSS replaceMap) throws ORMException, SQLException;
/**
* 替换数据,传入标准[表类]对象和更新器(取fieldMap和replaceMap)当存在时指定修改的值
*
* @param _table 表定义对象
* @param data 表对象
* @param updater 更新器
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int insertOrUpdate(_Table _table, LinkedMapSO data, Updater updater) throws ORMException, SQLException;
/**
* 批量增加数据
*
* @param _table 表定义对象
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] insertBatch(_Table _table, List<LinkedMapSO> dataList) throws ORMException, SQLException;
/**
* 批量增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表定义对象
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] insertBatch(_Table _table, List<LinkedMapSO> dataList, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//replace 替换数据,MYSQL支持,如果有数据先删除后增加
/**************************************************************************/
/**
* 替换数据,传入标准[表类]对象
*
* @param _table 表定义对象
* @param data 表对象
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(_Table _table, LinkedMapSO data) throws ORMException, SQLException;
/**
* 替换数据,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param _table 表定义对象
* @param data 表对象
* @param month 月份
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replaceMonth(_Table _table, LinkedMapSO data, String month) throws ORMException, SQLException;
/**
* 替换数据,支持表或字段中有一个替换字段,如LOG_TRACE$ID$
*
* @param _table 表定义对象
* @param data 表对象
* @param replaceKey 替换键
* @param replaceValue 替换值
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(_Table _table, LinkedMapSO data, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 替换数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表定义对象
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int replace(_Table _table, LinkedMapSO data, MapSS replaceMap) throws ORMException, SQLException;
/**
* 批量替换数据
*
* @param _table 表定义对象
* @param dataList 表对象列表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] replaceBatch(_Table _table, List<LinkedMapSO> dataList) throws ORMException, SQLException;
/**
* 批量替换数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param _table 表定义对象
* @param dataList 表对象列表
* @param replaceMap 适配表
* @return int 表示插入的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] replaceBatch(_Table _table, List<LinkedMapSO> dataList, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//update 更新数据
/**************************************************************************/
/**
* 更新数据,指定更新器需要更新的字段、条件和可替换表
*
* @param _table 表定义对象
* @param updater 更新器
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(_Table _table, Updater updater) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新
*
* @param _table 表定义对象
* @param data 表对象
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(_Table _table, LinkedMapSO data) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持表名中替换字段指定为$MONTH$,如LOG_TRACE$MONTH$
*
* @param _table 表定义对象
* @param data 表对象
* @param month 月份
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int updateMonth(_Table _table, LinkedMapSO data, String month) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持表或字段中有一个替换字段,如LOG_TRACE$ID$
*
* @param _table 表定义对象
* @param data 表对象
* @param replaceKey 替换键
* @param replaceValue 替换值
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(_Table _table, LinkedMapSO data, String replaceKey, String replaceValue) throws ORMException, SQLException;
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持可替换表
*
* @param _table 表定义对象
* @param data 表对象
* @param replaceMap 适配表
* @return int 表示更新的条数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int update(_Table _table, LinkedMapSO data, MapSS replaceMap) throws ORMException, SQLException;
/**************************************************************************/
//delete 删除数据
/**************************************************************************/
/**
* 删除数据,多个主键时使用
*
* @param _table 表定义对象
* @param ids 关键属性为数组,多个主键
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(_Table _table, Object... ids) throws ORMException, SQLException;
/**
* 删除数据,多个主键时使用
*
* @param _table 表定义对象
* @param replaceMap 替换表
* @param ids 关键属性为数组,多个主键
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(_Table _table, MapSS replaceMap, Object... ids) throws ORMException, SQLException;
/**
* 删除数据, 根据条件
*
* @param _table 表定义对象
* @param selector 对象选择器
* @return 返回删除数
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int delete(_Table _table, Selector selector) throws ORMException, SQLException;
/**
* 批量删除数据,多个主键时使用
*
* @param _table 表定义对象
* @param idsList 关键属性为数组,多个主键的列表
* @return 返回删除数列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] deleteBatch(_Table _table, List<Object[]> idsList) throws ORMException, SQLException;
/**
* 批量删除数据,多个主键时使用
*
* @param _table 表定义对象
* @param replaceMap 替换表
* @param idsList 关键属性为数组,多个主键的列表
* @return 返回删除数列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int[] deleteBatch(_Table _table, MapSS replaceMap, List<Object[]> idsList) throws ORMException, SQLException;
/**************************************************************************/
//count 查询数目
/**************************************************************************/
/**
* 查询数目,多个主键时使用
*
* @param _table 表定义对象
* @param ids 关键属性值,支持多个
* @return 存在的数目
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(_Table _table, Object... ids) throws ORMException, SQLException;
/**
* 查询数目,整表查询
*
* @param _table 表定义对象
* @return int 数目值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(_Table _table) throws ORMException, SQLException;
/**
* 查询数目,根据条件、可替换表查询
*
* @param _table 表定义对象
* @param selector 对象查询器
* @return int 数目值
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(_Table _table, Selector selector)throws ORMException, SQLException;
/**************************************************************************/
//sum 计算总和
/**************************************************************************/
/**
* 计算总和
*
* @param _table 表定义对象
* @param field 表字段
* @return 计算总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(_Table _table, String field) throws ORMException, SQLException;
/**
* 计算总和
*
* @param _table 表定义对象
* @param selector 对象查询器
* @param field 表字段
* @return 计算总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(_Table _table, Selector selector, String field) throws ORMException, SQLException;
/**
* 计算多个总和
*
* @param _table 表定义对象
* @param selector 对象查询器
* @param fields 多个表字段
* @return 计算多个总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long[] sum(_Table _table, Selector selector, String... fields) throws ORMException, SQLException;
/**************************************************************************/
//item 查询一条数据
/**************************************************************************/
/**
* 查询一个表对象,支持多个主键
*
* @param _table 表定义实例
* @param ids 关键属性值
* @return 返回表对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public LinkedMapSO item(_Table _table, Object... ids) throws ORMException, SQLException;
/**
* 查询一个表对象,并指定返回属性,查询第一行
*
* @param _table 表定义实例
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public LinkedMapSO item(_Table _table) throws ORMException, SQLException;
/**
* 查询一个表对象,并指定返回属性,查询条件和排序条件
*
* @param _table 表定义实例
* @param selector 对象查询器
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public LinkedMapSO item(_Table _table, Selector selector) throws ORMException, SQLException;
/**************************************************************************/
//list 查询列表
/**************************************************************************/
/**
* 查询表对象列表,全表查询
*
* @param _table 表定义对象
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public List<LinkedMapSO> list(_Table _table) throws ORMException, SQLException;
/**
* 查询表对象列表,并指定返回属性,查询条件和排序条件
*
* @param _table 表定义对象
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public List<LinkedMapSO> list(_Table _table, Selector selector) throws ORMException, SQLException;
/**
* 查询表对象列表,查询指定的位置的数据
*
* @param _table 表定义对象
* @param pageNo 页码
* @param pageSize 页数
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public List<LinkedMapSO> list(_Table _table, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询表对象列表,并指定位置的,条件和排序条件
*
* @param _table 表定义对象
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public List<LinkedMapSO> list(_Table _table, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
/**************************************************************************/
//page 分页显示
/**************************************************************************/
/**
* 查询表对象分页信息
*
* @param _table 表定义对象
* @param pageNo 页码
* @param pageSize 页数
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public PageResult<LinkedMapSO> page(_Table _table, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询表对象分页信息
*
* @param _table 表定义对象
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public PageResult<LinkedMapSO> page(_Table _table, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
/**************************************************************************/
//内部ZTabler & ZTable 共享的方法
/**************************************************************************/
/**
* 通过表定义对象,组装插入或替换的SQL
* 1.insert & insertOrUpdate & insertBatch
* 2.replace & replaceBatch
* 调用
*
* @param _table 表定义对象
* @param statement insert & replace
* @return SQL语句
*/
public String toInsertOrReplaceSQL(_Table _table, String statement);
/**
* 通过表定义对象,组装更新字段SQL
* update & insertOrUpdate调用
*
* @param _table 表定义对象
* @param updater 更新器
* @param paramMap 参数表
* @return SQL语句
* @throws ORMException 映射异常
*/
public String toUpdateFieldSQL(_Table _table, Updater updater, MapSO paramMap) throws ORMException;
}
+199
View File
@@ -0,0 +1,199 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm;
import java.sql.SQLException;
import java.util.List;
import org.zhiqim.kernel.MultiInstance;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.orm.dbo.Selector;
/**
* 视图类与数据库表多表映射调用,支持(count,sum,item,list,page)<br><br>
* count, 统计视图类对应的关联表数目<br>
* sum, 总计视图类对应的关联表数目<br>
* item, 查询视图类对应的关联表一条数据,根据主键,或根据条件排序取第一条<br>
* list, 查询视图类对应的关联表列表,或根据条件排序<br>
* pag, 分页查询视图类对应的关联表列表,指定分页页码和页数目<br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
* @version v1.2.0 @author zouzhigang 2016-6-27 修改原类名FRHEL为ZView,正式使用视图名称
*/
@AnAlias("ZView")
public interface ZView extends MultiInstance
{
/*****************************************************/
//count 查询数目
/*****************************************************/
/**
* 查询数目,查全视图
*
* @param clazz 视图类
* @return 返回数目
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> clazz)throws ORMException, SQLException;
/**
* 查询数目,根据条件、可替换表查询
*
* @param clazz 视图类
* @param selector 对象查询器
* @return 返回数目
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public int count(Class<?> clazz, Selector selector)throws ORMException, SQLException;
/*****************************************************/
//sum 计算总和
/*****************************************************/
/**
* 计算总和,全视图求和
*
* @param clazz 视图类
* @param field 视图字段
* @return 返回总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(Class<?> clazz, String field) throws ORMException, SQLException;
/**
* 计算总和,根据条件视图中求和
*
* @param clazz 视图类
* @param field 视图字段
* @param selector 查询器
* @return 返回总和(sum)
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long sum(Class<?> clazz, String field, Selector selector) throws ORMException, SQLException;
/**
* 计算多个总和,全视图中多个求和
*
* @param clazz 视图类
* @param fieldArr 多个视图字段
* @return 返回计算多个总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long[] sum(Class<?> clazz, String[] fieldArr) throws ORMException, SQLException;
/**
* 计算多个总和,根据条件视图中多个求和
*
* @param clazz 视图类
* @param fieldArr 多个视图字段
* @param selector 查询器
* @return 返回计算多个总和
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public long[] sum(Class<?> clazz, String[] fieldArr, Selector selector) throws ORMException, SQLException;
/*****************************************************/
//item 查询一条数据
/*****************************************************/
/**
* 查询一个视图对象,全视图中取第一个
*
* @param clazz 视图类
* @return 返回视图对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> clazz) throws ORMException, SQLException;
/**
* 查询一个视图对象,可排序取第一个
*
* @param clazz 视图类
* @param selector 查询器
* @return 返回视图对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> clazz, Selector selector) throws ORMException, SQLException;
/*****************************************************/
//list 查询列表
/*****************************************************/
/**
* 查询列表,查全视图
*
* @param clazz 视图类
* @return 视图对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz) throws ORMException, SQLException;
/**
* 查询列表,根据查询器
*
* @param clazz 视图类
* @param selector 查询器
* @return 视图对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, Selector selector) throws ORMException, SQLException;
/*****************************************************/
//page 分页显示
/*****************************************************/
/**
* 查询视图分页信息,查全视图
*
* @param clazz 视图类
* @param pageNo 页码
* @param pageSize 页数
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> clazz, int pageNo, int pageSize) throws ORMException, SQLException;
/**
* 查询视图分页信息
*
* @param clazz 视图类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 查询器
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> clazz, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException;
}
@@ -0,0 +1,41 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据库参数或结果注解
*
* @version v1.0.0 @author zouzhigang 2016-6-24 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE})
public @interface AnDbo
{
}
@@ -0,0 +1,45 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据库参数或结果字段注解
*
* @version v1.0.0 @author zouzhigang 2016-6-24 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnDboField
{
/** 列名 */
String column();
/** 列类型 */
String type();
}
@@ -0,0 +1,42 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 索引注解,用于定义表支持的多个索引注解值
* @see AnIndexValue 索引注解值
*
* @version v1.0.0 @author zouzhigang 2015-10-22 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnIndex
{
AnIndexValue[] value();
}
@@ -0,0 +1,49 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 索引注解值,用于定义该类对应到一张表
* @see AnIndex 索引注解
*
* @version v1.0.0 @author zouzhigang 2015-10-22 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnIndexValue
{
/** 索引名 */
String name();
/** 索引列,多个逗号隔开 */
String column();
/** 索引类型,如unique */
boolean unique() default false;
}
@@ -0,0 +1,51 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 表注解类,用于定义该类对应到一张表
* @see AnTableField 定义表属性
* @see AnIndexValue 定义表索引属性
* @see AnViewJoin 定义视图中表连接关系
*
* @version v1.0.0 @author zouzhigang 2015-10-22 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnTable
{
/** 表名 */
String table();
/** 表主键 */
String key();
/** 表存储类型如innodb */
String type() default "";
}
@@ -0,0 +1,49 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 表字段注解类,用于定义该字段对应的个表的字段
* @see AnTable 定义表属性
*
* @version v1.0.0 @author zouzhigang 2015-11-13 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnTableField
{
/** 列名 */
String column();
/** 列类型,共9种,如int|string,32|binary,2000 */
String type();
/** 列是否允许为null,为空时表示不适用于创建表 */
boolean notNull() default false;
}
@@ -0,0 +1,42 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 表可替换字段注解类,用于定义该字段对应的分表时的字段
* @see AnTable 定义表属性
*
* @version v1.0.0 @author zouzhigang 2015-11-13 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnTableReplace
{
String value();
}
@@ -0,0 +1,44 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 视图注解类,用于定义该类对应到多表的关联
* @see AnViewField 定义视图属性
* @see AnViewJoin 定义视图中表连接关系
*
* @version v1.0.0 @author zouzhigang 2015-10-22 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnView
{
/** 多表名之间用逗号隔开 */
String value();
}
@@ -0,0 +1,47 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 视图字段注解类,用于定义该字段对应的个表的字段
* @see AnView 定义视图属性
* @see AnViewJoin 定义视图中表连接关系
*
* @version v1.0.0 @author zouzhigang 2015-11-13 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnViewField
{
/** 表名 */
String table();
/** 列名 */
String column();
}
@@ -0,0 +1,43 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* 表连接注解类,用于定义视图需要的多个连接属性
* @see AnViewJoinValue 定义一个连接属性
*
* @version v1.0.0 @author zouzhigang 2015-10-22 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnViewJoin
{
AnViewJoinValue[] value();
}
@@ -0,0 +1,59 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* 表连接注解属性类,用于定义视图的一个连接属性
* @see AnViewJoin 定义一个连接属性放置到连接表中
*
* @version v1.0.0 @author zouzhigang 2015-10-22 新建与整理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AnViewJoinValue
{
/** 连接类型(EQUAL|LEFT|RIGHT) */
String type();
/** 左表名 */
String lTable();
/** 左表列名 */
String lColumn();
/** 右表名 */
String rTable() default "";
/** 右表列名 */
String rColumn() default "";
/** 右值,右值和右表名右表列名互斥只取一个 */
String rValue() default "";
}
+471
View File
@@ -0,0 +1,471 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.cache;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.zhiqim.kernel.extend.HashMapCO;
import org.zhiqim.kernel.extend.HashMapCV;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.paging.PageBuilder;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.schedule.Scheduler;
import org.zhiqim.kernel.schedule.TaskThreader;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Objects;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.ORMServer;
import org.zhiqim.orm.dbo.Comparator;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.condition._Equal;
import org.zhiqim.orm.dbo.defined._Table;
import org.zhiqim.orm.impl.ZTableImplement;
/**
* 表缓存
*
* @version v1.0.0 @author zhichenggang 2017-7-1 新建与整理
*/
public final class ZTableCache
{
private static final Log log = LogFactory.getLog(ZTableCache.class);
private final ORMServer server;
private final HashMapCO lockMap;
private final HashMapCV<List<?>> cache;
private final HashMapCV<HashMap<ZTableCacheKey, ?>> index;
private final Scheduler scheduler;
public ZTableCache(ORMServer server)
{
this.server = server;
this.lockMap = new HashMapCO();
this.cache = new HashMapCV<>();
this.index = new HashMapCV<>();
//增加计划任务
this.scheduler = new Scheduler();
this.scheduler.create();
}
/** 安排任务 */
public void schedule()
{
for (TaskThreader task : server.getCacheMap().values())
{
this.scheduler.addTask(task);
}
}
/** 缓存回调刷新 */
public <T> void cache(Class<?> clazz, List<T> list) throws ORMException, SQLException
{
Object lock = lock(clazz);
synchronized (lock)
{//表内锁
//1.创建表缓存
List<?> oList = cache.remove(clazz);
if (oList != null)
{
oList.clear();
oList = null;
}
cache.put(clazz, list);
//2.创建表主键索引
_Table _table = ((ZTableImplement)server.table()).getTable(clazz);
String[] keyFields = _table.getKeyFieldArr();
if (keyFields.length == 0)
{//没有主键
index.put(clazz, null);
}
else
{
//把主键数组换成字段数组
HashMap<ZTableCacheKey, T> map = new HashMap<>();
for (T item : list)
{
ZTableCacheKey key = new ZTableCacheKey(keyFields.length);
for (int i=0;i<keyFields.length;i++)
{
key.set(i, Classes.getFieldValue(item, keyFields[i]));
}
map.put(key, item);
}
index.put(clazz, map);
}
}
log.info("刷新缓存[%s]", clazz.getName());
}
/********************************************************************************************/
//item 查询一条数据
/********************************************************************************************/
/**
* 查询一个表对象,并指定返回属性,查询第一行
*
* @param clazz 表类
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> T item(Class<T> clazz) throws ORMException, SQLException
{
List<T> list = check(clazz);
if (list.isEmpty())
return null;
return Objects.copy(list.get(0), Classes.newInstance(clazz));
}
/**
* 查询一个表对象,支持多个主键
*
* @param clazz 表类
* @param ids 关键属性值
* @return 返回表对象
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
@SuppressWarnings("unchecked")
public <T> T item(Class<T> clazz, Object... ids) throws ORMException, SQLException
{
List<T> list = check(clazz);
if (list.isEmpty())
return null;
//读取索引表
HashMap<ZTableCacheKey, T> map = (HashMap<ZTableCacheKey, T>)index.get(clazz);
if (map == null)
return null;
return map.get(new ZTableCacheKey(ids));
}
/**
* 查询一个表对象,并指定返回属性,查询条件和排序条件
*
* @param clazz 表类
* @param selector 对象查询器
* @return 返回表对象
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
@SuppressWarnings("unchecked")
public <T> T item(Class<T> clazz, Selector selector) throws ORMException, SQLException
{
if (selector == null)
return item(clazz);
List<T> list = check(clazz);
if (list.isEmpty())
return null;
if (selector.hasCondition())
{//有条件的
HashMap<ZTableCacheKey, T> map = (HashMap<ZTableCacheKey, T>)index.get(clazz);
if (map != null)
{//如果有索引表的支持,则判断一下是否包含索引的条件
_Table _table = ((ZTableImplement)server.table()).getTable(clazz);
String[] keyFields = _table.getKeyFieldArr();
ZTableCacheKey key = new ZTableCacheKey(keyFields.length);
for (Condition condition : selector.getConditionList())
{
if (!(condition instanceof _Equal))
continue;
_Equal equal = (_Equal)condition;
int idx = Arrays.indexOf(keyFields, equal.getField());
if (idx != -1)
{//把结果配对到主键中
key.set(idx, equal.getValue());
}
}
if (key.isAllKey())
{
T result = map.get(key);
if (result == null)
return null;
return match(result, selector)?result:null;
}
}
}
//逐个检查
list = fatch(clazz, list, selector);
if (list.isEmpty())
return null;
//取第一个
return Objects.copy(list.get(0), Classes.newInstance(clazz));
}
/********************************************************************************************/
//list 查询列表
/********************************************************************************************/
/**
* 查询表对象列表,全表查询
*
* @param clazz 表类
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz) throws ORMException, SQLException
{
return list(clazz, null);
}
/**
* 查询表对象列表,并指定返回属性,查询条件和排序条件
*
* @param clazz 表类
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, Selector selector) throws ORMException, SQLException
{
List<T> list = check(clazz);
if (list.isEmpty())
return new ArrayList<T>();
list = fatch(clazz, list, selector);
//最后取拷贝数据
return copyList(clazz, list);
}
/**
* 查询表对象列表,查询指定的位置的数据
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @return 返回表对象列表
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, int pageNo, int pageSize) throws ORMException, SQLException
{
return list(clazz, pageNo, pageSize, null);
}
/**
* 查询表对象列表,并指定位置的,条件和排序条件
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 返回表对象列表
* @throws ORMException 映射异常,如果传入的属性不在配置文件中则异常
* @throws SQLException 数据库异常
*/
public <T> List<T> list(Class<T> clazz, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException
{
List<T> list = check(clazz);
if (list.isEmpty())
return new ArrayList<T>();
list = fatch(clazz, list, selector);
//取得分页的列表
list = PageBuilder.pageList(pageNo, pageSize, list);
//最后取拷贝数据
return copyList(clazz, list);
}
/********************************************************************************************/
//page 分页显示
/********************************************************************************************/
/**
* 查询表对象分页信息
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> clazz, int pageNo, int pageSize) throws ORMException, SQLException
{
return page(clazz, pageNo, pageSize, null);
}
/**
* 查询表对象分页信息
*
* @param clazz 表类
* @param pageNo 页码
* @param pageSize 页数
* @param selector 对象查询器
* @return 分页信息,包括总页数,页码,页数和查询的记录
* @throws ORMException 映射异常
* @throws SQLException 数据库异常
*/
public <T> PageResult<T> page(Class<T> clazz, int pageNo, int pageSize, Selector selector) throws ORMException, SQLException
{
if (selector == null)
return page(clazz, pageNo, pageSize);
List<T> list = check(clazz);
if (list.isEmpty())
return PageBuilder.newResult(pageNo, pageSize);
list = fatch(clazz, list, selector);
//取得分页的列表
int total = list.size();
list = PageBuilder.pageList(pageNo, pageSize, list);
//取得分页列表的拷贝数据
list = copyList(clazz, list);
//最后封装成分页对象
return PageBuilder.newResult(total, pageNo, pageSize, list);
}
/********************************************************************************************/
//私用共享方
/********************************************************************************************/
@SuppressWarnings("unchecked") /** 检查缓存,未缓存的加载缓存 */
private <T> List<T> check(Class<T> clazz) throws ORMException, SQLException
{
List<T> list = (List<T>) cache.get(clazz);
if (list != null)
return list;
//第一次没有数据,执行更新缓存操作
synchronized (cache)
{
list = (List<T>) cache.get(clazz);
if (list == null)
{//第二次作双重检查
server.table().cache(clazz);
}
}
if (list == null)
{//最后再检查一次
list = (List<T>) cache.get(clazz);
}
return list;
}
/** 抓取列表,没条件的全列表,有条件的逐个匹配 */
private <T> List<T> fatch(Class<T> clazz, List<T> list, Selector selector)
{
if (selector == null || (!selector.hasCondition() && !selector.hasOrderby()))
{//没条件且不要排序的,无需拷贝列表,直接返回缓存原始列表即可
return list;
}
List<T> nList = null;
if (!selector.hasCondition())
{//没条件的,但要排序的,拷贝列表
nList = Lists.copy(list, false);
}
else
{//有条件的
nList = new ArrayList<>();
for (T item : list)
{//逐个匹配
if (match(item, selector))
nList.add(item);
}
}
if (nList.size() > 1 && selector.hasOrderby())
{//数据大于1条的,且要求排序的作排序
Collections.sort(nList, new Comparator<>(selector));
}
return nList;
}
/** 匹配对象 */
private <T> boolean match(T item, Selector selector)
{
for (Condition c : selector.getConditionList())
{
if (!c.match(item))
return false;
}
return true;
}
/** 读取表锁 */
private Object lock(Class<?> clazz)
{
synchronized (this)
{
Object lock = lockMap.get(clazz);
if (lock == null)
{
lock = new Object();
lockMap.put(clazz, lock);
}
return lock;
}
}
/** 拷贝列表,数据全部重新创建 */
private <T> List<T> copyList(Class<T> clazz, List<T> list)
{
if (list.isEmpty())
return new ArrayList<>();
ArrayList<T> cList = new ArrayList<>(list.size());
for (T item : list)
{
cList.add(Objects.copy(item, Classes.newInstance(clazz)));
}
return Lists.trim(cList);
}
}
+89
View File
@@ -0,0 +1,89 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.cache;
import java.util.Arrays;
/**
* 表缓存主键
*
* @version v1.0.0 @author zouzhigang 2019-3-21 新建与整理
*/
public class ZTableCacheKey
{
private Object[] objs;
public ZTableCacheKey(int count)
{
this.objs = new Object[count];
}
public ZTableCacheKey(Object[] ids)
{
this.objs = ids;
}
public void set(int idx, Object obj)
{
this.objs[idx] = obj;
}
public Object[] get()
{
return objs;
}
public boolean isAllKey()
{//有一个为空则非全KEY匹配
for (Object id : objs)
{
if (id == null)
return false;
}
return true;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(objs);
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ZTableCacheKey other = (ZTableCacheKey) obj;
if (!Arrays.equals(objs, other.objs))
return false;
return true;
}
}
@@ -0,0 +1,62 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.cache;
import java.sql.SQLException;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.schedule.Task;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.ZTable;
/**
* 表缓存刷新任务
*
* @version v1.4.1 @author zouzhigang 2018-5-3 新建与整理
*/
public class ZTableCacheTask implements Task
{
private static final Log log = LogFactory.getLog(ZTableCache.class);
private final ZTable zTable;
private final Class<?> clazz;
public ZTableCacheTask(ZTable zTable, Class<?> clazz)
{
this.zTable = zTable;
this.clazz = clazz;
}
@Override
public void execute()
{
try
{
zTable.cache(clazz);
}
catch (ORMException | SQLException e)
{
log.error("刷新缓存[%s]时异常", e, clazz.getName());
}
}
}
@@ -0,0 +1,116 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.config;
import java.io.InputStream;
import java.util.Map;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.zhiqim.kernel.constants.XmlConstants;
import org.zhiqim.kernel.extend.LinkedMapSS;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.kernel.xml.Xmls;
import org.zhiqim.orm.ORMConstants;
import org.zhiqim.orm.ORMException;
/**
* ZhiqimSQL配置信息,id和SQL语句<br><br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ZSQLConfig implements ORMConstants, XmlConstants
{
private String name;
private LinkedMapSS sqlMap = new LinkedMapSS();
public ZSQLConfig(String name)
{
this.name = name;
}
public String toString()
{
StringBuilder strb = new StringBuilder();
strb.append(_XML_DEFIND_).append(_BR_);
strb.append(Z_SQL_CONFIG_XML_DOCTYPE).append(_BR_);
strb.append(Z_SQL_CONFIG_XML_HEAD).append(_BR_).append(_BR_);
for (Map.Entry<String, String> entry : sqlMap.entrySet())
{
strb.append("<sql id=\">").append(entry.getKey()).append("\">").append(_BR_);
strb.append("<![CDATA[").append(_BR_);
strb.append(entry.getValue()).append(_BR_);
strb.append("]]>").append(_BR_);
strb.append("</sql>").append(_BR_);
}
strb.append(_BR_);
strb.append(Z_SQL_CONFIG_XML_TAIL);
return strb.toString();
}
/**
* 加载XML
*
* @param in 输入流
* @throws Exception 可能的异常
*/
public void load(InputStream in) throws Exception
{
Document document = Xmls.buildDocument(in, new ZSQLResolver());
//遍历<sql>标签
NodeList updateList = document.getElementsByTagName("sql");
for (int i=0;i<updateList.getLength();i++)
{
Node node = updateList.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
continue;
String id = Xmls.getAttribute(node, _ID_);
String sql = node.getTextContent();
if (Validates.isEmptyBlank(sql))
throw new ORMException("不允许SQL语句为空的配置,[id="+id+"]");
sqlMap.put(id, Sqls.formatSpace(sql));
}
}
public String getName()
{
return name;
}
public String getSQL(String id)
{
return sqlMap.get(id);
}
public LinkedMapSS getSQLMap()
{
return sqlMap;
}
}
@@ -0,0 +1,50 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.config;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.zhiqim.kernel.util.Resources;
import org.zhiqim.orm.ORMConstants;
/**
* 实现DTD本地验证,这样则不要到zhiqim.org下载验证 <br>
*/
public class ZSQLResolver implements EntityResolver, ORMConstants
{
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException
{
if (Z_SQL_CONFIG_DTD_PUBLIC_ID.equals(publicId))
{
InputStream stream = Resources.getResourceStream(ZSQLResolver.class, Z_SQL_CONFIG_DTD_PATH);
return new InputSource(stream);
}
return null;
}
}
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!ELEMENT zhiqim-sql (sql*)>
<!ELEMENT sql (#PCDATA)>
<!ATTLIST sql id ID #REQUIRED>
@@ -0,0 +1,103 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
public class ZCall
{
/**
* 从存储过程中读取对象
*
* @param resultClass 结果类
* @param cstmt 过程
* @param index 索引值
* @return 索引位置的对象
* @throws SQLException SQL异常
*/
public static Object getValue(Class<?> resultClass, CallableStatement cstmt, int index) throws SQLException
{
if (resultClass == boolean.class || resultClass == Boolean.class)
return cstmt.getBoolean(index);
else if (resultClass == byte.class || resultClass == Byte.class || resultClass == short.class || resultClass == Short.class || resultClass == int.class || resultClass == Integer.class)
return cstmt.getInt(index);
else if (resultClass == long.class || resultClass == Long.class)
return cstmt.getLong(index);
//日期类型
else if (resultClass == Timestamp.class)
return cstmt.getTimestamp(index);
else if (resultClass == Date.class)
return cstmt.getDate(index);
else if (resultClass == Time.class)
return cstmt.getTime(index);
//字符串
else if (resultClass == String.class)
return cstmt.getString(index);
//二进制
else if (resultClass == byte[].class)
return cstmt.getBytes(index);
else
{//其他类型
return cstmt.getObject(index);
}
}
/**
* 通过类,对应到存储过程的类型
*
* @param clazz 类结构
* @return 数据库字段类型
*/
public static int getType(Class<?> clazz)
{
if (clazz == null)
return Types.NULL;
else if (clazz == boolean.class || clazz == Boolean.class)
return Types.BOOLEAN;
else if (clazz == byte.class || clazz == Byte.class || clazz == short.class || clazz == Short.class || clazz == int.class || clazz == Integer.class)
return Types.INTEGER;
else if (clazz == long.class || clazz == Long.class)
return Types.BIGINT;
//日期类型
else if (clazz == Timestamp.class)
return Types.TIMESTAMP;
else if (clazz == Date.class)
return Types.DATE;
else if (clazz == Time.class)
return Types.TIME;
//字符串
else if (clazz == String.class)
return Types.VARCHAR;
//二进制
else if (clazz == byte[].class)
return Types.BLOB;
else
{//其他类型
return Types.OTHER;
}
}
}
@@ -0,0 +1,456 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
* 数据库连接类,对Connection进行封装,增加对是否空闲,空闲时长和处理数等字段,以及close释放到连接池中 <br><br>
* 1.connection属性为通过DataSource创建的连接信息<br>
* 2.isIdle,idleTime,completedCount表示空闲时数据以及处理数<br>
* 3.close()为提供业务关闭时释放连接<br>
* 4.shutdown()为连接池关闭连接<br>
* 5.isConnectionAvailable()检查数据库连接有效性<br>
* 6.isExcessTimeOrNum()检查是否超出空闲时长和处理数<br>
* 采用LRU(Least Recently Used)算法对连接进行管理,即每次提供的缓存连接都是最近的,那么最远的就会超出最大空闲了。
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ZConnection implements Connection
{
private ZDataSource source;
private Connection conn;
private String connId;
private long keepTimeMs;
private volatile boolean autoCommit;
private volatile boolean closed;
private volatile boolean idle;
private volatile long idleTimeMs;
public ZConnection(ZDataSource source, Connection conn)
{
this.source = source;
this.conn = conn;
this.connId = source.nextSequence();
this.keepTimeMs = System.currentTimeMillis();
try{this.autoCommit = conn.getAutoCommit();}catch (SQLException e){this.autoCommit = true;}
this.idle = true;
this.idleTimeMs = keepTimeMs;
}
/** 当前连接编号 */
public String getId()
{
return connId;
}
/** 当前连接是否空闲 */
public boolean isIdle()
{
return !closed && idle;
}
/** 当前线程是否运行 */
public boolean isActive()
{
return !idle;
}
/** 设置连接为运行中 */
public ZConnection active()
{
idle = false;
source.active();
return this;
}
/** 设置连接为空闲中 */
public void idle()
{
idle = true;
idleTimeMs = System.currentTimeMillis();
source.idle();
}
/**
* 检查数据库连接是否超过指定的最大保持时长、最大空闲时长和最大调用量
*
* @return =true表示超过,=false可用
*/
public boolean isKeepOrIdleTimeout()
{
if ((System.currentTimeMillis() - keepTimeMs) > source.getMaxKeepTimeMs())
return true;
if ((System.currentTimeMillis() - idleTimeMs) > source.getMaxIdleTimeMs())
return true;
return false;
}
/**
* 检查数据库连接
*
* @return =true,正常,=false不可用
*/
public boolean isConnectionAvailable()
{
if (conn == null)
return false;
ResultSet rst = null;
try
{
DatabaseMetaData metaData = conn.getMetaData();
rst = metaData.getTables(null, null, "PROBABLYNOT", new String[]{"TABLE"});
return true;
}
catch (SQLException e)
{
return false;
}
finally
{
ZDBClose.close(rst);
}
}
public void setAutoCommit()
{
try{conn.setAutoCommit(autoCommit);}catch (SQLException e){}
}
void shutdown()
{
closed = true;
try{if (!conn.isClosed())conn.close();}catch(SQLException e){}
}
public void close() throws SQLException
{
try{conn.clearWarnings();}catch(Exception e){}
source.releaseConnection(this);
}
/** 获取连接已保持时长 */
public long getKeepTimeMs()
{
return keepTimeMs;
}
/** 获取连接已空闲时长 */
public long getIdleTimeMs()
{
return idleTimeMs;
}
public int getHoldability() throws SQLException
{
return conn.getHoldability();
}
public int getTransactionIsolation() throws SQLException
{
return conn.getTransactionIsolation();
}
public void clearWarnings() throws SQLException
{
conn.clearWarnings();
}
public void commit() throws SQLException
{
conn.commit();
}
public void rollback() throws SQLException
{
conn.rollback();
}
public boolean getAutoCommit() throws SQLException
{
return conn.getAutoCommit();
}
public boolean isClosed()
{
if (closed){return true;}
try{return conn.isClosed();}catch (SQLException e) {return true;}
}
public boolean isReadOnly() throws SQLException
{
return conn.isReadOnly();
}
public void setHoldability(int holdability) throws SQLException
{
conn.setHoldability(holdability);
}
public void setTransactionIsolation(int level) throws SQLException
{
conn.setTransactionIsolation(level);
}
public void setAutoCommit(boolean autoCommit) throws SQLException
{
this.autoCommit = autoCommit;
conn.setAutoCommit(autoCommit);
}
public void setReadOnly(boolean readOnly) throws SQLException
{
conn.setReadOnly(readOnly);
}
public String getCatalog() throws SQLException
{
return conn.getCatalog();
}
public void setCatalog(String catalog) throws SQLException
{
conn.setCatalog(catalog);
}
public DatabaseMetaData getMetaData() throws SQLException
{
return conn.getMetaData();
}
public SQLWarning getWarnings() throws SQLException
{
return conn.getWarnings();
}
public Savepoint setSavepoint() throws SQLException
{
return conn.setSavepoint();
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
conn.releaseSavepoint(savepoint);
}
public void rollback(Savepoint savepoint) throws SQLException
{
conn.rollback(savepoint);
}
public Statement createStatement() throws SQLException
{
return conn.createStatement();
}
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
return conn.createStatement(resultSetType, resultSetConcurrency);
}
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
return conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
}
public Map<String, Class<?>> getTypeMap() throws SQLException
{
return conn.getTypeMap();
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException
{
conn.setTypeMap(map);
}
public String nativeSQL(String sql) throws SQLException
{
return conn.nativeSQL(sql);
}
public CallableStatement prepareCall(String sql) throws SQLException
{
return conn.prepareCall(sql);
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
return conn.prepareCall(sql, resultSetType, resultSetConcurrency);
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
return conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
public PreparedStatement prepareStatement(String sql) throws SQLException
{
return conn.prepareStatement(sql);
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
return conn.prepareStatement(sql, autoGeneratedKeys);
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{
return conn.prepareStatement(sql, columnIndexes);
}
public Savepoint setSavepoint(String name) throws SQLException
{
return conn.setSavepoint(name);
}
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
return conn.prepareStatement(sql, columnNames);
}
public <T> T unwrap(Class<T> iface) throws SQLException
{
return conn.unwrap(iface);
}
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
return conn.isWrapperFor(iface);
}
public Clob createClob() throws SQLException
{
return conn.createClob();
}
public Blob createBlob() throws SQLException
{
return conn.createBlob();
}
public NClob createNClob() throws SQLException
{
return conn.createNClob();
}
public SQLXML createSQLXML() throws SQLException
{
return conn.createSQLXML();
}
public boolean isValid(int timeout) throws SQLException
{
return conn.isValid(timeout);
}
public void setClientInfo(String name, String value) throws SQLClientInfoException
{
conn.setClientInfo(name, value);
}
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
conn.setClientInfo(properties);
}
public String getClientInfo(String name) throws SQLException
{
return conn.getClientInfo(name);
}
public Properties getClientInfo() throws SQLException
{
return conn.getClientInfo();
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException
{
return conn.createArrayOf(typeName, elements);
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
return conn.createStruct(typeName, attributes);
}
/**********************************************************/
//JDK1.7增加
/**********************************************************/
public void setSchema(String schema) throws SQLException
{
}
public String getSchema() throws SQLException
{
return null;
}
public void abort(Executor executor) throws SQLException
{
}
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
}
public int getNetworkTimeout() throws SQLException
{
return 0;
}
}
@@ -0,0 +1,153 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
/**
* 数据库连接测试类 <br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ZConnectionTester
{
private static final Log log = LogFactory.getLog("database.log");
public final static int CONNECTION_IS_OKAY = 0;
public final static int CONNECTION_IS_INVALID = -1;
public final static int DATABASE_IS_INVALID = -8;
private final static Set<String> INVALID_DB_STATES;
static
{
Set<String> temp = new HashSet<String>();
temp.add("08001"); //SQL State "Unable to connect to data source"
temp.add("08007"); //SQL State "Connection failure during transaction"
temp.add(null); //SQL State "Io 异常: Connection reset by peer: socket write error"
// MySql appently uses this state to indicate a stale, expired
// connection when the database is fine, so we'll not presume
// this SQL state signals an invalid database.
temp.add("08S01"); //SQL State "Communication link failure"
INVALID_DB_STATES = Collections.unmodifiableSet(temp);
}
private ZDataSource dataSource = null;
private ZConnection testconnection = null;
public ZConnectionTester(ZDataSource dataSource)
{
this.dataSource = dataSource;
}
/**
* 判断数据库是否断开
*
* @return boolean =true表示断开,=false表示正常
*/
public boolean isDbBreak()
{
if (testconnection == null)
{
testconnection = dataSource.newProxyConnection("测试");
if (testconnection == null)
return true;
}
if (testconnection.isClosed() || testconnection.isKeepOrIdleTimeout())
{
testconnection.shutdown();
testconnection = null;
testconnection = dataSource.newProxyConnection("测试");
if (testconnection == null)
return true;
}
int status = isConnectionAvailable(testconnection);
if (status == CONNECTION_IS_OKAY)
return false;
testconnection.shutdown();
testconnection = null;
return true;
}
/**
* 检查数据库连接
*
* @param connection 数据库连接
* @return =0,正常,=-1,该连接异常,=-8,数据库异常
*/
public int isConnectionAvailable(Connection connection)
{
if (connection == null)
return CONNECTION_IS_INVALID;
ResultSet rst = null;
try
{
DatabaseMetaData metaData = connection.getMetaData();
rst = metaData.getTables(null, null, "PROBABLYNOT", new String[]{"TABLE"});
return CONNECTION_IS_OKAY;
}
catch (SQLException e)
{
String state = e.getSQLState();
if (INVALID_DB_STATES.contains(state))
{
log.error("检查数据库连接是否可用时:数据库不可用");
return DATABASE_IS_INVALID;
}
else
{
log.error("检查数据库连接是否可用时:连接不可用");
return CONNECTION_IS_INVALID;
}
}
finally
{
ZDBClose.close(rst);
}
}
/** 关闭测试连接 */
public void shutdown()
{
if (testconnection != null)
{
testconnection.shutdown();
testconnection = null;
}
}
}
@@ -0,0 +1,104 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
/**
* 数据库关闭工具类
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public final class ZDBClose
{
private static final Log log = LogFactory.getLog(ZDBClose.class);
/** 关闭连接结果集 */
public static void close(ResultSet rst)
{
try
{
if (rst != null)
rst.close();
}
catch (Exception e)
{
log.error(e.getMessage());
}
}
/** 关闭连接属性 */
public static void close(Statement stmt)
{
try
{
if (stmt != null)
stmt.close();
}
catch (Exception e)
{
log.error(e.getMessage());
}
}
/** 关闭连接属性 */
public static void close(ResultSet rst, Statement stmt)
{
close(rst);
close(stmt);
}
/** 关闭/归还连接 */
public static void close(Connection conn)
{
try
{
if (conn != null)
conn.close();
}
catch (SQLException e)
{
log.error(e.getMessage());
}
}
/** 关闭和归还连接属性 */
public static void close(Statement stmt, Connection conn)
{
close(stmt);
close(conn);
}
/** 关闭和归还连接属性 */
public static void close(ResultSet rst, Statement stmt, Connection conn)
{
close(rst);
close(stmt);
close(conn);
}
}
@@ -0,0 +1,681 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.zhiqim.kernel.control.ThreadLock;
import org.zhiqim.kernel.control.Threadx;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Randoms;
import org.zhiqim.kernel.util.Threads;
import org.zhiqim.kernel.util.seqs.Sequence;
/**
* 数据库配置与管理类 <br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ZDataSource extends Threadx implements DataSource, Runnable
{
private static final Log log = LogFactory.getLog("database.log");
private static final String JNDI = "jndi"; //JNDI
private static final int CHK_TIME = 60 * 1000; //每60秒检查一次线程池
//数据库基础属性
private final String id; //数据库服务编号
private final Sequence sequence = new Sequence(6); //数据库连接序号
private final ThreadLock lock = new ThreadLock(); //数据库连接有效时通知锁
private final List<ZConnection> connList; //数据库连接池
private final ConcurrentHashMap<ZConnection, String> closedMap; //数据库连接池等待关闭列表
private final AtomicInteger activeSize; //数据库连接活跃数
//数据库驱动配置
private String driver; //数据库驱动
private String url; //数据库URL
private String user; //数据库用户名
private String pass; //数据库密码
private int level; //事务隔离级别0/1/2/4/8分别表示不支持事务/脏读/不支持读未提交/再次读取相同的数据而不会失败,但虚读仍然会出现/防止脏读、不可重复的读和虚读
//数据库连接池配置
private int minPoolSize; //连接池最小数目
private int maxPoolSize; //连接池最大数目
private long maxKeepTimeMs; //数据库连接最大保持毫秒时间,超出则重建连接
private long maxIdleTimeMs; //数据库连接最大空闲毫秒时间,超出则重建连接
//数据库连接检查配置
private boolean isChkConnOnTimer; //是否定时检查连接有效性
private boolean isChkConnOnGet; //是否在获取连接时检查连接有效性
private boolean isChkConnOnRelease; //是否在释放连接时检查连接有效性
//数据库连接耗尽策略配置
private int outOfConnWaitTimeMs; //数据库连接耗尽时,最大等待时长,单位毫秒,建议5000毫秒
private int outOfConnRetryCount; //数据库连接耗尽时,重试次数,建议重试1次
//数据库状态属性
private boolean isDbBreak; //数据库是否已断开
private ZConnectionTester tester; //数据库连接测试类
/**
* 默认参数构造函数,默认空闲时间=保持时间,最大100001次调用,定时检查连接有效性,获取和释放时检查有效性
*
* @param id 数据库服务编号
* @param driver 数据库驱动
* @param url 数据库URL
* @param user 数据库用户名
* @param pass 数据库密码
* @param minPoolSize 连接池最小数目
* @param maxPoolSize 连接池最大数目
* @param maxKeepTime 数据库连接最大保持时长,超出则重建连接,单位:秒
*/
public ZDataSource(String id, String driver, String url, String user, String pass, int minPoolSize, int maxPoolSize, int maxKeepTime)
{
this(id, driver, url, user, pass, -1, minPoolSize, maxPoolSize, maxKeepTime, maxKeepTime, true, false, false, 5, 1);
}
/**
* 全参数构造函数
*
* @param id 数据库服务编号
* @param driver 数据库驱动
* @param url 数据库URL
* @param user 数据库用户名
* @param pass 数据库密码
* @param level 数据库连接事务隔离级别
* @param minPoolSize 连接池最小数目
* @param maxPoolSize 连接池最大数目
* @param maxKeepTime 数据库连接最大保持时长,超出则重建连接,单位:秒
* @param maxIdleTime 数据库连接最大空闲时长,超出则重建连接,单位:秒
* @param isChkConnOnTimer 是否定时检查连接有效性
* @param isChkConnOnGet 是否在获取连接时检查连接有效性
* @param isChkConnOnRelease 是否在释放连接时检查连接有效性
* @param outOfConnWaitTime 数据库连接耗尽时,最大等待时长,单位秒
* @param outOfConnRetryCount 数据库连接耗尽时,重试次数,建议重试1次
*/
public ZDataSource(String id, String driver, String url, String user, String pass, int level, int minPoolSize, int maxPoolSize, int maxKeepTime, int maxIdleTime,
boolean isChkConnOnTimer, boolean isChkConnOnGet, boolean isChkConnOnRelease, int outOfConnWaitTime, int outOfConnRetryCount)
{
//配置
this.id = id != null?id:Randoms.lettersDigits(2);
this.connList = new LinkedList<>();
this.closedMap = new ConcurrentHashMap<>();
this.activeSize = new AtomicInteger(0);
//基础参数
this.driver = driver;
this.url = url;
this.user = user;
this.pass = pass;
this.level = level;
//连接池/处理参数
this.minPoolSize = minPoolSize;
this.maxPoolSize = maxPoolSize;
this.maxKeepTimeMs = maxKeepTime * 1000;
this.maxIdleTimeMs = maxIdleTime * 1000;
this.isChkConnOnTimer = isChkConnOnTimer;
this.isChkConnOnGet = isChkConnOnGet;
this.isChkConnOnRelease = isChkConnOnRelease;
this.outOfConnWaitTimeMs = outOfConnWaitTime * 1000;
this.outOfConnRetryCount = outOfConnRetryCount;
}
/** 数据库信息 */
public String toString()
{
return new StringBuilder("数据库[")
.append("id:").append(id).append(",")
.append("min:").append(minPoolSize).append(",")
.append("max:").append(maxPoolSize).append(",")
.append("cur:").append(getConnSize()).append(",")
.append("active:").append(activeSize.get()).append(",")
.append("mKeep:").append(maxKeepTimeMs/1000).append(",")
.append("mIdle:").append(maxIdleTimeMs/1000).append(",")
.append("isTimer:").append(isChkConnOnTimer).append(",")
.append("isGet:").append(isChkConnOnGet).append(",")
.append("isRelease:").append(isChkConnOnRelease).append(",")
.append("outWait:").append(outOfConnWaitTimeMs/1000).append(",")
.append("outRetry:").append(outOfConnRetryCount).append("]")
.toString();
}
/**********************************************************************************/
//数据库服务线程开启&关闭&运行
/**********************************************************************************/
@Override /** 线程名 */
protected String getThreadName()
{
return "ZDataSource-"+id;
}
@Override /** 线程开启前 */
protected boolean openBefore()
{
if (!createConnectionTester())
{//创建连接测试者
return false;
}
//2.先删除已有的连接
deleteConnections();
//3.创建新的连接
return createConnections("初始化");
}
@Override /** 线程关闭后 */
protected void closeAfter()
{
deleteConnections();
tester.shutdown();
log.info("数据库[%s]监视线程退出", id);
}
@Override /** 线程首次运行 */
protected void first()
{
Threads.sleepIgnoreException(CHK_TIME);
}
@Override /** 线程持续运行 */
protected void loop()
{
//1.打印数据库日记信息
log.info(toString());
//2.关闭等待关闭的连接
for (Iterator<ZConnection> it=closedMap.keySet().iterator();it.hasNext();)
{
ZConnection conn = it.next();
conn.shutdown();
it.remove();
log.info("监视关闭数据库等待关闭的连接[%s][%s]成功", id, conn.getId());
}
//3.检查数据库是否断开
isDbBreak = tester.isDbBreak();
if (isDbBreak)
{//如果数据库断开,则关闭所有连接
deleteConnections();
return;
}
//4.检查所有连接,关闭需要关闭的连接(已关闭、超出时长和连接不可用)
List<ZConnection> list = Lists.copy(connList, true);
for (ZConnection conn : list)
{
if (conn.isActive())
{//活动中的连接不检查
continue;
}
if (conn.isClosed() || conn.isKeepOrIdleTimeout() || (isChkConnOnTimer && !conn.isConnectionAvailable()))
{//已关闭、已超出时长或数目、和要求定时检查连接连接不可用时,三种情况下销毁连接并从队列移除
synchronized (connList)
{
connList.remove(conn);
}
String connId = conn.getId();
conn.shutdown();
conn = null;
log.info("监视关闭数据库连接[%s][%s]成功", id, connId);
}
}
//5.补足最小连接数
createConnections("补足");
//6.等待60秒进入下次循环
Threads.sleepIgnoreException(CHK_TIME);
}
/**创建测试连接*/
private boolean createConnectionTester()
{
if (tester != null)
{//如果已有测试器,先关闭
tester.shutdown();
tester = null;
}
try
{
if (!JNDI.equalsIgnoreCase(driver))
{//判断驱动类是否能加载到
Class<?> cls = Classes.forName(driver);
if (cls == null)
{
log.error("数据库[%s]初始化失败,未找到驱动类[%s]", id, driver);
return false;
}
}
tester = new ZConnectionTester(this);
if (tester.isDbBreak())
{
log.error("数据库[%s]初始化失败,连接断开", id);
return false;
}
}
catch (Exception e)
{
log.error("数据库[%s]初始化失败,%s", id, e.getMessage());
return false;
}
return true;
}
/** 从池里获取一个连接,当连接耗尽时重复等待多少次 */
public Connection getConnection() throws SQLException
{
return getConnection(0);
}
/** 从池里获取一个连接 */
private Connection getConnection(int times) throws SQLException
{
//第一步,先看是否能从连接池找到或新建
synchronized (connList)
{
//1.1循环寻找一个有效的空闲连接,并对无效连接进行处理
for (Iterator<ZConnection> it=connList.iterator();it.hasNext();)
{
ZConnection conn = it.next();
if (conn.isActive())
{//1.1.1 先判断是否活动中,活动中继续找下一个
continue;
}
if (conn.isClosed() || conn.isKeepOrIdleTimeout() || (isChkConnOnGet && !conn.isConnectionAvailable()))
{//1.1.2 已关闭、已超出时长或数目、和要求获取时检查连接连接不可用时,三种情况下销毁连接并从队列移除
closedMap.put(conn, null);
it.remove();
continue;
}
//1.1.3 找到一个空闲并可用的连接即返回
return conn.active();
}
//1.2如果没有空闲连接则检查是否达到最达连接数,没到最大值新建一个并返回
if (connList.size() < maxPoolSize)
{
ZConnection conn = newProxyConnection("获取");
if (conn != null)
{
connList.add(conn);
return conn.active();
}
}
}
//第二步,如果没有空闲且连接达到最大数,则线程进入等待状态5秒,等待别的线程处理完释放连接
lock.lock(outOfConnWaitTimeMs);
//第三步,别的线程有释放或时间到达,检查是否有效线程,有则返回
synchronized (connList)
{
for (ZConnection conn : connList)
{
if (conn.isActive())
continue;
return conn.active();
}
}
//第四步,最后还是没有获取到连接则抛出异常,防止线程锁死在等待数据库连接上,导致发现不了问题
String fatal = "数据库连接["+id+"]连接耗尽,[max:"+getMaxPoolSize()+",cur:"+getConnSize()+",active:"+activeSize.get()+"]";
if (times < outOfConnRetryCount)
{
log.fatal("%s[第%s]", fatal, times+1);
return getConnection(times + 1);
}
else
{
log.fatal("%s[第%s][全部失败抛出异常到业务层]", fatal, times+1);
throw new SQLException("数据库连接耗尽,请与管理员联系检查数据库是否正常工作和连接池配置是否足够!");
}
}
/** 释放一个连接到池内 */
public void releaseConnection(ZConnection conn)
{
if (conn == null)
return;
if (conn.isClosed() || conn.isKeepOrIdleTimeout() || (isChkConnOnRelease && !conn.isConnectionAvailable()))
{//已关闭、已超出时长或数目、和要求释放时检查连接连接不可用时,三种情况下销毁连接并从队列移除
String connId = conn.getId();
conn.shutdown();
synchronized (connList)
{
connList.remove(conn);
}
conn = null;
log.info("释放关闭数据库连接[%s][%s]成功", id, connId);
return;
}
//连接没问题即设置为空闲并通知
conn.idle();
lock.unlock();
}
/** 创建所有连接 */
private boolean createConnections(String type)
{
int num = minPoolSize - connList.size();
for(int i=0;i<num;i++)
{
ZConnection conn = newProxyConnection(type);
if (conn == null)
return false;
synchronized (connList)
{
connList.add(conn);
}
}
if (num > 0)
{//有创建连接的解锁通知
lock.unlock();
}
return true;
}
/** 删除所有连接 */
private void deleteConnections()
{
synchronized (connList)
{
for (Iterator<ZConnection> it=connList.iterator();it.hasNext();)
{
ZConnection conn = it.next();
String connId = conn.getId();
conn.shutdown();
it.remove();
conn = null;
log.info("销毁关闭数据库连接[%s][%s]成功", id, connId);
}
}
}
/** 获取一个代理的连接 */
ZConnection newProxyConnection(String type)
{
try
{
Connection conn = null;
if (JNDI.equalsIgnoreCase(driver))
{//JNDI
DataSource dataSource = (DataSource)new InitialContext().lookup(url);
if (dataSource == null)
return null;
dataSource.setLoginTimeout(10);
conn = dataSource.getConnection();
}
else
{//JDBC
DriverManager.setLoginTimeout(10);
conn = DriverManager.getConnection(url, user, pass);
}
if (conn == null)
{
log.error("创建数据库连接[%s]失败,[%s]", id, type);
return null;
}
ZConnection connection = new ZConnection(this, conn);
if (level == 0 || level == 1 || level == 2 || level == 4 || level == 8)
{//事务隔离等级,分5级,分别是0/1/2/4/8,越大越严格,其中0表示不支持事务,默认取决于数据库
connection.setTransactionIsolation(level);
}
log.info("创建数据库连接[%s][%s]成功,[%s]", id, connection.getId(), type);
return connection;
}
catch (SQLException e)
{
log.error("创建数据库连接[%s]时,发生异常:[%s]", id, e.getMessage());
return null;
}
catch(Exception e)
{
log.error("创建数据库连接[%s]时,发生异常:[%s]", id, e.getMessage());
return null;
}
}
void active()
{
activeSize.getAndIncrement();
}
void idle()
{
activeSize.getAndDecrement();
}
/***********************************/
//DataSource 参数信息,密码不支持获取
/***********************************/
/** 获取当前连接数 */
public int getConnSize()
{
return connList.size();
}
/** 获取当前连接活跃数 */
public int getConnActiveSize()
{
return activeSize.get();
}
/** 判断数据库是否断开 */
public boolean isDbBreak()
{
return tester.isDbBreak();
}
/** 下一个连接序号 */
public String nextSequence()
{
return sequence.nextString();
}
public String getId()
{
return id;
}
public String getDriver()
{
return driver;
}
public String getUrl()
{
return url;
}
public String getUser()
{
return user;
}
public int getMinPoolSize()
{
return minPoolSize;
}
public int getMaxPoolSize()
{
return maxPoolSize;
}
public long getMaxKeepTimeMs()
{
return maxKeepTimeMs;
}
public long getMaxIdleTimeMs()
{
return maxIdleTimeMs;
}
public boolean isChkConnOnTimer()
{
return isChkConnOnTimer;
}
public boolean isChkConnOnGet()
{
return isChkConnOnGet;
}
public boolean isChkConnOnRelease()
{
return isChkConnOnRelease;
}
/***********************************/
//DataSource 支持动态修改的参数
/***********************************/
public void setMinPoolSize(int minPoolSize)
{
this.minPoolSize = minPoolSize;
}
public void setMaxPoolSize(int maxPoolSize)
{
this.maxPoolSize = maxPoolSize;
}
public void setMaxKeepTime(long maxKeepTime)
{
this.maxKeepTimeMs = maxKeepTime * 1000;
}
public void setMaxIdleTime(long maxIdleTime)
{
this.maxIdleTimeMs = maxIdleTime * 1000;
}
public void setChkConnOnTimer(boolean isChkConnOnTimer)
{
this.isChkConnOnTimer = isChkConnOnTimer;
}
public void setChkConnOnGet(boolean isChkConnOnGet)
{
this.isChkConnOnGet = isChkConnOnGet;
}
public void setChkConnOnRelease(boolean isChkConnOnRelease)
{
this.isChkConnOnRelease = isChkConnOnRelease;
}
/***********************************/
//DataSource要求实现的方法,但没用上
/***********************************/
public Connection getConnection(String username, String password) throws SQLException
{
throw new SQLException("不支持传入用户名和密码获取连接");
}
public PrintWriter getLogWriter() throws SQLException
{
return DriverManager.getLogWriter();
}
public int getLoginTimeout() throws SQLException
{
return DriverManager.getLoginTimeout();
}
public void setLogWriter(PrintWriter out) throws SQLException
{
DriverManager.setLogWriter(out);
}
public void setLoginTimeout(int seconds) throws SQLException
{
DriverManager.setLoginTimeout(seconds);
}
/***********************************/
//JDK1.6增加
/***********************************/
public boolean isWrapperFor(Class<?> iface) throws SQLException
{
return false;
}
public <T> T unwrap(Class<T> iface) throws SQLException
{
return null;
}
/***********************************/
//JDK1.7增加
/***********************************/
public Logger getParentLogger() throws SQLFeatureNotSupportedException
{
return null;
}
}
@@ -0,0 +1,315 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.zhiqim.kernel.extend.LinkedMapSO;
import org.zhiqim.kernel.extend.TreeMapSO;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.orm.ORMConstants;
import org.zhiqim.orm.dbo.Dbo;
import org.zhiqim.orm.dbo.DboField;
/**
* 数据库结果集工具类
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ZResultSet implements ORMConstants
{
/*******************************************************************************************/
//解释结果集
/*******************************************************************************************/
/**
* 解释结果集到哈唏表中
*
* @param rst 结果集
* @param resultClass 结果类
* @return 结果表
* @throws SQLException SQL异常
*/
public static List<?> parseToBase(ResultSet rst, Class<?> resultClass) throws SQLException
{
if (!rst.next())
{//先判断是否有数据
return new ArrayList<>();
}
ArrayList<Object> resultList = new ArrayList<>();
ResultSetMetaData rstMeta = rst.getMetaData();
int columnCount = rstMeta.getColumnCount();
do
{
if (columnCount == 1)
{//只有一列时,取该值
resultList.add(getValue(resultClass, rst, 1));
}
else
{//多列时,取数据
Object[] result = new Object[columnCount];
for (int i=1;i<=columnCount;i++)
{// 从1开始
result[i-1] = getValue(resultClass, rst, i);
}
resultList.add(result);
}
}
while (rst.next());
resultList.trimToSize();
return resultList;
}
/**
* 解释结果集到哈唏表中
*
* @param rst 结果集
* @param resultClass 结果类
* @return 结果表
* @throws SQLException SQL异常
*/
public static List<?> parseToMap(ResultSet rst, Class<?> resultClass) throws SQLException
{
if (!rst.next())
{//先判断是否有数据
return new ArrayList<>();
}
ArrayList<Object> resultList = new ArrayList<>();
ResultSetMetaData rstMeta = rst.getMetaData();
int columnCount = rstMeta.getColumnCount();
do
{
LinkedMapSO result = new LinkedMapSO(columnCount);
for (int i = 1; i <= columnCount; i++)
{// 从1开始
int type = rstMeta.getColumnType(i);
String columnName = rstMeta.getColumnName(i);
switch (type)
{
case Types.CLOB:
Clob clob = rst.getClob(i);
if (clob != null)
result.put(columnName, clob.getSubString((long) 1, (int) clob.length()));
else
result.put(columnName, null);
break;
default:
Object obj = rst.getObject(i);
result.put(columnName, obj);
break;
}
}
if (resultClass == Map.class || resultClass == HashMap.class || resultClass == LinkedHashMap.class)
resultList.add(result.instance());
else if (resultClass == TreeMap.class)
resultList.add(new TreeMap<String, Object>(result.instance()));
else if (resultClass == TreeMapSO.class)
resultList.add(new TreeMapSO(result));
else
resultList.add(result);
}
while (rst.next());
resultList.trimToSize();
return resultList;
}
/**
* 解释结果集到DBO中
*
* @param rst 结果集
* @param resultDbo 结果DBO
* @return 结果表
* @throws SQLException SQL异常
*/
public static List<?> parseToDbo(ResultSet rst, Dbo resultDbo) throws Exception
{
if (!rst.next())
{//先判断是否有数据
return new ArrayList<>();
}
ArrayList<Object> resultList = new ArrayList<>();
ResultSetMetaData rstMeta = rst.getMetaData();
int columnCount = rstMeta.getColumnCount();
do
{
// 生成DBO
Object result = Classes.newInstance(resultDbo.getName());
for (int i = 1; i <= columnCount; i++)
{// 从1开始
String columnName = rstMeta.getColumnName(i);
int columnType = rstMeta.getColumnType(i);
parseToDboField(rst, result, resultDbo, columnName, columnType, i);
}
resultList.add(result);
}
while (rst.next());
resultList.trimToSize();
return resultList;
}
/**
* 解释结果集到DBO中,使用反射调用结果集方法设置数据
*
* @param rst 结果集
* @param result 结果对象
* @param dbo 数据库对象
* @param columnName 列名
* @param i 索引
* @throws Exception 可能的异常
*/
private static void parseToDboField(ResultSet rst, Object result, Dbo dbo, String columnName, int columnType, int i) throws Exception
{
//查找属性,先找列对应,后找属性对应
DboField field = dbo.getField(columnName);
if (field == null)
return;
Class<?> clazz = result.getClass();
String method = field.getSetMethod();
int type = field.getType();
Object obj = null;
Method m = null;
switch (type)
{
//基本类型
case Z_ORM_BOOLEAN_INT: obj = rst.getBoolean(i);m = clazz.getMethod(method, boolean.class);break;
case Z_ORM_BYTE_INT: obj = rst.getInt(i);m = clazz.getMethod(method, int.class);break;
case Z_ORM_SHORT_INT: obj = rst.getInt(i);m = clazz.getMethod(method, int.class);break;
case Z_ORM_INT_INT: obj = rst.getInt(i);m = clazz.getMethod(method, int.class);break;
case Z_ORM_LONG_INT: obj = rst.getLong(i);m = clazz.getMethod(method, long.class);break;
//小数和时间
case Z_ORM_DECIMAL_INT: obj = rst.getDouble(i);m = clazz.getMethod(method, double.class);break;
case Z_ORM_DATETIME_INT: obj = rst.getTimestamp(i);break;
//字符串
case Z_ORM_STRING_INT:
{
if (Types.CLOB == columnType)
{//CLOB
Clob clob = rst.getClob(i);
if (clob != null)
obj = clob.getSubString(0, (int)clob.length());
}
else
{//其他类型直接读取字符串
obj = rst.getString(i);
}
break;
}
//二进制字节数组
case Z_ORM_BINARY_INT:
{
if (Types.BLOB == columnType)
{
Blob blob = rst.getBlob(i);
if (blob != null)
obj = blob.getBytes(1, (int)blob.length());
}
else
{//其他类型直接读byte[]
obj = rst.getBytes(i);
}
break;
}
default:
obj = rst.getObject(i);
break;
}
if (obj != null)
{
if (m == null)
m = clazz.getMethod(method, obj.getClass());
m.invoke(result, obj);
}
}
/*******************************************************************************************/
//从结果集或结果中读取对象
/*******************************************************************************************/
/**
* 从结果集中读取对象
*
* @param resultClass 结果类
* @param rst 结果集
* @param index 索引值
* @return 索引位置的对象
* @throws SQLException SQL异常
*/
public static Object getValue(Class<?> resultClass, ResultSet rst, int index) throws SQLException
{
if (resultClass == boolean.class || resultClass == Boolean.class)
return rst.getBoolean(index);
else if (resultClass == byte.class || resultClass == Byte.class || resultClass == short.class || resultClass == Short.class || resultClass == int.class || resultClass == Integer.class)
return rst.getInt(index);
else if (resultClass == long.class || resultClass == Long.class)
return rst.getLong(index);
//日期类型
else if (resultClass == Timestamp.class)
return rst.getTimestamp(index);
else if (resultClass == Date.class)
return rst.getDate(index);
else if (resultClass == Time.class)
return rst.getTime(index);
//字符串
else if (resultClass == String.class)
return rst.getString(index);
//二进制
else if (resultClass == byte[].class)
return rst.getBytes(index);
else
{//其他类型
return rst.getObject(index);
}
}
}
@@ -0,0 +1,316 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.datasource;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.Writer;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import oracle.sql.BLOB;
import oracle.sql.CLOB;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Hexs;
import org.zhiqim.kernel.util.Replaces;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.orm.ORMServer;
/**
* 数据库处理工具类
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class ZStatement
{
/**
* 预处理语句设置参数,对SQL语句填充后返回SQL语句,用于打印日志
*
* @param server ORM服务
* @param pstmt 预处理语句
* @param index 索引
* @param value 设置的值
* @param str SQL语句
* @return 填充后的SQL语句
* @throws SQLException SQL异常
* @throws IOException IO异常
*/
public static String setParameter(ORMServer server, PreparedStatement pstmt, int index, Object value, String str) throws SQLException, IOException
{
if (value == null)
{
pstmt.setNull(index, Types.CHAR);//注意这里用Types.CHAR,可以保证string,int,long等值正确,其他的未测试
str = str.replaceFirst("\\?", "null");
}
//基本类型
else if (value instanceof Boolean)
{
pstmt.setBoolean(index, ((Boolean)value).booleanValue());
str = str.replaceFirst("\\?", String.valueOf(value));
}
else if (value instanceof Byte)
{
pstmt.setByte(index, ((Byte)value).byteValue());
str = str.replaceFirst("\\?", String.valueOf(value));
}
else if (value instanceof Short)
{
pstmt.setShort(index, ((Short)value).shortValue());
str = str.replaceFirst("\\?", String.valueOf(value));
}
else if (value instanceof Integer)
{
pstmt.setInt(index, ((Integer)value).intValue());
str = str.replaceFirst("\\?", String.valueOf(value));
}
else if (value instanceof Long)
{
pstmt.setLong(index, ((Long)value).longValue());
str = str.replaceFirst("\\?", String.valueOf(value));
}
//日期格式
else if (value instanceof Timestamp)
{
Timestamp time = (Timestamp)value;
pstmt.setTimestamp(index, time);
str = str.replaceFirst("\\?", "'" + Sqls.toDateTimeString(time) + "'");
}
else if (value instanceof Date)
{
Date date = (Date)value;
pstmt.setDate(index, date);
str = str.replaceFirst("\\?", "'" + Sqls.toDateString(date) + "'");
}
else if (value instanceof Time)
{
Time time = (Time)value;
pstmt.setTime(index, time);
str = str.replaceFirst("\\?", "'" + Sqls.toTimeString(time) + "'");
}
//字符串
else if (value instanceof String)
{
String v = (String)value;
if (v.length() <= 2000)
pstmt.setString(index, v);
else if (server.isOracle())
{//oracle
CLOB clob = CLOB.createTemporary(pstmt.getConnection(), false, CLOB.DURATION_SESSION);
clob.open(CLOB.MODE_READWRITE);
Writer writer = clob.getCharacterOutputStream();
writer.write(v);
writer.close();
clob.close();
pstmt.setClob(index, clob);
}
else
{//其他
StringReader reader = new StringReader(v);
pstmt.setCharacterStream(index, reader, v.length());
}
//SQL转义
v = v.replaceAll("'", "''");
if (v.indexOf("?") != -1)
{//转义
v = v.replaceAll("\\?", "-%6-%-3%-");
}
v = Replaces.toReplaceEscape(v);
str = str.replaceFirst("\\?", "'"+ v +"'");
}
//二进制
else if (value instanceof byte[])
{
byte[] v = (byte[])value;
if (!server.isOracle())
pstmt.setBytes(index, v);
else
{
BLOB blob = BLOB.createTemporary(pstmt.getConnection(), false, BLOB.DURATION_SESSION);
blob.open(BLOB.MODE_READWRITE);
OutputStream os = blob.getBinaryOutputStream();
os.write(v);
os.close();
blob.close();
pstmt.setBlob(index, blob);
}
str = str.replaceFirst("\\?", "'"+ Hexs.toHexString(v) +"'");
}
else
{//其他类型
pstmt.setObject(index, value);
str = str.replaceFirst("\\?", String.valueOf(value));
}
return str;
}
/**
* 预处理语句设置参数
*
* @param server ORM服务
* @param pstmt 预处理语句
* @param index 索引
* @param value 设置的值
* @throws SQLException SQL异常
* @throws IOException IO异常
*/
public static void setParameter(ORMServer server, PreparedStatement pstmt, int index, Object value) throws SQLException, IOException
{
if (value == null)
pstmt.setNull(index, Types.CHAR);//注意这里用Types.CHAR,可以保证string,int,long等值正确,其他的未测试
//基本类型
else if (value instanceof Boolean)
pstmt.setBoolean(index, ((Boolean)value).booleanValue());
else if (value instanceof Byte)
pstmt.setByte(index, ((Byte)value).byteValue());
else if (value instanceof Short)
pstmt.setShort(index, ((Short)value).shortValue());
else if (value instanceof Integer)
pstmt.setInt(index, ((Integer)value).intValue());
else if (value instanceof Long)
pstmt.setLong(index, ((Long)value).longValue());
//日期类型
else if (value instanceof Timestamp)
pstmt.setTimestamp(index, (Timestamp)value);
else if (value instanceof Date)
pstmt.setDate(index, (Date)value);
else if (value instanceof Time)
pstmt.setTime(index, (Time)value);
//字符串
else if (value instanceof String)
{
String v = (String)value;
if (v.length() <= 2000)
pstmt.setString(index, (String)value);
else if (server.isOracle())
{//oracle clob
CLOB clob = CLOB.createTemporary(pstmt.getConnection(), false, CLOB.DURATION_SESSION);
clob.open(CLOB.MODE_READWRITE);
Writer writer = clob.getCharacterOutputStream();
writer.write(v);
writer.close();
clob.close();
pstmt.setClob(index, clob);
}
else
{//其他
StringReader reader = new StringReader(v);
pstmt.setCharacterStream(index, reader, v.length());
}
}
//二进制
else if (value instanceof byte[])
{
byte[] v = (byte[])value;
if (!server.isOracle())
pstmt.setBytes(index, v);
else
{//oracle blob
BLOB blob = BLOB.createTemporary(pstmt.getConnection(), false, BLOB.DURATION_SESSION);
blob.open(BLOB.MODE_READWRITE);
OutputStream os = blob.getBinaryOutputStream();
os.write(v);
os.close();
blob.close();
pstmt.setBlob(index, blob);
}
}
else
{//其他类型
pstmt.setObject(index, value);
}
}
/**
* 替换SQL中##参数值为?
*
* @param sql SQL语句
* @param paramKeyList 参数KEY列表
* @return 新的SQL语句
*/
public static String paramMapString(String sql, List<String> paramKeyList)
{
for (int i=0,start=0,end=sql.indexOf('#');end!=-1;i++,start=end,end=sql.indexOf('#', start+1))
{
if (i % 2 == 0)
continue;
String paramKey = sql.substring(start + 1, end);
paramKeyList.add(paramKey);
}
for (int i=0;i<paramKeyList.size();i++)
{
String paramKey = paramKeyList.get(i);
sql = sql.replaceAll("#"+paramKey+"#", "?");//把#paramKey#换成?
}
return sql;
}
/**
* 替换SQL中##参数值为结果值
*
* @param sql SQL语句
* @param paramMap 参数KEY列表
* @return 新的SQL语句
*/
public static String paramMapString(String sql, MapSO paramMap)
{
List<String> paramKeyList = new ArrayList<String>();
for (int i=0,start=0,end=sql.indexOf('#');end!=-1;i++,start=end,end=sql.indexOf('#', start+1))
{
if (i % 2 == 0)
continue;
String paramKey = sql.substring(start + 1, end);
paramKeyList.add(paramKey);
}
for (int i=0;i<paramKeyList.size();i++)
{
String paramKey = paramKeyList.get(i);
Object paramValue = paramMap.get(paramKey);
sql = sql.replaceAll("#"+paramKey+"#", "'"+paramValue+"'");//把#paramKey#换成'paramValue'
}
return sql;
}
}
@@ -0,0 +1,55 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
/**
* 批处理类型
*
* @version v1.0.0 @author zouzhigang 2019-3-29 新建与整理
*/
public enum BatchType
{
/*****************************************************************************/
//枚举类型定义
/*****************************************************************************/
/** 插入 */
INSERT,
/** 替换 */
REPLACE,
/** 插入或更新 */
INSERT_OR_UPDATE,
/** 更新 */
UPDATE,
/** 更新器 */
UPDATER,
/** 使用主键删除 */
DELETE_ID,
/** 使用查询器删除 */
DELETE_SELECTOR;
}
@@ -0,0 +1,314 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import org.zhiqim.kernel.extend.MapSS;
/**
* 批量处理封装
*
* @version v1.0.0 @author zouzhigang 2019-3-29 新建与整理
*/
public class Batcher
{
private BatchType type;
//插入
private Object insertData;
private MapSS insertReplaceMap;
//替换
private Object replaceData;
private MapSS replaceReplaceMap;
//插入或更新
private Object insertOrUpdateData;
private Updater insertOrUpdateUpdater;
//更新
private Object updateData;
private MapSS updateReplaceMap;
//更新器
private Class<?> updaterClass;
private Updater updaterUpdater;
//删除
private Class<?> deleteClass;
private MapSS deleteReplaceMap;
private Object[] deleteIds;
private Selector deleteSelector;
/*************************************************************************************/
//设置
/*************************************************************************************/
/**
* 增加数据,传入标准[表类]对象
*
* @param data 表对象
* @return 当前对象
*/
public Batcher insert(Object data)
{
this.insertData = data;
this.type = BatchType.INSERT;
return this;
}
/**
* 增加数据,支持表或字段中中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param data 表对象
* @param replaceMap 适配表
* @return 当前对象
*/
public Batcher insert(Object data, MapSS replaceMap)
{
this.insertData = data;
this.insertReplaceMap = replaceMap;
this.type = BatchType.INSERT;
return this;
}
/**
* 替换数据,传入标准[表类]对象和更新器(取fieldMap和replaceMap)当存在时指定修改的值
*
* @param data 表对象
* @param updater 更新器
* @return 当前对象
*/
public Batcher insertOrUpdate(Object data, Updater updater)
{
this.insertOrUpdateData = data;
this.insertOrUpdateUpdater = updater;
this.type = BatchType.INSERT_OR_UPDATE;
return this;
}
/**
* 替换数据,传入标准[表类]对象
*
* @param data 表对象
* @return 当前对象
*/
public Batcher replace(Object data)
{
this.replaceData = data;
this.type = BatchType.REPLACE;
return this;
}
/**
* 替换数据,支持表或字段中有多个替换字段,如LOG_TRACE_$MONTH$_$ID$
*
* @param data 表对象
* @param replaceMap 适配表
* @return 当前对象
*/
public Batcher replace(Object data, MapSS replaceMap)
{
this.replaceData = data;
this.replaceReplaceMap = replaceMap;
this.type = BatchType.REPLACE;
return this;
}
/**
* 更新数据,指定更新器需要更新的字段、条件和可替换表
*
* @param cls 表类
* @param updater 更新器
* @return 当前对象
*/
public Batcher update(Class<?> cls, Updater updater)
{
this.updaterClass = cls;
this.updaterUpdater = updater;
this.type = BatchType.UPDATE;
return this;
}
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新
*
* @param data 表对象
* @return 当前对象
*/
public Batcher update(Object data)
{
this.updateData = data;
this.type = BatchType.UPDATE;
return this;
}
/**
* 更新数据,指定对象,根据主键进行更新,主键值不更新,支持可替换表
*
* @param data 表对象
* @param replaceMap 适配表
* @return 当前对象
*/
public Batcher update(Object data, MapSS replaceMap)
{
this.updateData = data;
this.updateReplaceMap = replaceMap;
return this;
}
/**
* 删除数据,多个主键时使用
*
* @param cls 表类
* @param ids 关键属性为数组,多个主键
* @return 当前对象
*/
public Batcher delete(Class<?> cls, Object... ids)
{
this.deleteClass = cls;
this.deleteIds = ids;
this.type = BatchType.DELETE_ID;
return this;
}
/**
* 删除数据,多个主键时使用
*
* @param cls 表类
* @param replaceMap 替换表
* @param ids 关键属性为数组,多个主键
* @return 当前对象
*/
public Batcher delete(Class<?> cls, MapSS replaceMap, Object... ids)
{
this.deleteClass = cls;
this.deleteReplaceMap = replaceMap;
this.deleteIds = ids;
this.type = BatchType.DELETE_ID;
return this;
}
/**
* 删除数据, 根据条件
*
* @param cls 表类
* @param selector 对象选择器
* @return 当前对象
*/
public Batcher delete(Class<?> cls, Selector selector)
{
this.deleteClass = cls;
this.deleteSelector = selector == null?new Selector():selector;
this.type = BatchType.DELETE_SELECTOR;
return this;
}
/********************************************************************************************/
//获取
/********************************************************************************************/
public BatchType getType()
{
return type;
}
public Object getInsertData()
{
return insertData;
}
public MapSS getInsertReplaceMap()
{
return insertReplaceMap;
}
public Object getReplaceData()
{
return replaceData;
}
public MapSS getReplaceReplaceMap()
{
return replaceReplaceMap;
}
public Object getInsertOrUpdateData()
{
return insertOrUpdateData;
}
public Updater getInsertOrUpdateUpdater()
{
return insertOrUpdateUpdater;
}
public Object getUpdateData()
{
return updateData;
}
public MapSS getUpdateReplaceMap()
{
return updateReplaceMap;
}
public Class<?> getUpdaterClass()
{
return updaterClass;
}
public Updater getUpdaterUpdater()
{
return updaterUpdater;
}
public Class<?> getDeleteClass()
{
return deleteClass;
}
public MapSS getDeleteReplaceMap()
{
return deleteReplaceMap;
}
public Object[] getDeleteIds()
{
return deleteIds;
}
public Selector getDeleteSelector()
{
return deleteSelector;
}
}
@@ -0,0 +1,106 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import java.sql.CallableStatement;
import java.sql.SQLException;
import org.zhiqim.orm.ORMConstants;
import org.zhiqim.orm.datasource.ZCall;
/**
* 调用参数
*
* @version v1.4.1 @author zouzhigang 2018-7-23 新建与整理
*/
public final class CallParam implements ORMConstants
{
private CALL_TYPE type;
private Class<?> clazz;
private Object value;
private CallParam(CALL_TYPE type, Class<?> clazz)
{
this.type = type;
this.clazz = clazz;
}
private CallParam(CALL_TYPE type, Object value)
{
this.type = type;
this.value = value;
this.clazz = value.getClass();
}
public CALL_TYPE type()
{
return type;
}
public Object value()
{
return value;
}
/**********************************************************************************/
//三种生成参数对象
/**********************************************************************************/
public boolean isInWrite()
{
return this.type == CALL_TYPE.IN || this.type == CALL_TYPE.INOUT;
}
public boolean isOutRead()
{
return this.type == CALL_TYPE.OUT || this.type == CALL_TYPE.INOUT;
}
public int typeSQL()
{
return ZCall.getType(clazz);
}
public void value(CallableStatement cstmt, int index) throws SQLException
{
value = ZCall.getValue(clazz, cstmt, index);
}
/**********************************************************************************/
//三种生成参数对象
/**********************************************************************************/
public static CallParam in(Object value)
{
return new CallParam(CALL_TYPE.IN, value);
}
public static CallParam inout(Object value)
{
return new CallParam(CALL_TYPE.INOUT, value);
}
public static CallParam out(Class<?> clazz)
{
return new CallParam(CALL_TYPE.OUT, clazz);
}
}
@@ -0,0 +1,62 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import java.util.ArrayList;
import java.util.List;
/**
* 调用结果集
*
* @version v1.4.1 @author zouzhigang 2018-7-23 新建与整理
*/
public class CallResult
{
private Class<?> resultClass;
private List<?> resultList;
private CallResult(Class<?> resultClass)
{
this.resultClass = resultClass;
this.resultList = new ArrayList<>();
}
public Class<?> getResultClass()
{
return resultClass;
}
public List<?> getResultList()
{
return resultList;
}
public void setResultList(List<?> resultList)
{
this.resultList = resultList;
}
public static CallResult set(Class<?> resultClass)
{
return new CallResult(resultClass);
}
}
@@ -0,0 +1,131 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import java.sql.Timestamp;
import java.util.Map.Entry;
import org.zhiqim.kernel.extend.LinkedMapSS;
import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.orm.ORMConstants;
/**
* 对象比较器,用于排序,其中静态方法用于条件比较
*
* @version v1.0.0 @author zouzhigang 2017-8-23 新建与整理
*/
public class Comparator<T> implements java.util.Comparator<T>, ORMConstants
{
private Selector selector;
public Comparator(Selector selector)
{
this.selector = selector;
}
@Override
public int compare(T o1, T o2)
{
if (selector == null)
return 0;
LinkedMapSS orderbyMap = selector.getOrderby();
if (orderbyMap == null || orderbyMap.isEmpty())
return 0;
for (Entry<String, String> entry : orderbyMap.entrySet())
{
String field = entry.getKey();
String orderby = entry.getValue();
boolean isAsc = ASC.equals(orderby);
Object value1 = Classes.getFieldValue(o1, field);
Object value2 = Classes.getFieldValue(o2, field);
int val = compareValue(value1, value2);
if (val == 0)
continue;
return ((val < 0 && isAsc) || (val > 0 && !isAsc))?-1:1;
}
return 0;
}
/**
* 比较两个对象值,9种数据库类型转为Java的6种类型
*
* @param value1 值1
* @param value2 值2
* @return =0表示相等,>0表示前者大,<0表示后者大
*/
public static int compareValue(Object value1, Object value2)
{
Asserts.as(value1.getClass() == value2.getClass()?null:"比较的两个对象类型不一致");
switch (value1.getClass().getName().hashCode())
{
case BOOLEAN_OBJ_CODE:
{
boolean v1 = (Boolean)value1;
boolean v2 = (Boolean)value2;
int v11 = v1?1:0;
int v22 = v2?1:0;
return v11 - v22;
}
case INT_OBJ_CODE:
{
int v1 = (Integer)value1;
int v2 = (Integer)value2;
return v1 - v2;
}
case LONG_OBJ_CODE:
{
long v1 = (Long)value1;
long v2 = (Long)value2;
return v1 == v2?0:(v1 > v2)?1:-1;
}
case STRING_CODE:
{
String v1 = (String)value1;
String v2 = (String)value2;
return v1.compareTo(v2);
}
case DOUBLE_OBJ_CODE:
{
double v1 = (Double)value1;
double v2 = (Double)value2;
return v1 == v2?0:(v1 > v2)?1:-1;
}
case TIMESTAMP_CODE:
{
Timestamp v1 = (Timestamp)value1;
Timestamp v2 = (Timestamp)value2;
long v11 = v1.getTime();
long v22 = v2.getTime();
return v11 == v22?0:(v11 > v22)?1:-1;
}
default:
throw Asserts.exception("比较的对象类型不是ORM支持的类型");
}
}
}
@@ -0,0 +1,132 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import org.zhiqim.kernel.constants.SignConstants;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.orm.ORMException;
public abstract class Condition implements SignConstants
{
//比较条件
public static final String EQUAL = "="; //= 等于
public static final String EQUAL_NOT = "<>"; //<> 不等
public static final String LIKE = "like"; //like 两边都LIKE %value%,左边%value,右边value%
public static final String LIKE_NOT = "not like"; //not like 两边都LIKE %value%,左边%value,右边value%
public static final String THEN_G = ">"; //> 大于
public static final String THEN_GE = ">="; //>= 大于等于
public static final String THEN_L = "<"; //< 小于
public static final String THEN_LE = "<="; //<= 小于等于
//判断条件
public static final String IS_NULL = "is null"; //is null 为空
public static final String IS_NOT_NULL = "is not null"; //is not null 不为空
public static final String IN = "in"; //in 包含
public static final String IN_NOT = "not in"; //not in 不包含
//多重条件
public static final String OR = "or"; //or 或者
/*******************************************************************/
//子类必须实现的方法
/*******************************************************************/
/**
* 判断对象是否匹配
*
* @param obj 比较的对象
* @return =true表示匹配成功
*/
public abstract boolean match(Object obj);
/**
* 生成FDbo对应的条件SQL
*
* @param dbo _Dbo/_Table/_View三种的一种
* @param paramMap 由Selector/Updater指定的参数表
* @return SQL
* @throws ORMException 异常
*/
public abstract String toSql(Dbo dbo, MapSO paramMap) throws ORMException;
/*******************************************************************/
//内部断言方法和值转换方法
/*******************************************************************/
/**
* 验证字段在DBO中的有效性
*
* @param dbo 数据库对象
* @param field 字段
* @throws ORMException 异常
*/
protected void assertField(Dbo dbo, String field) throws ORMException
{
if (!dbo.hasField(field))
throw new ORMException("ZTable/ZView["+dbo.getName()+"]配置中未找到["+field+"]属性");
}
/**
* 断言是否是int[],long[],String[]三种
*
* @param value 值
* @throws ORMException 异常
*/
protected void assertArray(Object value) throws ORMException
{
if (!(value instanceof int[]) && !(value instanceof long[]) && !(value instanceof String[]))
throw new ORMException("ZTable/ZView[in/not in]仅支持int[],long[],String[]三种数组类型");
}
/**
* 值转换,针对对象转换成数据库支持的类型
*
* @param value 原值
* @return 转换后的值
*/
protected Object convertValue(Object value)
{
if (value instanceof Boolean)
{//boolean型转换成int型
boolean b = (Boolean)value;
return b?1:0;
}
return value;
}
/**
* 值转换,针对in/not in把对象转换成数组格式
*
* @param value 原值
* @return 转换后的值
*/
protected String convertArray(Object value)
{
if (value instanceof int[])
return "("+Arrays.toString((int[])value, ",") + ")";
else if (value instanceof long[])
return "("+Arrays.toString((long[])value, ",") + ")";
else
return "("+Arrays.toStringSql((String[])value, ",") + ")";
}
}
@@ -0,0 +1,700 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import org.zhiqim.kernel.extend.LinkedMapSS;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.kernel.util.Types;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORMConstants;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.condition._Equal;
import org.zhiqim.orm.dbo.condition._EqualNot;
import org.zhiqim.orm.dbo.condition._Expression;
import org.zhiqim.orm.dbo.condition._In;
import org.zhiqim.orm.dbo.condition._InNot;
import org.zhiqim.orm.dbo.condition._IsEmpty;
import org.zhiqim.orm.dbo.condition._IsNotEmpty;
import org.zhiqim.orm.dbo.condition._IsNotNull;
import org.zhiqim.orm.dbo.condition._IsNull;
import org.zhiqim.orm.dbo.condition._Like;
import org.zhiqim.orm.dbo.condition._LikeL;
import org.zhiqim.orm.dbo.condition._LikeNot;
import org.zhiqim.orm.dbo.condition._LikeNotL;
import org.zhiqim.orm.dbo.condition._LikeNotR;
import org.zhiqim.orm.dbo.condition._LikeR;
import org.zhiqim.orm.dbo.condition._Or;
import org.zhiqim.orm.dbo.condition._ThenG;
import org.zhiqim.orm.dbo.condition._ThenGE;
import org.zhiqim.orm.dbo.condition._ThenL;
import org.zhiqim.orm.dbo.condition._ThenLE;
/**
* 条件管理器,管理条件和可替换表
* 1. @see Selector 查询器
* 2. @see Updater 更新器
*
* @version v1.0.0 @author zouzhigang 2016-6-27 新建与整理
*/
abstract class Conditioner<C extends Conditioner<?>> implements Serializable, ORMConstants
{
private static final long serialVersionUID = 1L;
protected List<Condition> conditionList = null;
protected LinkedMapSS replaceMap = new LinkedMapSS();
/** 返回对应的适配信息 */
public LinkedMapSS getReplaceMap()
{
return replaceMap;
}
public List<Condition> getConditionList()
{
return conditionList;
}
public boolean hasCondition()
{
return conditionList != null && !conditionList.isEmpty();
}
/******************************************************/
//条件列表管理
/******************************************************/
/** 增加[可能][相等]条件 */
public C addMaybe(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _Equal(field, value));
return self();
}
/** 增加[强制][相等]条件 */
public C addMust(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _Equal(field, value));
return self();
}
/** 增加[可能][不等]条件 */
public C addMaybeNotEqual(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _EqualNot(field, value));
return self();
}
/** 增加[强制][不等]条件 */
public C addMustNotEqual(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _EqualNot(field, value));
return self();
}
/** 增加[可能][LIKE]条件 */
public C addMaybeLike(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _Like(field, String.valueOf(value)));
return self();
}
/** 增加[强制][LIKE]条件 */
public C addMustLike(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _Like(field, String.valueOf(value)));
return self();
}
/** 增加[可能][LIKE_LEFT]查询条件 */
public C addMaybeLikeLeft(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _LikeL(field, String.valueOf(value)));
return self();
}
/** 增加[强制][LIKE_LEFT]条件 */
public C addMustLikeLeft(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _LikeL(field, String.valueOf(value)));
return self();
}
/** 增加[可能][LIKE_RIGHT]查询条件 */
public C addMaybeLikeRight(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _LikeR(field, String.valueOf(value)));
return self();
}
/** 增加[强制][LIKE_RIGHT]查询条件 */
public C addMustLikeRight(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _LikeR(field, String.valueOf(value)));
return self();
}
/** 增加[可能][NOT LIKE]条件 */
public C addMaybeNotLike(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _LikeNot(field, String.valueOf(value)));
return self();
}
/** 增加[强制][NOT LIKE]条件 */
public C addMustNotLike(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _LikeNot(field, String.valueOf(value)));
return self();
}
/** 增加[可能][NOT LIKE_LEFT]查询条件 */
public C addMaybeNotLikeLeft(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _LikeNotL(field, String.valueOf(value)));
return self();
}
/** 增加[强制][NOT LIKE_LEFT]条件 */
public C addMustNotLikeLeft(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _LikeNotL(field, String.valueOf(value)));
return self();
}
/** 增加[可能][NOT LIKE_RIGHT]查询条件 */
public C addMaybeNotLikeRight(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _LikeNotR(field, String.valueOf(value)));
return self();
}
/** 增加[强制][NOT LIKE_RIGHT]查询条件 */
public C addMustNotLikeRight(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _LikeNotR(field, String.valueOf(value)));
return self();
}
/** 增加[可能][大于]查询条件 */
public C addMaybeThenG(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _ThenG(field, value));
return self();
}
/** 增加[强制][大于]查询条件 */
public C addMustThenG(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _ThenG(field, value));
return self();
}
/** 增加[可能][大于等于]查询条件 */
public C addMaybeThenGE(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _ThenGE(field, value));
return self();
}
/** 增加[强制][大于等于]查询条件 */
public C addMustThenGE(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _ThenGE(field, value));
return self();
}
/** 增加[可能][小于]查询条件 */
public C addMaybeThenL(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _ThenL(field, value));
return self();
}
/** 增加[强制][小于]查询条件 */
public C addMustThenL(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _ThenL(field, value));
return self();
}
/** 增加[可能][小于等于]查询条件 */
public C addMaybeThenLE(String field, Object value)
{
if (!chkMaybeFieldValue(field, value))
return self();
addCondition(new _ThenLE(field, value));
return self();
}
/** 增加[强制][小于等于]查询条件 */
public C addMustThenLE(String field, Object value)
{
chkMustFieldValue(field, value);
addCondition(new _ThenLE(field, value));
return self();
}
/** 增加[可能][is null]查询条件 */
public C addMaybeIsNull(String field)
{
if (!chkMaybeFieldValue(field))
return self();
addCondition(new _IsNull(field));
return self();
}
/** 增加[强制][is null]查询条件 */
public C addMustIsNull(String field)
{
chkMustFieldValue(field);
addCondition(new _IsNull(field));
return self();
}
/** 增加[可能][is not null]查询条件 */
public C addMaybeIsNotNull(String field)
{
if (!chkMaybeFieldValue(field))
return self();
addCondition(new _IsNotNull(field));
return self();
}
/** 增加[强制][is not null]查询条件 */
public C addMustIsNotNull(String field)
{
chkMustFieldValue(field);
addCondition(new _IsNotNull(field));
return self();
}
/** 增加[可能][is null or = '']查询条件 */
public C addMaybeIsEmpty(String field)
{
if (!chkMaybeFieldValue(field))
return self();
addCondition(new _IsEmpty(field));
return self();
}
/** 增加[强制][is null or = '']查询条件 */
public C addMustIsEmpty(String field)
{
chkMustFieldValue(field);
addCondition(new _IsEmpty(field));
return self();
}
/** 增加[可能][is not null and <> '']查询条件 */
public C addMaybeIsNotEmpty(String field)
{
if (!chkMaybeFieldValue(field))
return self();
addCondition(new _IsNotEmpty(field));
return self();
}
/** 增加[强制][is not null and <> '']查询条件 */
public C addMustIsNotEmpty(String field)
{
chkMustFieldValue(field);
addCondition(new _IsNotEmpty(field));
return self();
}
/** 增加[可能][in][String]查询条件 */
public C addMaybeIn(String field, String ... values)
{
if (!chkMaybeFieldValue(field, values))
return self();
addCondition(new _In(field, values));
return self();
}
/** 增加[强制][in][String]查询条件 */
public C addMustIn(String field, String ... values)
{
chkMustFieldValue(field, values);
addCondition(new _In(field, values));
return self();
}
/** 增加[可能][in][int]查询条件 */
public C addMaybeIn(String field, int ... values)
{
if (!chkMaybeFieldValue(field, values))
return self();
addCondition(new _In(field, values));
return self();
}
/** 增加[强制][in][int]查询条件 */
public C addMustIn(String field, int ... values)
{
chkMustFieldValue(field, values);
addCondition(new _In(field, values));
return self();
}
/** 增加[可能][in][long]查询条件 */
public C addMaybeInLong(String field, long ... values)
{
if (!chkMaybeFieldValue(field, values))
return self();
addCondition(new _In(field, values));
return self();
}
/** 增加[强制][in][long]查询条件 */
public C addMustInLong(String field, long ... values)
{
chkMustFieldValue(field, values);
addCondition(new _In(field, values));
return self();
}
/** 增加[可能][not in][String]查询条件 */
public C addMaybeNotIn(String field, String ... values)
{
if (!chkMaybeFieldValue(field, values))
return self();
addCondition(new _InNot(field, values));
return self();
}
/** 增加[强制][not in][String]查询条件 */
public C addMustNotIn(String field, String ... values)
{
chkMustFieldValue(field, values);
addCondition(new _InNot(field, values));
return self();
}
/** 增加[可能][not in][int]查询条件 */
public C addMaybeNotIn(String field, int ... values)
{
if (!chkMaybeFieldValue(field, values))
return self();
addCondition(new _InNot(field, values));
return self();
}
/** 增加[强制][not in][int]查询条件 */
public C addMustNotIn(String field, int ... values)
{
chkMustFieldValue(field, values);
addCondition(new _InNot(field, values));
return self();
}
/** 增加[可能][not in][long]查询条件 */
public C addMaybeNotInLong(String field, long ... values)
{
if (!chkMaybeFieldValue(field, values))
return self();
addCondition(new _InNot(field, values));
return self();
}
/** 增加[强制][not in][long]查询条件 */
public C addMustNotInLong(String field, long ... values)
{
chkMustFieldValue(field, values);
addCondition(new _InNot(field, values));
return self();
}
/*****************************************************************/
//表达式管理结束
/*****************************************************************/
/** 增加相等表达式 */
public C addExpression(String field, String expression)
{
return addExpression(field, expression, Condition.EQUAL);
}
/** 增加不等表达式 */
public C addExpressionNotEqual(String field, String expression)
{
return addExpression(field, expression, Condition.EQUAL_NOT);
}
/** 增加大于表达式 */
public C addExpressionThenG(String field, String expression)
{
return addExpression(field, expression, Condition.THEN_G);
}
/** 增加大于等于表达式 */
public C addExpressionThenGE(String field, String expression)
{
return addExpression(field, expression, Condition.THEN_GE);
}
/** 增加小于表达式 */
public C addExpressionThenL(String field, String expression)
{
return addExpression(field, expression, Condition.THEN_L);
}
/** 增加小于等于表达式 */
public C addExpressionThenLE(String field, String expression)
{
return addExpression(field, expression, Condition.THEN_LE);
}
/** 增加表达式 */
private C addExpression(String field, String expression, String condition)
{
Asserts.notEmptyBlank(field, _FIELD_);
Asserts.notEmptyBlank(expression, _VALUE_);
addCondition(new _Expression(field, expression, condition));
return self();
}
/*****************************************************************/
//表达式管理结束
/*****************************************************************/
/**
* 增加或者列表
*
* @param selector 否则列表由多个条件组成
* @return 本对象
*/
public C addOr(Selector selector)
{
List<Condition> conditionList = selector.getConditionList();
Asserts.as(conditionList != null?null:"增加[or]查询条件不能为空");
Asserts.as(conditionList.size() >= 2?null:"增加[or]查询条件必须>=2个");
_Or or = new _Or();
for (Condition condition : conditionList)
{
or.addCondition(condition);
}
addCondition(or);
return self();
}
/*****************************************************************/
//条件列表管理结束
/*****************************************************************/
/**
* 组装Where条件的SQL语句
*
* @param dbo _Dbo/_Table/_View三种的一种
* @param paramMap 参数表
* @return SQL字符串
* @throws ORMException 异常
*/
public String getWhereSQL(Dbo dbo, MapSO paramMap) throws ORMException
{
if (conditionList == null || conditionList.isEmpty())
return "";
//如果相等的连接条件,后面加and即可,否则先加where,再接and
boolean hasEqualJoin = dbo.hasEqualJoin();
StringBuilder whereSQL = new StringBuilder();
//第一个
whereSQL.append(hasEqualJoin?" and ":" where ");
whereSQL.append(conditionList.get(0).toSql(dbo, paramMap));
//后面的
for (int i=1;i<conditionList.size();i++)
{
whereSQL.append(" and ").append(conditionList.get(i).toSql(dbo, paramMap));
}
return whereSQL.toString();
}
/** 返回子类实例 */
@SuppressWarnings("unchecked")
protected final C self()
{
return (C)this;
}
/**
* 增加适配信息
*
* @param key 适配建
* @param value 适配值
*/
protected void addReplaceInner(String key, String value)
{
if (replaceMap == null)
replaceMap = new LinkedMapSS(2);
replaceMap.put(key, value);
}
/**
* 增加查询条件
*
* @param condition 条件
*/
protected void addCondition(Condition condition)
{
if (conditionList == null)
conditionList = new ArrayList<Condition>(3);
conditionList.add(condition);
}
/**
* 可能性检查字段是否为空,为空返回false,否则返回true
*
* @param field 字段
* @return 为空返回false,否则返回true
*/
protected boolean chkMaybeFieldValue(String field)
{
return !Validates.isEmptyBlank(field);
}
/**
* 强制性检查字段是否为空,为空返回false,否则返回true
*
* @param field 字段
*/
protected void chkMustFieldValue(String field)
{
Asserts.notEmptyBlank(field);
}
/**
* 可能性检查字段和值是否为空,为空返回false,否则返回true
*
* @param field 字段
* @param value 值
* @return 为空返回false,否则返回true
*/
protected boolean chkMaybeFieldValue(String field, Object value)
{
if (Validates.isEmptyBlank(field) || value == null)
return false;
if (value instanceof String && Validates.isEmpty((String)value))
return false;
if (value instanceof Integer && ((Integer)value) == -1)
return false;
if (value instanceof Long && ((Long)value) == -1)
return false;
if (Types.isArray(value))
{
if (Array.getLength(value) == 0)
return false;
}
return true;
}
/**
* 强制性检查字段和值是否为空,为空抛非法参数异常
*
* @param field 字段
* @param value 值
*/
protected void chkMustFieldValue(String field, Object value)
{
Asserts.notEmptyBlank(field, _FIELD_);
Asserts.notNull(value, _VALUE_);
Asserts.as(!(value instanceof String && Validates.isEmpty((String)value)) ? null : "字段["+field+"]的["+value+"]为String型时值不能为空字符串");
Asserts.as(!(value instanceof Integer && ((Integer)value) == -1) ? null : "字段["+field+"]的["+value+"]为int型时值不能为-1");
Asserts.as(!(value instanceof Long && ((Long)value) == -1) ? null : "字段["+field+"]的["+value+"]为long型时值不能为-1");
if (Types.isArray(value))
{
Asserts.as(Array.getLength(value) > 0 ? null : "字段["+field+"]或["+value+"]为Array型时数目必须>0");
}
}
}
@@ -0,0 +1,58 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import org.zhiqim.orm.dbo.defined._Dbo;
import org.zhiqim.orm.dbo.defined._Table;
import org.zhiqim.orm.dbo.defined._View;
/**
* 数据库对象模型,(_Dbo,_Table, _View)三个子类<br><br>
* @see _Dbo 是查询结果对象,用于executeQuery时组装返回一个对象<br>
* @see _Table 是数据库表对象,用于ZTable对象映射到数据库进行增删改查<br>
* @see _View 是数据库视图对象,由多个表数据组装而成,用于ZView关联查询<br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public interface Dbo
{
/** 获取类名 */
public String getName();
/** 判断是否是有相等的连接条件 */
public boolean hasEqualJoin();
/** 判断是否存在该字段 */
public boolean hasField(String fieldName);
/** 通过字段获取数据库列名 */
public String getColumn(String fieldName);
/** 通过字段名获取组装GET方法 */
public String getGetMethod(String fieldName);
/** 通过字段名获取字段 */
public DboField getField(String fieldName);
/** 获取字段列表,按长度排序 */
public DboField[] getFieldColumnListOrderByLen();
}
@@ -0,0 +1,48 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
/**
* 数据库对象字段模型,(_DboField, _TableField, _ViewField)三个子类<br><br>
* 1. @see _DboField 数据库查询结构对象的字段
* 2. @see _TableField 数据库表列,描述类字段和数据库表列名的映射关系,如字段userName对应表列名USER_NAME,类型为String<br>
* 3. @see _ViewField 数据库视图关联列,比_TableField多一个table字段,用于指定某个表的列名和类型<br>
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public interface DboField
{
/** 字段数据类型,当前支持共9种 */
public int getType();
/** 字段SET方法,用于运行时反射机制赋值 */
public String getSetMethod();
/** 字段SET方法,用于运行时反射机制赋值 */
public String getGetMethod();
/** 获取字段名 */
public String getField();
/** 获取列名 */
public String getColumn();
}
@@ -0,0 +1,378 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.annotation.AnNew;
import org.zhiqim.kernel.extend.HashMapSV;
import org.zhiqim.kernel.extend.LinkedMapSS;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.dbo.defined._Table;
/**
* 对象查询器,支持查询字段、条件和排序条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
@AnAlias("Selector")
@AnNew
public class Selector extends Conditioner<Selector>
{
private static final long serialVersionUID = 1L;
private static final String FIELD_FORMAT = " ,_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
private String fields = null;
private String groupby = null;
private LinkedMapSS orderbyMap = null;
private HashMapSV<Selector> joinMap = null;
/** 构造空查询器,构造后增加参数 */
public Selector()
{
}
/** 构造指定字段串的查询器 */
public Selector(String fields)
{
addFields(fields);
}
/** 构造指定一个相等条件的查询器 */
public Selector(String field, Object value)
{
addMust(field, value);
}
/** 构造指定字段串和一个相等条件的查询器 */
public Selector(String fields, String field, Object value)
{
addFields(fields);
addMust(field, value);
}
/** 增加一个条件 */
public Selector(Condition condition)
{
addCondition(condition);
}
/** 增加字段字符串 */
public Selector addFields(String fields)
{
if (!Validates.isScope(fields, FIELD_FORMAT))
return this;
//去除前后空格和逗号
fields = fields.trim();
fields = Strings.trimLeft(fields, ",");
fields = Strings.trimRight(fields, ",");
if (Validates.isEmptyBlank(fields))
return this;
if (this.fields != null)
fields = this.fields + "," + fields;
//去除相同的字段
String[] fieldArr = Arrays.toStringArray(fields);
this.fields = Arrays.toFilterSameStr(fieldArr);
return this;
}
/** 清除字段字符串 */
public Selector clearFields()
{
this.fields = null;
return this;
}
/**
* 增加适配信息
*
* @param key 适配建
* @param value 适配值
* @return 返回本对象
*/
public Selector addReplace(String key, String value)
{
addReplaceInner(key, value);
return this;
}
/** 增加分组字段字符串 */
public Selector addGroupbyFields(String fields)
{
if (!Validates.isScope(fields, FIELD_FORMAT))
return this;
//去除前后空格和逗号
fields = fields.trim();
fields = Strings.trimLeft(fields, ",");
fields = Strings.trimRight(fields, ",");
if (Validates.isEmptyBlank(fields))
return this;
if (this.groupby != null)
fields = this.groupby + "," + fields;
//去除相同的字段
String[] fieldArr = Arrays.toStringArray(fields);
this.groupby = Arrays.toFilterSameStr(fieldArr);
return this;
}
/** 清除分组字段字符串 */
public Selector clearGroupbyFields()
{
this.groupby = null;
return this;
}
/** 增加左右连别名查询器 */
public Selector addJoin(String alias, Selector selector)
{
if (joinMap == null)
joinMap = new HashMapSV<>();
joinMap.put(alias, selector);
return this;
}
/** 增加左右连类查询器 */
public Selector addJoin(Class<?> clazz, Selector selector)
{
if (joinMap == null)
joinMap = new HashMapSV<>();
joinMap.put(clazz.getName(), selector);
return this;
}
/**
* 组装Where条件的SQL语句
*
* @param dbo _Dbo/_Table/_View三种的一种
* @param alias 表别名
* @param table 表真实名称
* @param tableAlias 表真实名后连表别名
* @param paramMap 参数表
* @return SQL字符串
* @throws ORMException 异常
*/
public String getJoinWhereSQL(ZTable fTable, String alias, String table, String tableAlias, MapSO paramMap) throws ORMException
{
if (joinMap == null)
return tableAlias;
//先判断是否从别名中获取到,没有再找类名
_Table dbo = fTable.getTableByTableName(table);
Selector selector = joinMap.get(alias);
if (selector == null)
selector = joinMap.get(dbo.getName());
if (selector == null)
return tableAlias;
List<Condition> conditionList = selector.getConditionList();
if (conditionList == null || conditionList.isEmpty())
return tableAlias;
//如果相等的连接条件,后面加and即可,否则先加where,再接and
StringBuilder whereSQL = new StringBuilder();
//第一个
whereSQL.append("(select ").append(selector.getFieldSQL(dbo))
.append(" from ").append(table)
.append(" where ");
whereSQL.append(conditionList.get(0).toSql(dbo, paramMap));
//后面的
for (int i=1;i<conditionList.size();i++)
{
whereSQL.append(" and ").append(conditionList.get(i).toSql(dbo, paramMap));
}
whereSQL.append(") as ").append(alias);
return whereSQL.toString();
}
/******************************************************/
//排序管理
/******************************************************/
/** 判断是否有排序 */
public boolean hasOrderby()
{
return orderbyMap != null && !orderbyMap.isEmpty();
}
/** 获取排序列表 */
public LinkedMapSS getOrderby()
{
return orderbyMap;
}
/**
* 增加顺序排序方式
*
* @param fields 排序属性
*/
public Selector addOrderbyAsc(String fields)
{
if (orderbyMap == null)
orderbyMap = new LinkedMapSS(2);
String[] fieldArr = Arrays.toStringArray(fields);
for (String field : fieldArr){
orderbyMap.put(field, ASC);
}
return this;
}
/**
* 增加倒序排序方式
*
* @param field 排序属性
*/
public Selector addOrderbyDesc(String fields)
{
if (orderbyMap == null)
orderbyMap = new LinkedMapSS(2);
String[] fieldArr = Arrays.toStringArray(fields);
for (String field : fieldArr){
orderbyMap.put(field, DESC);
}
return this;
}
/** 获取字段字符串 */
public String getFields()
{
return fields;
}
/** 获取字段SQL */
public String getFieldSQL(Dbo dbo) throws ORMException
{
if (Validates.isEmptyBlank(fields))
return "*";
StringBuilder strb = new StringBuilder();
String[] fieldArr = Arrays.toStringArray(fields);
for (String field : fieldArr)
{
String column = dbo.getColumn(field);
if (column == null)
continue;
strb.append(column).append(",");
}
if (strb.length() > 0){
strb.setLength(strb.length()-1);
}
return strb.toString();
}
/** 检查排序 */
public String getOrderbySQL(Dbo dbo) throws ORMException
{
if (orderbyMap == null || orderbyMap.isEmpty())
return "";
StringBuilder strb = new StringBuilder(" order by");
for (Entry<String, String> entry : orderbyMap.entrySet())
{
String field = entry.getKey();
if (!dbo.hasField(field))
throw new ORMException("映射配置异常,在配置["+dbo.getName()+"]中未找到["+field+"]字段");
String column = dbo.getColumn(field);
strb.append(" ").append(column).append(" ").append(entry.getValue()).append(",");
}
strb.setLength(strb.length()-1);
return strb.toString();
}
/** 检查排序并反转,用于分页时倒序的倒序 */
public String getOrderbyReverseSQL(Dbo dbo) throws ORMException
{
if (orderbyMap == null || orderbyMap.isEmpty())
return "";
//先转换成列表
ArrayList<String[]> orderbyList = new ArrayList<String[]>();
for (Entry<String, String> entry : orderbyMap.entrySet())
{
String field = entry.getKey();
if (!dbo.hasField(field))
throw new ORMException("映射配置异常,在配置["+dbo.getName()+"]中未找到["+field+"]字段");
orderbyList.add(new String[]{field, (ASC.equals(entry.getValue()))?DESC:ASC});
}
//再作反转
orderbyList = Lists.reverse(orderbyList);
//生成字符串
StringBuilder strb = new StringBuilder(" order by");
for (String[] orderbyArr : orderbyList)
{
String field = orderbyArr[0];
String value = orderbyArr[1];
String column = dbo.getColumn(field);
strb.append(" ").append(column).append(" ").append(value).append(",");
}
strb.setLength(strb.length()-1);
return strb.toString();
}
/** 获取分组SQL */
public String getGroupbySQL(Dbo dbo) throws ORMException
{
if (Validates.isEmptyBlank(groupby))
return "";
StringBuilder strb = new StringBuilder(" group by");
String[] fieldArr = Arrays.toStringArray(groupby);
for (String field : fieldArr)
{
String column = dbo.getColumn(field);
if (column == null)
throw new ORMException("映射配置异常,在配置["+dbo.getName()+"]中未找到["+field+"]属性");
strb.append(" ").append(column).append(",");
}
strb.setLength(strb.length()-1);
return strb.toString();
}
}
@@ -0,0 +1,89 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.annotation.AnNew;
import org.zhiqim.kernel.extend.LinkedMapSV;
import org.zhiqim.orm.ORMException;
/**
* 对象更新器,支持更新字段列表,和查询条件列表
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
@AnAlias("Updater")
@AnNew
public class Updater extends Conditioner<Updater>
{
private static final long serialVersionUID = 1L;
private LinkedMapSV<UpdaterField> fieldMap = new LinkedMapSV<>();
/** 检查有效性 */
public boolean isValid() throws ORMException
{
//完成field
if (fieldMap.isEmpty() || conditionList.isEmpty())
return false;
else
return true;
}
/**
* 增加适配信息
*
* @param key 适配建
* @param value 适配值
* @return 返回本对象
*/
public Updater addReplace(String key, String value)
{
addReplaceInner(key, value);
return this;
}
/******************************************************/
//字段管理
/******************************************************/
/**
* 增加更新字段
*
* @param field 更新字段
*/
public Updater addField(String field, Object value)
{
fieldMap.put(field, new UpdaterField(field, value));
return this;
}
public Updater addFieldExpression(String field, String expression)
{
fieldMap.put(field, new UpdaterField(field, expression, 1));
return this;
}
public LinkedMapSV<UpdaterField> getFieldList()
{
return fieldMap;
}
}
@@ -0,0 +1,70 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo;
import java.io.Serializable;
/**
* 更新器字段说明
*
* 1.更新字段=某值
* 2.更新字段为表达式
*
* @version v1.0.0 @author zhichenggang 2014-3-21 新建与整理
*/
public class UpdaterField implements Serializable
{
private static final long serialVersionUID = 1L;
private String field;
private Object value;
private int type;//=0表示值,=1表示表达式,其中表达式支持字段替换
UpdaterField(String field, Object value)
{
this.field = field;
this.value = value;
this.type = 0;
}
UpdaterField(String field, Object value, int type)
{
this.field = field;
this.value = value;
this.type = type;
}
public String getField()
{
return field;
}
public Object getValue()
{
return value;
}
public int getType()
{
return type;
}
}
@@ -0,0 +1,81 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 比较类型的条件,一共支持9种
*
* @see _Equal 相等
* @see _EqualNot 不等
* @see _ThenG 大于
* @see _ThenGE 大于等于
* @see _ThenL 小于
* @see _ThenLE 小于等于
* @see _Like 两边like
* @see _LikeL 左边like
* @see _LikeR 右边like
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public abstract class _Compare extends Condition
{
protected String field;
protected Object value;
protected String compare;
public _Compare(String field, Object value, String compare)
{
this.field = field;
this.value = value;
this.compare = compare;
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
String column = dbo.getColumn(field);
int ind = paramMap.size();
paramMap.put(field+ind, convertValue(value));//把值放到表中,后续方便把##转成?号,然后再设置值
return new StringBuilder()
.append(column).append(_SPACE_).append(compare).append(_SPACE_)
.append("#").append(field+ind).append("#")
.toString();
}
public String getField()
{
return field;
}
public Object getValue()
{
return value;
}
}
@@ -0,0 +1,45 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Validates;
/**
* 相等条件
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _Equal extends _Compare
{
public _Equal(String field, Object value)
{
super(field, value, EQUAL);
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return Validates.isEqual(fValue, value);
}
}
@@ -0,0 +1,46 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Validates;
/**
* 不等条件
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _EqualNot extends _Compare
{
public _EqualNot(String field, Object value)
{
super(field, value, EQUAL_NOT);
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return !Validates.isEqual(fValue, value);
}
}
@@ -0,0 +1,74 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
import org.zhiqim.orm.dbo.DboField;
/**
* 表达式条件,如where field = field2+1
*
* @version v1.0.0 @author zouzhigang 2017-9-8 新建与整理
*/
public class _Expression extends Condition
{
private String field;
private String expression;
private String condition;
public _Expression(String field, String expression, String condition)
{
this.field = field;
this.expression = expression;
this.condition = condition;
}
@Override
public boolean match(Object obj)
{
throw Asserts.exception("暂不支持表达式匹配");
}
@Override
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
String column = dbo.getColumn(field);
//对表达式中可能出现的字段进行匹配,替换成表列,注意有可能第二个列名会包含第一个列名,因此处理时字段名从长到短进行匹配
DboField[] dboFieldArr = dbo.getFieldColumnListOrderByLen();
for (DboField dboField : dboFieldArr)
{//依次从长到短对表达式中的字段替换成表列 TODO 暂不对$等可能替换成错进行处理
expression = expression.replaceAll(dboField.getField(), dboField.getColumn());
}
return new StringBuilder()
.append(column).append(_SPACE_).append(condition).append(_SPACE_).append(expression)
.toString();
}
}
@@ -0,0 +1,73 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 判断是否在数组中的条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _In extends Condition
{
private String field;
private Object value;
public _In(String field, Object value)
{
this.field = field;
this.value = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return Validates.isContain(Lists.toList(Arrays.toArray(value)), fValue);
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
assertArray(value);
String column = dbo.getColumn(field);
return new StringBuilder().append(column).append(_SPACE_).append(IN).append(_SPACE_).append(convertArray(value)).toString();
}
public String getField()
{
return field;
}
public Object getValue()
{
return value;
}
}
@@ -0,0 +1,73 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Arrays;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Lists;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 判断是否不在数组中的条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _InNot extends Condition
{
private String field;
private Object value;
public _InNot(String field, Object value)
{
this.field = field;
this.value = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return !Validates.isContain(Lists.toList(Arrays.toArray(value)), fValue);
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
assertArray(value);
String column = dbo.getColumn(field);
return new StringBuilder().append(column).append(_SPACE_).append(IN_NOT).append(_SPACE_).append(convertArray(value)).toString();
}
public String getField()
{
return field;
}
public Object getValue()
{
return value;
}
}
@@ -0,0 +1,59 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 判断是否为空的条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _IsEmpty extends Condition
{
private String field;
public _IsEmpty(String field)
{
this.field = field;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return fValue == null;
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
String column = dbo.getColumn(field);
return new StringBuilder("(").append(column).append(_SPACE_).append(IS_NULL)
.append(" or ").append(column).append(" = '')")
.toString();
}
}
@@ -0,0 +1,59 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 判断是否不为空的条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _IsNotEmpty extends Condition
{
private String field;
public _IsNotEmpty(String field)
{
this.field = field;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return fValue != null;
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
String column = dbo.getColumn(field);
return new StringBuilder().append(column).append(_SPACE_).append(IS_NOT_NULL)
.append(" and ").append(column).append(" <> ''")
.toString();
}
}
@@ -0,0 +1,57 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 判断是否不为空的条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _IsNotNull extends Condition
{
private String field;
public _IsNotNull(String field)
{
this.field = field;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return fValue != null;
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
String column = dbo.getColumn(field);
return new StringBuilder().append(column).append(_SPACE_).append(IS_NOT_NULL).toString();
}
}
@@ -0,0 +1,57 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.extend.MapSO;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.dbo.Condition;
import org.zhiqim.orm.dbo.Dbo;
/**
* 判断是否为空的条件
*
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _IsNull extends Condition
{
private String field;
public _IsNull(String field)
{
this.field = field;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
return fValue == null;
}
public String toSql(Dbo dbo, MapSO paramMap) throws ORMException
{
assertField(dbo, field);
String column = dbo.getColumn(field);
return new StringBuilder().append(column).append(_SPACE_).append(IS_NULL).toString();
}
}
@@ -0,0 +1,50 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
/**
* 两边LIKE
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _Like extends _Compare
{
private String orgiValue;
public _Like(String field, String value)
{
super(field, "%"+value+"%", LIKE);
this.orgiValue = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
if (fValue == null)
return false;
return String.valueOf(fValue).contains(orgiValue);
}
}
@@ -0,0 +1,51 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Strings;
/**
* 左边LIKE
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _LikeL extends _Compare
{
private String orgiValue;
public _LikeL(String field, String value)
{
super(field, "%"+value, LIKE);
this.orgiValue = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
if (fValue == null)
return false;
return Strings.endsWith(String.valueOf(fValue), orgiValue);
}
}
@@ -0,0 +1,50 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
/**
* 两边NOT LIKE
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _LikeNot extends _Compare
{
private String orgiValue;
public _LikeNot(String field, String value)
{
super(field, "%"+value+"%", LIKE_NOT);
this.orgiValue = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
if (fValue == null)
return false;
return !String.valueOf(fValue).contains(orgiValue);
}
}
@@ -0,0 +1,51 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Strings;
/**
* 左边NOT LIKE
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _LikeNotL extends _Compare
{
private String orgiValue;
public _LikeNotL(String field, String value)
{
super(field, "%"+value, LIKE_NOT);
this.orgiValue = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
if (fValue == null)
return false;
return !Strings.endsWith(String.valueOf(fValue), orgiValue);
}
}
@@ -0,0 +1,51 @@
/*
* 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙,邂逅框架梦]
*
* 知启蒙数据库映射(zhiqim_orm)在LGPL3.0协议下开源:https://www.zhiqim.com/gitcan/zhiqim/zhiqim_orm.htm
*
* This file is part of [zhiqim_orm].
*
* [zhiqim_orm] is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* [zhiqim_orm] is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with [zhiqim_orm].
* If not, see <http://www.gnu.org/licenses/>.
*/
package org.zhiqim.orm.dbo.condition;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Strings;
/**
* 右边NOT LIKE
*
* @see _Compare 具体实现在父类比较条件中
* @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
*/
public class _LikeNotR extends _Compare
{
private String orgiValue;
public _LikeNotR(String field, String value)
{
super(field, value+"%", LIKE_NOT);
this.orgiValue = value;
}
public boolean match(Object obj)
{
Object fValue = Classes.getFieldValue(obj, field);
if (fValue == null)
return false;
return !Strings.startsWith(String.valueOf(fValue), orgiValue);
}
}

Some files were not shown because too many files have changed in this diff Show More