...
 
Commits (13)
    https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/75dd870da51cc42810b749d76c72cd63b86d2e48 LogicDeleteProvider 2023-07-31T21:19:38+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/aa95c407ca4bef0a7ecd0faf4d483891cef9a822 3.2 2023-07-31T21:25:15+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/d9aad5369b259012d9eca74726d071f44aefef49 mybatis-jpa-extra-core rename mybatis-jpa-extra 2023-08-03T09:10:54+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/3e54608a9c46e4adaf7a7b83fa172aba88d85a63 ${project.parent.version} 2023-08-04T19:12:59+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/33ac78bfec281c01d1b5b23ca088d90ecd48b455 add findByIds and Split TestRunner 2023-08-05T11:46:24+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/4a103c24eada347c7a629d9b2d45b01db491d5da readme 2023-08-05T12:08:30+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/324e3141be29379d6a3a539f071b100424617fe3 Update README.md 2023-08-05T12:14:52+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/18aecef62dd994e71deeca8b726cb8444e2d366d readme 2023-08-05T14:26:04+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/d67e13c75cd4bc8df6ff020c1feeedf5ab7196e3 Update README.md 2023-08-05T19:55:08+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/fed62a3e0774512bfc5b2e9c0d674c6576f91cc5 release 2023-08-05T20:42:11+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/2fd2fb607bd60854b0a0ecf3319f0211491631a5 del jar 2023-08-09T09:21:09+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/3436bf3646878018b69f71189f56748e51113f3e fetchPageResults 2023-08-11T14:01:36+08:00 MaxKey shimingxy@qq.com https://gitcode.net/maxkeytop/mybatis-jpa-extra/-/commit/707c8c1d67095bf07b2b0c5004d717b57dd8286d 代码优化 2023-08-13T10:56:08+08:00 MaxKey shimingxy@qq.com
......@@ -21,3 +21,4 @@ jdk/*
.vscode/launch.json
*/bin/*
*\bin\*
target/mybatis-jpa-extra-parent-3.2.pom
......@@ -2,9 +2,9 @@
**MyBatis JPA Extra**对MyBatis扩展JPA功能
1.Jakarta JPA 3注释**简化CUID操作**;
2.Interceptor实现数据库**SELECT分页查询**;
3.**链式**Query查询条件构造器;
4.提供starter,**简化SpringBoot集成**;
......@@ -37,40 +37,36 @@
## 1.3、Java Bean 注释
```java
@Entity
@Table(name = "STUDENTS")
public class Students extends JpaEntity implements Serializable{
@Id
@Column
@GeneratedValue
//@GeneratedValue(strategy=GenerationType.AUTO,generator="snowflakeid")
//@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="SEQ_MYBATIS_STUD")
private String id;
@Column
private String stdNo;
@Column
private String stdName;
@Column
@ColumnDefault("'M'")
private String stdGender;
@Column
private int stdAge;
@Column
private String stdMajor;
@Column
private String stdClass;
@Column
private byte[] images;
@Column(insertable = false)
@GeneratedValue
@Temporal(TemporalType.TIMESTAMP)
@Id
@Column
@GeneratedValue
private String id;
@Column
private String stdNo;
@Column
private String stdName;
@Column
@ColumnDefault("'M'")
private String stdGender;
@Column
private int stdAge;
@Column
private String stdMajor;
@Column
private String stdClass;
@Column
private byte[] images;
@Column(insertable = false)
@GeneratedValue
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime modifyDate;
@ColumnLogic
@Column(name ="is_deleted")
private int isDeleted;
//getter setter
@ColumnLogic
@Column(name ="is_deleted")
private int isDeleted;
//getter setter
}
```
## 2、基本操作
......@@ -78,239 +74,225 @@ public class Students extends JpaEntity implements Serializable{
## 2.1、CURD
```java
//新增数据
@Test
public void insert() throws Exception{
_logger.info("insert...");
Students student = new Students();
student.setStdNo("10024");
student.setStdGender("M");
student.setStdName("司马昭");
student.setStdAge(20);
student.setStdMajor("政治");
student.setStdClass("4");
service.insert(student);
Thread.sleep(1000);
_logger.info("insert id " + student.getId());
}
//查询数据实体并更新
@Test
public void update() throws Exception{
_logger.info("get...");
Students student = service.get("317d5eda-927c-4871-a916-472a8062df23");
System.out.println("Students "+student);
_logger.info("Students "+student);
_logger.info("update...");
student.setImages(null);
service.update(student);
_logger.info("updateed.");
student.setImages("ssss".getBytes());
service.update(student);
_logger.info("updateed2.");
}
//根据实体查询并更新
@Test
public void merge() throws Exception{
_logger.info("merge...");
Students student = new Students();
student.setStdNo("10024");
student.setStdGender("M");
student.setStdName("司马昭");
student.setStdAge(20);
student.setStdMajor("政治");
student.setStdClass("4");
service.merge(student);
Thread.sleep(1000);
_logger.info("merge id " + student.getId());
}
//根据ID查询
@Test
public void get() throws Exception{
_logger.info("get...");
Students student = service.get("317d5eda-927c-4871-a916-472a8062df23");
System.out.println("Students "+student);
_logger.info("Students "+student);
}
//根据实体查询
@Test
public void query() throws Exception{
_logger.info("query...");
Students student = new Students();
student.setStdGender("M");
List<Students> listStudents =service.query(student);
}
//新增数据
@Test
void insert() throws Exception{
Students student = new Students();
student.setStdNo("10024");
student.setStdGender("M");
student.setStdName("司马昭");
student.setStdAge(20);
student.setStdMajor("政治");
student.setStdClass("4");
service.insert(student);
}
//查询数据实体并更新
@Test
void update() throws Exception{
Students student = service.get("317d5eda-927c-4871-a916-472a8062df23");
student.setStdMajor("政治");
service.update(student);
}
//根据实体查询并更新
@Test
void merge() throws Exception{
Students student = new Students();
student.setStdMajor("政治");
student.setStdClass("4");
service.merge(student);
}
//根据ID查询
@Test
void get() throws Exception{
Students student = service.get("317d5eda-927c-4871-a916-472a8062df23");
}
//根据实体查询
@Test
void query() throws Exception{
Students student = new Students();
student.setStdGender("M");
List<Students> listStudents = service.query(student);
}
//查询所有记录
@Test
void findAll() throws Exception{
List<Students> listStudents = service.findAll();
}
//根据ID删除
@Test
void remove() throws Exception{
service.remove("921d3377-937a-4578-b1e2-92fb23b5e512");
}
//根据ID集合批量删除
@Test
void batchDelete() throws Exception{
List<String> idList = new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
idList.add("ab7422e9-a91a-4840-9e59-9d911257c918");
//...
service.deleteBatch(idList);
}
//根据ID批量删除
@Test
void batchDeleteByIds() throws Exception{
service.deleteBatch("2");
service.deleteBatch("2,639178432667713536");
}
```
## 2.2、逻辑删除
```java
//根据ID删除或者ID字符串分隔符,批量逻辑删除
@Test
void logicDelete() throws Exception{
service.logicDelete("2");
service.logicDelete("2,639178432667713536");
}
//根据IDS批量逻辑删除
@Test
void logicBatchDelete() throws Exception{
List<String> idList=new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
idList.add("ab7422e9-a91a-4840-9e59-9d911257c918");
//...
service.logicDelete(idList);
}
//根据IDS字符串和分割符批量逻辑删除
@Test
void logicDeleteSplit() throws Exception{
service.logicDeleteSplit("2,639178432667713536",",");
}
//查询所有记录
@Test
public void findAll() throws Exception{
_logger.info("findAll...");
List<Students> listStudents = service.findAll();
}
```
//根据ID删除
@Test
public void remove() throws Exception{
_logger.info("remove...");
service.remove("921d3377-937a-4578-b1e2-92fb23b5e512");
}
//根据ID集合批量删除
@Test
public void batchDelete() throws Exception{
_logger.info("batchDelete...");
List<String> idList = new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
idList.add("ab7422e9-a91a-4840-9e59-9d911257c918");
idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c");
idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe");
service.deleteBatch(idList);
}
//根据ID批量逻辑删除
@Test
public void logicDelete() throws Exception{
_logger.info("logicDelete...");
List<String> idList = new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
idList.add("ab7422e9-a91a-4840-9e59-9d911257c918");
idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c");
idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe");
service.logicDelete(idList);
}
## 2.3、Find查询和Qruey构造器
//根据ID批量删除
@Test
public void batchDeleteByIds() throws Exception{
_logger.info("batchDeleteByIds...");
service.deleteBatch("2");
service.deleteBatch("2,639178432667713536");
}
```java
//SpringJDBC的查询方式 where StdNo = '10024' or StdNo = '10004'
@Test
void find() throws Exception{
List<Students> listStudents = service.find(" StdNo = ? or StdNo = ? ",
new Object[]{"10024","10004"},
new int[]{Types.VARCHAR,Types.INTEGER}
);
}
//根据链式条件构造器查询
//WHERE (stdMajor = '政治' and STDAGE > 30 and stdMajor in ( '政治' , '化学' ) or ( stdname = '周瑜' or stdname = '吕蒙' ) )
@Test
void queryByCondition() throws Exception{
List<Students> listStudents = service.query(
new Query().eq("stdMajor", "政治").and().gt("STDAGE", 30).and().in("stdMajor", new Object[]{"政治","化学"})
.or(new Query().eq("stdname", "周瑜").or().eq("stdname", "吕蒙")));
}
```
## 2.2、Find查询和Qruey构造器
## 2.4、单表分页查询
```java
//springJDBC 的查询方式
@Test
public void find() throws Exception{
_logger.info("find by filter StdNo = '10024' or StdNo = '10004'");
List<Students> listStudents = service.find(" StdNo = ? or StdNo = ? ",
new Object[]{"10024","10004"},
new int[]{Types.VARCHAR,Types.INTEGER}
);
}
//根据链式条件构造器查询
//WHERE (stdMajor = '政治' and STDAGE > 30 and stdMajor in ( '政治' , '化学' ) or ( stdname = '周瑜' or stdname = '吕蒙' ) )
@Test
public void queryByCondition() throws Exception{
_logger.info("query by condition ...");
List<Students> listStudents = service.query(
new Query().eq("stdMajor", "政治").and().gt("STDAGE", 30).and().in("stdMajor", new Object[]{"政治","化学"})
.or(new Query().eq("stdname", "周瑜").or().eq("stdname", "吕蒙")));
}
//根据实体分页查询
@Test
void fetch() throws Exception{
JpaPage page = new JpaPage();
page.setPageSize(20);
page.setPageable(true);
Students student = new Students();
student.setStdGender("M");
JpaPageResults<Students> results = service.fetch(page,student);
}
//根据Query条件分页查询 where stdMajor = '政治' and STDAGE > 30
@Test
void fetchByCondition() throws Exception{
JpaPage page = new JpaPage();
page.setPageSize(20);
page.setPageable(true);
Query condition = new Query().eq("stdMajor", "政治").and().gt("STDAGE", 30);
JpaPageResults<Students> results = service.fetch(page,condition);
}
```
## 2.3、分页查询并count数据量
## 2.5、根据mapper的xml分页查询
```java
//根据实体分页查询
@Test
public void fetchPageResults() throws Exception{
_logger.info("fetchPageResults...");
Students student=new Students();
student.setPageSize(10);
//student.setPageNumber(2);
student.calculate(21);
JpaPageResults<Students> results = service.fetchPageResults(student);
List<Students> rowsStudents = results.getRows();
long records =results.getRecords();//当前页记录数量
long totalPage =results.getTotalPage();//总页数
long total =results.getTotal();//总数据量
long page =results.getPage();//当前页
}
//mapper id分页查询
@Test
public void fetchPageResultsByMapperId() throws Exception{
_logger.info("fetchPageResults by mapperId...");
Students student=new Students();
student.setStdGender("M");
student.setPageSize(10);
student.setPageNumber(2);
JpaPageResults<Students> results =
service.fetchPageResults("fetchPageResults1",student);
}
//根据Mapper xml配置fetchPageResults分页查询
@Test
void fetchPageResults() throws Exception{
Students student=new Students();
student.setStdGender("M");
student.setPageSize(10);
student.calculate(21);
JpaPageResults<Students> results = service.fetchPageResults(student);
}
//根据Mapper xml id分页查询,fetchPageResults1在mapper的xml中配置
@Test
void fetchPageResultsByMapperId() throws Exception{
Students student=new Students();
student.setStdGender("M");
student.setPageSize(10);
student.setPageNumber(2);
JpaPageResults<Students> results = service.fetchPageResults("fetchPageResults1",student);
}
```
## 3、mapper配置
```xml
<mapper namespace="org.apache.mybatis.jpa.test.dao.persistence.StudentsMapper" >
<sql id="sql_condition">
WHERE 1 = 1
<if test="id != null">
AND ID = '${id}'
</if>
<if test="stdName != null and stdName != '' ">
AND STDNAME like '%${stdName}%'
</if>
<if test="stdGender != null and stdGender != '' ">
AND STDGENDER = #{stdGender}
</if>
<if test="stdMajor != null">
<![CDATA[AND STDMAJOR = #{stdMajor}]]>
</if>
</sql>
<sql id="sql_condition">
WHERE 1 = 1
<if test="id != null">
AND ID = '${id}'
</if>
<if test="stdName != null and stdName != '' ">
AND STDNAME like '%${stdName}%'
</if>
<if test="stdGender != null and stdGender != '' ">
AND STDGENDER = #{stdGender}
</if>
<if test="stdMajor != null">
<![CDATA[AND STDMAJOR = #{stdMajor}]]>
</if>
</sql>
<select id="fetchPageResults" parameterType="Students" resultType="Students">
SELECT
ID ,
STDNO ,
STDNAME ,
STDGENDER ,
STDAGE ,
STDMAJOR ,
STDCLASS
FROM STUDENTS
<include refid="sql_condition"/>
SELECT
ID ,
STDNO ,
STDNAME ,
STDGENDER ,
STDAGE ,
STDMAJOR ,
STDCLASS
FROM STUDENTS
<include refid="sql_condition"/>
</select>
<select id="fetchPageResults1" parameterType="Students" resultType="Students">
SELECT
ID ,
STDNO ,
STDNAME ,
STDGENDER ,
STDAGE ,
STDMAJOR ,
STDCLASS
FROM STUDENTS
<include refid="sql_condition"/>
SELECT
ID ,
STDNO ,
STDNAME ,
STDGENDER ,
STDAGE ,
STDMAJOR ,
STDCLASS
FROM STUDENTS
<include refid="sql_condition"/>
</select>
<select id="queryBy" parameterType="Students" resultType="Students">
SELECT
ID ,
STDNO ,
STDNAME ,
STDGENDER ,
STDAGE ,
STDMAJOR ,
STDCLASS
FROM ROLES
<include refid="sql_condition"/>
SELECT
ID ,
STDNO ,
STDNAME ,
STDGENDER ,
STDAGE ,
STDMAJOR ,
STDCLASS
FROM ROLES
<include refid="sql_condition"/>
</select>
<delete id="delete" parameterType="Students" >
DELETE FROM STUDENTS WHERE ID=#{id}
DELETE FROM STUDENTS WHERE ID=#{id}
</delete>
```
......
set MAVEN_HOME=D:\IDE\apache-maven-3.9.1
set JAVA_HOME=D:\IDE\jdk-17.0.2.8
call %MAVEN_HOME%/bin/mvn versions:set -DnewVersion=3.1
call %MAVEN_HOME%/bin/mvn versions:set -DnewVersion=3.2
call %MAVEN_HOME%/bin/mvn versions:update-child-modules
......@@ -7,7 +7,7 @@
<parent>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-parent</artifactId>
<version>3.1</version>
<version>3.2</version>
</parent>
<!--self -->
......@@ -25,17 +25,17 @@
<dependency>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra</artifactId>
<version>${mybatis.jpa.extra.version}</version>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-test</artifactId>
<version>${mybatis.jpa.extra.version}</version>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-spring-boot-starter</artifactId>
<version>${mybatis.jpa.extra.version}</version>
<version>${project.parent.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
......
......@@ -7,7 +7,7 @@
<parent>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-parent</artifactId>
<version>3.1</version>
<version>3.2</version>
</parent>
<!--self -->
......@@ -25,7 +25,7 @@
<dependency>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra</artifactId>
<version>${mybatis.jpa.extra.version}</version>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
......
......@@ -5,7 +5,7 @@
<parent>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-parent</artifactId>
<version>3.1</version>
<version>3.2</version>
</parent>
<!--self -->
......@@ -18,7 +18,7 @@
<dependency>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra</artifactId>
<version>${mybatis.jpa.extra.version}</version>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
<build>
......
......@@ -32,7 +32,7 @@ public class CurdTestRunner {
public static StudentsService service;
@Test
public void insert() throws Exception{
void insert() throws Exception{
_logger.info("insert...");
Students student=new Students();
student.setStdNo("10024");
......@@ -48,7 +48,7 @@ public class CurdTestRunner {
}
@Test
public void merge() throws Exception{
void merge() throws Exception{
_logger.info("merge...");
Students student=new Students();
student.setStdNo("10024");
......@@ -65,7 +65,7 @@ public class CurdTestRunner {
}
@Test
public void get() throws Exception{
void get() throws Exception{
_logger.info("get...");
Students student=service.get("317d5eda-927c-4871-a916-472a8062df23");
System.out.println("Students "+student);
......@@ -90,13 +90,13 @@ public class CurdTestRunner {
}
@Test
public void remove() throws Exception{
void remove() throws Exception{
_logger.info("remove...");
service.remove("921d3377-937a-4578-b1e2-92fb23b5e512");
}
@Test
public void batchDelete() throws Exception{
void batchDelete() throws Exception{
_logger.info("batchDelete...");
List<String> idList=new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
......@@ -107,31 +107,11 @@ public class CurdTestRunner {
}
@Test
public void logicDelete() throws Exception{
_logger.info("logicDelete...");
List<String> idList=new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
idList.add("ab7422e9-a91a-4840-9e59-9d911257c918");
idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c");
idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe");
service.logicDelete(idList);
}
@Test
public void batchDeleteByIds() throws Exception{
void batchDeleteByIds() throws Exception{
_logger.info("batchDeleteByIds...");
service.deleteBatch("2");
service.deleteBatch("2,639178432667713536");
}
@Test
public void findAll() throws Exception{
_logger.info("findAll...");
List<Students> allListStudents =service.findAll();
for (Students s : allListStudents) {
_logger.info("Students "+s);
}
}
@BeforeAll
public static void initSpringContext(){
......
......@@ -19,9 +19,7 @@ package org.dromara.mybatis.jpa.test;
import java.util.List;
import org.dromara.mybatis.jpa.entity.JpaPage;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
import org.dromara.mybatis.jpa.query.Query;
import org.dromara.mybatis.jpa.test.dao.service.StudentsService;
import org.dromara.mybatis.jpa.test.entity.Students;
import org.junit.jupiter.api.BeforeAll;
......@@ -34,7 +32,7 @@ public class FetchPageResultsTestRunner {
public static StudentsService service;
@Test
public void fetchPageResults() throws Exception{
void fetchPageResults() throws Exception{
_logger.info("fetchPageResults...");
Students student=new Students();
......@@ -54,43 +52,7 @@ public class FetchPageResultsTestRunner {
}
@Test
public void fetch() throws Exception{
_logger.info("fetch...");
JpaPage page = new JpaPage();
Students student = new Students();
student.setStdGender("M");
student.setStdAge(40);
page.setPageSize(20);
page.setPageable(true);
JpaPageResults<Students> results = service.fetch(page,student);
List<Students> rowsStudents = results.getRows();
_logger.info("records {} , totalPage {} , total {} , page {} ",
results.getRecords(),results.getTotalPage(),results.getTotal(),results.getPage());
for (Students s : rowsStudents) {
_logger.info("Students "+s);
}
}
@Test
public void fetchByCondition() throws Exception{
_logger.info("fetchByCondition...");
JpaPage page = new JpaPage();
Query condition = new Query().eq("stdMajor", "政治").and().gt("STDAGE", 30);
page.setPageSize(20);
page.setPageable(true);
JpaPageResults<Students> results = service.fetch(page,condition);
List<Students> rowsStudents = results.getRows();
_logger.info("records {} , totalPage {} , total {} , page {} ",
results.getRecords(),results.getTotalPage(),results.getTotal(),results.getPage());
for (Students s : rowsStudents) {
_logger.info("Students "+s);
}
}
@Test
public void fetchPageResultsByMapperId() throws Exception{
void fetchPageResultsByMapperId() throws Exception{
_logger.info("fetchPageResults by mapperId...");
Students student=new Students();
......
/*
* Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.mybatis.jpa.test;
import java.util.List;
import org.dromara.mybatis.jpa.entity.JpaPage;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
import org.dromara.mybatis.jpa.query.Query;
import org.dromara.mybatis.jpa.test.dao.service.StudentsService;
import org.dromara.mybatis.jpa.test.entity.Students;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FetchTestRunner {
private static final Logger _logger = LoggerFactory.getLogger(FetchTestRunner.class);
public static StudentsService service;
@Test
void fetch() throws Exception{
_logger.info("fetch...");
JpaPage page = new JpaPage();
Students student = new Students();
student.setStdGender("M");
student.setStdAge(40);
page.setPageSize(20);
page.setPageable(true);
JpaPageResults<Students> results = service.fetch(page,student);
List<Students> rowsStudents = results.getRows();
_logger.info("records {} , totalPage {} , total {} , page {} ",
results.getRecords(),results.getTotalPage(),results.getTotal(),results.getPage());
for (Students s : rowsStudents) {
_logger.info("Students "+s);
}
}
@Test
void fetchByCondition() throws Exception{
_logger.info("fetchByCondition...");
JpaPage page = new JpaPage();
page.setPageSize(20);
page.setPageable(true);
Query condition = new Query().eq("stdMajor", "政治").and().gt("STDAGE", 30);
JpaPageResults<Students> results = service.fetch(page,condition);
List<Students> rowsStudents = results.getRows();
_logger.info("records {} , totalPage {} , total {} , page {} ",
results.getRecords(),results.getTotalPage(),results.getTotal(),results.getPage());
for (Students s : rowsStudents) {
_logger.info("Students "+s);
}
}
@BeforeAll
public static void initSpringContext(){
if(InitContext.context!=null) return;
service = new InitContext().init();
}
}
\ No newline at end of file
/*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.mybatis.jpa.test;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.dromara.mybatis.jpa.test.dao.service.StudentsService;
import org.dromara.mybatis.jpa.test.entity.Students;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FindTestRunner {
private static final Logger _logger = LoggerFactory.getLogger(FindTestRunner.class);
public static StudentsService service;
@Test
void findAll() throws Exception{
_logger.info("findAll...");
List<Students> allListStudents =service.findAll();
for (Students s : allListStudents) {
_logger.info("Students "+s);
}
}
@Test
void findByIds() throws Exception{
_logger.info("findByIds...");
List<String> idList=new ArrayList<String>();
idList.add("8c34448b-c65b-4a4e-a0da-83284d05f909");
idList.add("b9111f83-d338-461d-8d46-f331087d5a42");
idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c");
idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe");
service.findByIds(idList);
}
@Test
void find() throws Exception{
_logger.info("find by filter StdNo = '10024' or StdNo = '10004'");
List<Students> listStudents = service.find(
" StdNo = ? or StdNo = ? ",
new Object[]{"10024","10004"},
new int[]{Types.VARCHAR,Types.INTEGER}
);
for (Students s : listStudents) {
_logger.info("Students {}" , s);
}
}
@BeforeAll
public static void initSpringContext(){
if(InitContext.context!=null) return;
service = new InitContext().init();
}
}
\ No newline at end of file
/*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dromara.mybatis.jpa.test;
import java.util.ArrayList;
import java.util.List;
import org.dromara.mybatis.jpa.test.dao.service.StudentsService;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogicDeleteTestRunner {
private static final Logger _logger = LoggerFactory.getLogger(LogicDeleteTestRunner.class);
public static StudentsService service;
@Test
void logicDelete() throws Exception{
_logger.info("batchDeleteByIds...");
service.logicDelete("2");
service.logicDelete("2,639178432667713536");
}
@Test
void logicBatchDelete() throws Exception{
_logger.info("logicDelete...");
List<String> idList=new ArrayList<String>();
idList.add("8584804d-b5ac-45d2-9f91-4dd8e7a090a7");
idList.add("ab7422e9-a91a-4840-9e59-9d911257c918");
idList.add("12b6ceb8-573b-4f01-ad85-cfb24cfa007c");
idList.add("dafd5ba4-d2e3-4656-bd42-178841e610fe");
service.logicDelete(idList);
}
@Test
void logicDeleteSplit() throws Exception{
_logger.info("batchDeleteByIds...");
service.logicDeleteSplit("2,639178432667713536",",");
}
@BeforeAll
public static void initSpringContext(){
if(InitContext.context!=null) return;
service = new InitContext().init();
}
}
\ No newline at end of file
......@@ -17,7 +17,6 @@
package org.dromara.mybatis.jpa.test;
import java.sql.Types;
import java.util.List;
import org.dromara.mybatis.jpa.query.Query;
......@@ -34,7 +33,7 @@ public class QueryTestRunner {
public static StudentsService service;
@Test
public void query() throws Exception{
void query() throws Exception{
_logger.info("find...");
List<Students> listStudents =service.query(new Students("10024"));
for (Students s : listStudents) {
......@@ -44,7 +43,7 @@ public class QueryTestRunner {
//WHERE (stdMajor = '政治' and STDAGE > 30 and stdMajor in ( '政治' , '化学' ) or ( stdname = '周瑜' or stdname = '吕蒙' ) )
@Test
public void queryByCondition() throws Exception{
void queryByCondition() throws Exception{
_logger.info("query by condition ...");
List<Students> listStudents =service.query(
new Query().eq("stdMajor", "政治").and().gt("STDAGE", 30).and().in("stdMajor", new Object[]{"政治","化学"})
......@@ -54,21 +53,6 @@ public class QueryTestRunner {
}
}
@Test
public void find() throws Exception{
_logger.info("find by filter StdNo = '10024' or StdNo = '10004'");
List<Students> listStudents = service.find(
" StdNo = ? or StdNo = ? ",
new Object[]{"10024","10004"},
new int[]{Types.VARCHAR,Types.INTEGER}
);
for (Students s : listStudents) {
_logger.info("Students {}" , s);
}
}
@BeforeAll
public static void initSpringContext(){
if(InitContext.context!=null) return;
......
......@@ -5,14 +5,14 @@
<parent>
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-parent</artifactId>
<version>3.1</version>
<version>3.2</version>
<relativePath>../pom.xml</relativePath>
</parent>
<!--self -->
<artifactId>mybatis-jpa-extra</artifactId>
<name>mybatis-jpa-extra</name>
<description>mybatis-jpa-extra</description>
<description>扩展MyBatis JPA支持,简化CUID操作,增强SELECT分页查询</description>
<url>https://github.com/MaxKeyTop/mybatis-jpa-extra</url>
<dependencies>
......
......@@ -44,6 +44,12 @@ public interface IJpaMapper<T> {
@SelectProvider(type = MapperSqlProvider.class, method = "findAll")
public List<T> findAll(@Param (MapperMetadata.ENTITY_CLASS)Class<?> entityClass);
@SelectProvider(type = MapperSqlProvider.class, method = "findByIds")
public List<T> findByIds(
@Param (MapperMetadata.ENTITY_CLASS) Class<?> entityClass,
@Param (MapperMetadata.PARAMETER_ID_LIST) List<String> idList,
@Param (MapperMetadata.PARAMETER_PARTITION_KEY) String partitionKey);
@SelectProvider(type = MapperSqlProvider.class, method = "fetchCount")
public Integer fetchCount(JpaPage page);
......@@ -59,6 +65,11 @@ public interface IJpaMapper<T> {
@Param (MapperMetadata.CONDITION) Query query,
@Param (MapperMetadata.ENTITY_CLASS)Class<?> entityClass);
//
public List<T> fetchPageResults(T entity);
public List<T> fetchPageResults(@Param (MapperMetadata.PAGE) JpaPage page ,@Param (MapperMetadata.ENTITY) T entity);
/**
* query by id
* @param id
......
......@@ -19,7 +19,10 @@ package org.dromara.mybatis.jpa;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import org.dromara.mybatis.jpa.entity.JpaPage;
import org.dromara.mybatis.jpa.entity.JpaPageResults;
......@@ -111,9 +114,7 @@ public class JpaService <T extends JpaEntity> {
}
} catch(Exception e) {
logger.error("getMapper Exception " , e);
} finally {
}
}
return mapper;
}
......@@ -147,11 +148,25 @@ public class JpaService <T extends JpaEntity> {
* @return
*/
public JpaPageResults<T> fetchPageResults(T entity) {
return fetchPageResults("fetchPageResults" , null , entity);
try {
beforePageResults(entity);
List<T> resultslist = getMapper().fetchPageResults(entity);
return buildPageResults(entity , resultslist);
}catch (Exception e) {
logger.error("fetchPageResults Exception " , e);
}
return null;
}
public JpaPageResults<T> fetchPageResults(JpaPage page , T entity) {
return fetchPageResults("fetchPageResults" , page , entity);
try {
beforePageResults(entity);
List<T> resultslist = getMapper().fetchPageResults(page , entity);
return buildPageResults(entity , resultslist);
}catch (Exception e) {
logger.error("fetchPageResults page Exception " , e);
}
return null;
}
/**
......@@ -176,20 +191,20 @@ public class JpaService <T extends JpaEntity> {
page == null ? new Object[]{entity} : new Object[]{page , entity});
return buildPageResults(entity , resultslist);
}catch (NoSuchMethodException e) {
logger.error("Mapper no queryPageResults Method Exception " , e);
logger.error("Mapper no fetchPageResults Method Exception " , e);
}catch (Exception e) {
logger.error("queryPageResults Exception " , e);
logger.error("fetchPageResults Exception " , e);
}
return null;
}
private void beforePageResults(JpaPage page) {
protected void beforePageResults(JpaPage page) {
page.setPageResultSelectUUID(page.generateId());
page.setStartRow(calculateStartRow(page.getPageNumber() ,page.getPageSize()));
page.setPageable(true);
}
private JpaPageResults<T> buildPageResults(JpaPage page , List<T> resultslist) {
protected JpaPageResults<T> buildPageResults(JpaPage page , List<T> resultslist) {
page.setPageable(false);
Integer totalPage = resultslist.size();
......@@ -200,7 +215,7 @@ public class JpaService <T extends JpaEntity> {
totalCount = parseCount(getMapper().fetchCount(page));
}
return new JpaPageResults<T>(page.getPageNumber(),page.getPageSize(),totalPage,totalCount,resultslist);
return new JpaPageResults<>(page.getPageNumber(),page.getPageSize(),totalPage,totalCount,resultslist);
}
/**
......@@ -235,7 +250,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("query Exception " , e);
}
return null;
return Collections.emptyList();
}
/**
......@@ -250,7 +265,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("query Exception " , e);
}
return null;
return Collections.emptyList();
}
/**
......@@ -263,7 +278,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("findAll Exception" , e);
}
return null;
return Collections.emptyList();
}
......@@ -285,7 +300,7 @@ public class JpaService <T extends JpaEntity> {
} catch(Exception e) {
logger.error("findAll Exception " , e);
}
return null;
return Collections.emptyList();
}
/**
......@@ -310,7 +325,7 @@ public class JpaService <T extends JpaEntity> {
public T findOne(String filter , Object[] args , int[] argTypes) {
try {
List<T> findList = find(filter ,args , argTypes);
return (findList == null ||findList.size() == 0) ? null : findList.get(0);
return CollectionUtils.isEmpty(findList) ? null : findList.get(0);
} catch(Exception e) {
logger.error("findAll Exception " , e);
}
......@@ -329,6 +344,74 @@ public class JpaService <T extends JpaEntity> {
return findOne( filter ,null , null);
}
/**
* find entity by id List
* @param idList
* @return List<T>
*/
public List<T> findByIds(List<String> idList) {
try {
logger.trace("findByIds {}" , idList);
List<T> findList = getMapper().findByIds(this.entityClass,idList,null);
logger.trace("findByIds count : {}" , findList.size());
return findList;
} catch(Exception e) {
logger.error("findByIds Exception " , e);
}
return Collections.emptyList();
}
/**
* find entity by id List
* @param idList
* @param partitionKey
* @return List<T>
*/
public List<T> findByIds(List<String> idList,String partitionKey) {
try {
logger.trace("findByIds {} , partitionKey {}" , idList , partitionKey);
List<T> findList = getMapper().findByIds(this.entityClass , idList , partitionKey);
logger.debug("findByIds count : {}" , findList.size());
return findList;
} catch(Exception e) {
logger.error("findByIds Exception " , e);
}
return Collections.emptyList();
}
/**
* find entity by ids,split with ,
* @param ids
* @return List<T>
*/
public List<T> findByIds(String ids) {
List<String> idList = StringUtils.string2List(ids, ",");
return findByIds(idList);
}
/**
* find entity by ids,split with ,
* @param ids
* @param partitionKey
* @return
*/
public List<T> findByIds(String ids,String partitionKey) {
List<String> idList = StringUtils.string2List(ids, ",");
return findByIds(idList,partitionKey);
}
/**
* find entity by ids , split with ,
* @param ids
* @param split
* @return List<T>
*/
public List<T> findByIdsSplit(String ids , String split) {
List<String> idList = StringUtils.string2List(ids, StringUtils.isBlank(split)? "," : split );
return findByIds(idList);
}
/**
* query one entity by entity id
* @param id
......
......@@ -51,11 +51,12 @@ public class MyBatisJpaSessionFactoryBean extends SqlSessionFactoryBean {
this.dialect = dialect;
}
@Override
protected SqlSessionFactory buildSqlSessionFactory() throws Exception {
SqlSessionFactory factory = super.buildSqlSessionFactory();
Configuration config = factory.getConfiguration();
logger.debug("buildSqlSessionFactory : {}" , config.toString());
logger.debug("buildSqlSessionFactory : {}" , config);
for (Interceptor interceptor : interceptors) {
config.addInterceptor(interceptor);
}
......
......@@ -20,6 +20,7 @@ package org.dromara.mybatis.jpa.dialect;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import org.dromara.mybatis.jpa.entity.JpaPage;
import org.slf4j.Logger;
......@@ -44,17 +45,17 @@ public abstract class Dialect {
static {
dialectMap=new HashMap<String,String>();
dialectMap=new HashMap<>();
dialectMap.put("db2", "org.dromara.mybatis.jpa.dialect.DB2Dialect");
dialectMap.put("derby", "org.dromara.mybatis.jpa.dialect.DerbyDialect");
dialectMap.put("mysql", "org.dromara.mybatis.jpa.dialect.MySQLDialect");
dialectMap.put(DEFAULT_DIALECT, "org.dromara.mybatis.jpa.dialect.MySQLDialect");
dialectMap.put("oracle", "org.dromara.mybatis.jpa.dialect.OracleDialect");
dialectMap.put("postgresql", "org.dromara.mybatis.jpa.dialect.PostgreSQLDialect");
dialectMap.put("highgo", "org.dromara.mybatis.jpa.dialect.HighgoDialect");
dialectMap.put("sqlserver", "org.dromara.mybatis.jpa.dialect.SQLServerDialect");
_logger.trace("Dialect Mapper : \n"+dialectMap);
_logger.trace("Dialect Mapper : \n{}" ,dialectMap);
}
// constructors and factory methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
......@@ -101,7 +102,7 @@ public abstract class Dialect {
/**
* @return the dialectMap
*/
public static HashMap<String, String> getDialectMap() {
public static Map<String, String> getDialectMap() {
return dialectMap;
}
......
......@@ -107,6 +107,15 @@ public class JpaPage {
@Transient
protected String pageResultSelectUUID;
public JpaPage(){}
public JpaPage(int pageNumber , int pageSize){
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.pageable = true;
}
@JsonIgnore
public int getRows() {
return rows;
......
......@@ -136,7 +136,7 @@ public class JpaPageResults <T>{
public void pageCount(int currentPage,int pageResults,Integer recordsCount){
this.page=currentPage;
//通过总记录数和每页显示记录数计算出当前页记录数
this.total =(int) ((recordsCount%pageResults>0)?recordsCount/pageResults+1:recordsCount/pageResults);
this.total =((recordsCount%pageResults>0)?recordsCount/pageResults+1:recordsCount/pageResults);
this.records = Long.parseLong(recordsCount+"");
}
/**
......
......@@ -2,14 +2,14 @@ package org.dromara.mybatis.jpa.id;
public class IdStrategy {
public static final String SERIAL = "serial";
public static final String SERIAL = "serial";
public static final String UUID = "uuid";
public static final String UUIDHEX = "uuid.hex";
public static final String UUIDHEX = "uuid.hex";
public static final String SNOWFLAKEID = "snowflakeid";
public static final String SNOWFLAKEID = "snowflakeid";
public static final String DEFAULT = "default";
public static final String DEFAULT = "default";
}
......@@ -25,7 +25,7 @@ public class IdentifierGeneratorFactory {
private static final Logger logger = LoggerFactory.getLogger(IdentifierGeneratorFactory.class);
public static ConcurrentHashMap<String, IdentifierGenerator>identifierGeneratorMap = new ConcurrentHashMap<String, IdentifierGenerator>();
public static ConcurrentHashMap<String, IdentifierGenerator> identifierGeneratorMap = new ConcurrentHashMap<>();
public IdentifierGeneratorFactory() {
register(IdStrategy.UUID , new UUIDGenerator());
......
......@@ -37,28 +37,28 @@ public class SnowFlakeIdGenerator implements IdentifierGenerator{
/**
* 起始的时间戳
*/
private final static long START_STMP = 1480166465631L;
private static final long START_STMP = 1480166465631L;
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
private static final long SEQUENCE_BIT = 12; //序列号占用的位数
private static final long MACHINE_BIT = 5; //机器标识占用的位数
private static final long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
private static final long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private static final long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private static final long MACHINE_LEFT = SEQUENCE_BIT;
private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private static final long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
......@@ -165,11 +165,11 @@ public class SnowFlakeIdGenerator implements IdentifierGenerator{
int sequenceStart = (int) (len < MACHINE_LEFT ? 0 : len - MACHINE_LEFT);
int workerStart = (int) (len < DATACENTER_LEFT ? 0 : len - DATACENTER_LEFT);
int timeStart = (int) (len < TIMESTMP_LEFT ? 0 : len - TIMESTMP_LEFT);
String sequence = sonwFlakeId.substring(sequenceStart, len);
String parseSequence = sonwFlakeId.substring(sequenceStart, len);
String workerId = sequenceStart == 0 ? "0" : sonwFlakeId.substring(workerStart, sequenceStart);
String dataCenterId = workerStart == 0 ? "0" : sonwFlakeId.substring(timeStart, workerStart);
String time = timeStart == 0 ? "0" : sonwFlakeId.substring(0, timeStart);
int sequenceInt = Integer.valueOf(sequence, 2);
int sequenceInt = Integer.valueOf(parseSequence, 2);
int workerIdInt = Integer.valueOf(workerId, 2);
int dataCenterIdInt = Integer.valueOf(dataCenterId, 2);
long diffTime = Long.parseLong(time, 2);
......
......@@ -30,7 +30,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractStatementHandlerInterceptor implements Interceptor {
protected Logger logger = LoggerFactory.getLogger(getClass());
private Logger logger = LoggerFactory.getLogger(getClass());
protected Dialect dialect;
......@@ -62,8 +62,7 @@ public abstract class AbstractStatementHandlerInterceptor implements Intercepto
StatementHandler statement = (StatementHandler) invocation.getTarget();
if (statement instanceof RoutingStatementHandler) {
MetaObject metaObject = SystemMetaObject.forObject(statement);
StatementHandler statementHandler = (StatementHandler)metaObject.getValue("delegate");
return statementHandler;
return (StatementHandler)metaObject.getValue("delegate");
}
return statement;
......@@ -71,8 +70,7 @@ public abstract class AbstractStatementHandlerInterceptor implements Intercepto
protected RowBounds getRowBounds(StatementHandler statement) {
MetaObject metaObject = SystemMetaObject.forObject(statement);
RowBounds rowBounds=(RowBounds)metaObject.getValue("rowBounds");
return rowBounds;
return (RowBounds)metaObject.getValue("rowBounds");
}
protected boolean hasBounds(RowBounds rowBounds) {
......
......@@ -48,7 +48,7 @@ import org.slf4j.LoggerFactory;
})
public class AllStatementHandlerInterceptor extends
AbstractStatementHandlerInterceptor implements Interceptor {
protected static Logger logger = LoggerFactory.getLogger(AllStatementHandlerInterceptor.class);
private static Logger logger = LoggerFactory.getLogger(AllStatementHandlerInterceptor.class);
public Object intercept(Invocation invocation) throws Throwable {
Method m = invocation.getMethod();
......
......@@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory;
@Intercepts( {
@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class ,Integer.class })})
public class StatementHandlerInterceptor extends AbstractStatementHandlerInterceptor implements Interceptor {
protected static Logger logger = LoggerFactory.getLogger(StatementHandlerInterceptor.class);
private static Logger logger = LoggerFactory.getLogger(StatementHandlerInterceptor.class);
public Object intercept(Invocation invocation) throws Throwable {
Method m = invocation.getMethod();
......@@ -73,8 +73,8 @@ public class StatementHandlerInterceptor extends AbstractStatementHandlerInterce
//判断是否select语句及需要分页支持
if (sql.toLowerCase().trim().startsWith("select")) {
JpaPage page = null;
if((parameterObject instanceof JpaPage)) {
page = (JpaPage)parameterObject;
if((parameterObject instanceof JpaPage parameterObjectPage)) {
page = parameterObjectPage;
}else if((parameterObject instanceof ParamMap)
&& ((ParamMap<?>)parameterObject).containsKey(MapperMetadata.PAGE)) {
page = (JpaPage)((ParamMap<?>)parameterObject).get(MapperMetadata.PAGE);
......@@ -90,7 +90,8 @@ public class StatementHandlerInterceptor extends AbstractStatementHandlerInterce
}
//分页标识
if(page != null && page.isPageable()){
logger.trace("prepare boundSql ==> {}" , removeBreakingWhitespace(sql));
String boundSqlRemoveBreakingWhitespace = removeBreakingWhitespace(sql);
logger.trace("prepare boundSql ==> {}" , boundSqlRemoveBreakingWhitespace);
if(statement instanceof SimpleStatementHandler){
sql = dialect.getLimitString(sql, page);
}else if(statement instanceof PreparedStatementHandler){
......@@ -100,7 +101,7 @@ public class StatementHandlerInterceptor extends AbstractStatementHandlerInterce
);
sql = dialect.getLimitString(sql, page);
}
logger.trace("prepare dialect boundSql : {}" , removeBreakingWhitespace(sql));
logger.trace("prepare dialect boundSql : {}" , boundSqlRemoveBreakingWhitespace);
metaObject.setValue("boundSql.sql", sql);
}
}
......
......@@ -91,12 +91,11 @@ public class MapperMetadata <T extends JpaEntity>{
}
public static ConcurrentMap<String, List<FieldColumnMapper>>
fieldsMap = new ConcurrentHashMap<String, List<FieldColumnMapper>>();
public static ConcurrentMap<String, List<FieldColumnMapper>> fieldsMap = new ConcurrentHashMap<>();
public static ConcurrentMap<String, String>sqlsMap = new ConcurrentHashMap<String, String>();
public static ConcurrentMap<String, String>sqlsMap = new ConcurrentHashMap<>();
public static ConcurrentMap<String, String>tableNameMap = new ConcurrentHashMap<String, String>();
public static ConcurrentMap<String, String>tableNameMap = new ConcurrentHashMap<>();
public static IdentifierGeneratorFactory identifierGeneratorFactory = new IdentifierGeneratorFactory();
......@@ -115,9 +114,9 @@ public class MapperMetadata <T extends JpaEntity>{
String schema = null;
String catalog = null;
//must use @Entity to ORM class
Entity entity =(Entity)entityClass.getAnnotation(Entity.class);
Entity entity = entityClass.getAnnotation(Entity.class);
logger.trace("entity {}" , entity);
Table table = (Table)entityClass.getAnnotation(Table.class);
Table table = entityClass.getAnnotation(Table.class);
logger.trace("table {}" , table);
if(entity != null ) {
if(entity.name() != null && !entity.name().equals("")) {
......@@ -242,7 +241,7 @@ public class MapperMetadata <T extends JpaEntity>{
logger.trace("entityClass {}" , entityClass);
Field[] fields = entityClass.getDeclaredFields();
List<FieldColumnMapper>fieldColumnMapperList=new ArrayList<FieldColumnMapper>(fields.length);
List<FieldColumnMapper>fieldColumnMapperList=new ArrayList<>(fields.length);
for (Field field : fields) {
//skip Transient field
......@@ -251,11 +250,11 @@ public class MapperMetadata <T extends JpaEntity>{
}
if (field.isAnnotationPresent(Column.class)) {
FieldColumnMapper fieldColumnMapper=new FieldColumnMapper();
FieldColumnMapper fieldColumnMapper = new FieldColumnMapper();
fieldColumnMapper.setFieldName( field.getName());
fieldColumnMapper.setFieldType(field.getType().getSimpleName());
String columnName = "";
Column columnAnnotation = (Column) field.getAnnotation(Column.class);
Column columnAnnotation = field.getAnnotation(Column.class);
fieldColumnMapper.setColumnAnnotation(columnAnnotation);
if (columnAnnotation.name() != null && !columnAnnotation.name().equals("")) {
columnName = columnAnnotation.name();
......
/*
* Copyright [2021] [MaxKey of copyright http://www.maxkey.top]
* Copyright [2023] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
......@@ -114,53 +114,5 @@ public class DeleteProvider <T extends JpaEntity>{
logger.trace("Delete SQL \n{}" , deleteSql);
return deleteSql;
}
@SuppressWarnings("unchecked")
public String logicDelete(Map<String, Object> parametersMap) {
Class<?> entityClass=(Class<?>)parametersMap.get(MapperMetadata.ENTITY_CLASS);
MapperMetadata.buildColumnList(entityClass);
String tableName = MapperMetadata.getTableName(entityClass);
ArrayList <String> idValues=(ArrayList<String>)parametersMap.get(MapperMetadata.PARAMETER_ID_LIST);
StringBuffer keyValue = new StringBuffer();
for(String value : idValues) {
if(value.trim().length() > 0) {
keyValue.append(",'").append(value).append("'");
logger.trace("logic delete by id {}" , value);
}
}
String keyValues = keyValue.substring(1).replaceAll(";", "");//remove ;
FieldColumnMapper logicColumnMapper = MapperMetadata.getLogicColumn((entityClass).getSimpleName());
String partitionKeyValue = (String) parametersMap.get(MapperMetadata.PARAMETER_PARTITION_KEY);
FieldColumnMapper partitionKeyColumnMapper = MapperMetadata.getPartitionKey((entityClass).getSimpleName());
FieldColumnMapper idFieldColumnMapper = MapperMetadata.getIdColumn(entityClass.getSimpleName());
SQL sql=new SQL()
.UPDATE(tableName)
.SET(" %s = %s ".formatted(
logicColumnMapper.getColumnName(),
logicColumnMapper.getColumnLogic().delete()
)
);
if(partitionKeyColumnMapper != null && partitionKeyValue != null) {
sql.WHERE("%s = #{%s} and %s in ( %s )"
.formatted(
partitionKeyColumnMapper.getColumnName() ,
partitionKeyValue,
idFieldColumnMapper.getColumnName(),
idFieldColumnMapper.getFieldName())
);
}else {
sql.WHERE(" %s in ( %s )".formatted(idFieldColumnMapper.getColumnName(),keyValues));
}
String deleteSql = sql.toString();
MapperMetadata.sqlsMap.put(tableName + SQL_TYPE.LOGICDELETE_SQL,deleteSql);
logger.trace("logic Delete SQL \n{}" , deleteSql);
return deleteSql;
}
}
......@@ -58,7 +58,7 @@ public class FetchCountProvider <T extends JpaEntity>{
//多个空格 tab 替换成1个空格
String selectSql = StringUtils.lineBreak2Blank(pageResultsSqlCache.getSql());
BoundSql boundSql = (BoundSql)pageResultsSqlCache.getBoundSql();
BoundSql boundSql = pageResultsSqlCache.getBoundSql();
logger.trace("Count original SQL :\n{}" , selectSql);
StringBuffer sql = new StringBuffer(SqlSyntaxConstants.SELECT +" "+ SqlSyntaxConstants.Functions.COUNT_ONE +" countrows_ ");
......
......@@ -21,6 +21,7 @@
package org.dromara.mybatis.jpa.provider;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
......@@ -84,7 +85,7 @@ public class FindProvider <T extends JpaEntity>{
throw new Exception("args length < parameter placeholder");
}
String filterSqls [] = filterSql.split("\\?");
String[] filterSqls = filterSql.split("\\?");
StringBuffer sqlBuffer = new StringBuffer("");
for(int i = 0 ;i < args.length ; i++){
logger.trace("Find args[{}] {}" , i, args[i]);
......@@ -116,4 +117,41 @@ public class FindProvider <T extends JpaEntity>{
return findSql;
}
public String findByIds(Map<String, Object> parametersMap) {
Class<?> parameterEntityClass = (Class<?>)parametersMap.get(MapperMetadata.ENTITY_CLASS);
MapperMetadata.buildColumnList(parameterEntityClass);
ArrayList <String> parameterIds = (ArrayList<String>)parametersMap.get(MapperMetadata.PARAMETER_ID_LIST);
StringBuffer keyValue = new StringBuffer();
for(String value : parameterIds) {
if(value.trim().length() > 0) {
keyValue.append(",'").append(value).append("'");
logger.trace("find by id {}" , value);
}
}
String idsValues = keyValue.substring(1).replaceAll(";", "");//remove ;
String partitionKeyValue = (String) parametersMap.get(MapperMetadata.PARAMETER_PARTITION_KEY);
FieldColumnMapper partitionKeyColumnMapper = MapperMetadata.getPartitionKey((parameterEntityClass).getSimpleName());
FieldColumnMapper idFieldColumnMapper = MapperMetadata.getIdColumn(parameterEntityClass.getSimpleName());
SQL sql = MapperMetadata.buildSelect(parameterEntityClass);
if(partitionKeyColumnMapper != null && partitionKeyValue != null) {
sql.WHERE("%s = #{%s} and %s in ( %s )"
.formatted(
partitionKeyColumnMapper.getColumnName() ,
partitionKeyValue,
idFieldColumnMapper.getColumnName(),
idsValues)
);
}else {
sql.WHERE(" %s in ( %s )".formatted(idFieldColumnMapper.getColumnName(),idsValues));
}
String findByIdsSql = sql.toString();
logger.trace("Find by ids SQL \n{}" , findByIdsSql);
return findByIdsSql;
}
}
/*
* Copyright [2023] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
*/
package org.dromara.mybatis.jpa.provider;
import java.util.ArrayList;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import org.dromara.mybatis.jpa.entity.JpaEntity;
import org.dromara.mybatis.jpa.metadata.FieldColumnMapper;
import org.dromara.mybatis.jpa.metadata.MapperMetadata;
import org.dromara.mybatis.jpa.metadata.MapperMetadata.SQL_TYPE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Crystal.Sea
*
*/
public class LogicDeleteProvider <T extends JpaEntity>{
private static final Logger logger = LoggerFactory.getLogger(LogicDeleteProvider.class);
@SuppressWarnings("unchecked")
public String logicDelete(Map<String, Object> parametersMap) {
Class<?> entityClass=(Class<?>)parametersMap.get(MapperMetadata.ENTITY_CLASS);
MapperMetadata.buildColumnList(entityClass);
String tableName = MapperMetadata.getTableName(entityClass);
ArrayList <String> idValues=(ArrayList<String>)parametersMap.get(MapperMetadata.PARAMETER_ID_LIST);
StringBuffer keyValue = new StringBuffer();
for(String value : idValues) {
if(value.trim().length() > 0) {
keyValue.append(",'").append(value).append("'");
logger.trace("logic delete by id {}" , value);
}
}
String keyValues = keyValue.substring(1).replaceAll(";", "");//remove ;
FieldColumnMapper logicColumnMapper = MapperMetadata.getLogicColumn((entityClass).getSimpleName());
String partitionKeyValue = (String) parametersMap.get(MapperMetadata.PARAMETER_PARTITION_KEY);
FieldColumnMapper partitionKeyColumnMapper = MapperMetadata.getPartitionKey((entityClass).getSimpleName());
FieldColumnMapper idFieldColumnMapper = MapperMetadata.getIdColumn(entityClass.getSimpleName());
SQL sql=new SQL()
.UPDATE(tableName)
.SET(" %s = %s ".formatted(
logicColumnMapper.getColumnName(),
logicColumnMapper.getColumnLogic().delete()
)
);
if(partitionKeyColumnMapper != null && partitionKeyValue != null) {
sql.WHERE("%s = #{%s} and %s in ( %s )"
.formatted(
partitionKeyColumnMapper.getColumnName() ,
partitionKeyValue,
idFieldColumnMapper.getColumnName(),
idFieldColumnMapper.getFieldName())
);
}else {
sql.WHERE(" %s in ( %s )".formatted(idFieldColumnMapper.getColumnName(),keyValues));
}
String deleteSql = sql.toString();
MapperMetadata.sqlsMap.put(tableName + SQL_TYPE.LOGICDELETE_SQL,deleteSql);
logger.trace("logic Delete SQL \n{}" , deleteSql);
return deleteSql;
}
}
......@@ -48,6 +48,10 @@ public class MapperSqlProvider <T extends JpaEntity>{
return new FindProvider().find(parametersMap);
}
public String findByIds(Map<String, Object> parametersMap) {
return new FindProvider().findByIds(parametersMap);
}
public String findAll(Map<String, Object> parametersMap) {
return new FindProvider().findAll(parametersMap);
}
......@@ -61,7 +65,7 @@ public class MapperSqlProvider <T extends JpaEntity>{
}
public String logicDelete(Map<String, Object> parametersMap) {
return new DeleteProvider().logicDelete(parametersMap);
return new LogicDeleteProvider().logicDelete(parametersMap);
}
/**
......
......@@ -44,7 +44,7 @@ public class QueryProvider<T extends JpaEntity> {
if (query.getOrderBy() != null) {
sql.ORDER_BY(QueryBuilder.buildOrderBy(query));
}
logger.trace("filter By Query SQL \n{}" , sql.toString());
logger.trace("filter By Query SQL \n{}" , sql);
return sql.toString();
}
......@@ -70,12 +70,12 @@ public class QueryProvider<T extends JpaEntity> {
|| (fieldType.equals("Integer")&& fieldValue.equals("0"))
|| (fieldType.equals("Float")&& fieldValue.equals("0.0"))
|| (fieldType.equals("Double")&& fieldValue.equals("0.0"))){
// skip default field value
}else {
sql.WHERE(fieldColumnMapper.getColumnName() + " = #{" + fieldColumnMapper.getFieldName() + "}");
}
}
logger.trace("filter By Entity SQL \n{}" , sql.toString());
logger.trace("filter By Entity SQL \n{}" , sql);
return sql.toString();
}
......
package org.dromara.mybatis.jpa.query;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
public class Query {
......@@ -11,7 +14,7 @@ public class Query {
public static final String DESC = "desc";
}
ArrayList<Condition> conditions = new ArrayList<Condition>();
ArrayList<Condition> conditions = new ArrayList<>();
ArrayList<Condition> groupBy ;
......@@ -21,23 +24,23 @@ public class Query {
super();
}
public Query builder(){
public static Query builder(){
return new Query();
}
public ArrayList<Condition> getConditions() {
public List<Condition> getConditions() {
return conditions;
}
public ArrayList<Condition> getOrderBy() {
public List<Condition> getOrderBy() {
return orderBy;
}
public void joint() {
if(conditions.size() >= 1) {
if(CollectionUtils.isNotEmpty(conditions)) {
Operator lastJoint = conditions.get(conditions.size() -1).getExpression();
if(lastJoint.equals(Operator.and)
||lastJoint.equals(Operator.or)) {
||lastJoint.equals(Operator.or)){
}else {
and();
}
......@@ -310,7 +313,7 @@ public class Query {
* @param value
* @return Query
*/
public Query isNotNull(String column, Object value) {
public Query isNotNull(String column) {
joint();
conditions.add(new Condition(Operator.isNotNull,column,null));
return this;
......@@ -354,7 +357,7 @@ public class Query {
public Query groupBy(String column) {
if(groupBy == null) {
this.groupBy = new ArrayList<Condition>();
this.groupBy = new ArrayList<>();
}
groupBy.add(new Condition(Operator.group,column,""));
return this;
......@@ -362,13 +365,13 @@ public class Query {
public Query orderBy(String column,String orderType) {
if(orderBy == null) {
this.orderBy = new ArrayList<Condition>();
this.orderBy = new ArrayList<>();
}
orderBy.add(new Condition(Operator.order,column,orderType));
return this;
}
public ArrayList<Condition> getGroupBy() {
public List<Condition> getGroupBy() {
return groupBy;
}
......
......@@ -27,6 +27,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.LogFactory;
public class BeanUtil {
......@@ -65,10 +66,7 @@ public class BeanUtil {
@SuppressWarnings("rawtypes")
public static boolean isNotNull(Collection collection) {
if(collection != null && collection.size() > 0) {
return true;
}
return false;
return CollectionUtils.isNotEmpty(collection);
}
@SuppressWarnings("rawtypes")
......
......@@ -25,6 +25,8 @@ import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
......@@ -32,42 +34,41 @@ import org.slf4j.LoggerFactory;
*
*/
public class MacAddress {
public static String os;
private static final Logger logger = LoggerFactory.getLogger(MacAddress.class);
public static final String os;
static{
Properties prop = System.getProperties();
os = prop.getProperty("os.name");
LoggerFactory.getLogger(MacAddress.class).info("OS : "+os);
logger.info("OS : {}" , os);
}
public static String getAllHostMacAddress(){
String hostIpAddress="";
StringBuilder hostIpAddress = new StringBuilder();
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress inetAddress = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
NetworkInterface ni = netInterfaces.nextElement();
if(ni.getInetAddresses().hasMoreElements()){
inetAddress = (InetAddress) ni.getInetAddresses().nextElement();
inetAddress = ni.getInetAddresses().nextElement();
if(!inetAddress.isLoopbackAddress()){
hostIpAddress += getMac(inetAddress)+",";
LoggerFactory.getLogger(MacAddress.class).info("host MAC : "+getMac(inetAddress));
hostIpAddress.append(getMac(inetAddress)).append(",");
logger.info("host MAC : {}" ,getMac(inetAddress));
}
}
}
} catch (SocketException e) {
e.printStackTrace();
logger.error("Socket Exception",e);
}
return hostIpAddress;
return hostIpAddress.toString();
}
public static String getMac(InetAddress ia) throws SocketException {
//获取网卡,获取地址
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
//LoggerFactory.getLogger(MacAddress.class).info("mac数组长度:"+mac.length);
StringBuffer sb = new StringBuffer("");
for(int i=0; i<mac.length; i++) {
if(i!=0) {
......
......@@ -64,7 +64,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
if (string != null && !string.equals("")) {
strs = string.split(split);
}
ArrayList<String> resultList = new ArrayList<String>(0);
ArrayList<String> resultList = new ArrayList<>(0);
for (int i = 0; i < strs.length; i++) {
if (strs[i] != null&& !strs[i].equals("")) {
resultList.add(strs[i]);
......
......@@ -4,19 +4,18 @@
<!--parent -->
<groupId>org.dromara.mybatis-jpa-extra</groupId>
<artifactId>mybatis-jpa-extra-parent</artifactId>
<version>3.1</version>
<version>3.2</version>
<packaging>pom</packaging>
<!--modules -->
<modules>
<module>mybatis-jpa-extra-core</module>
<module>mybatis-jpa-extra</module>
<module>mybatis-jpa-extra-spring-boot-starter</module>
<module>mybatis-jpa-extra-test</module>
<module>mybatis-jpa-extra-spring-boot-starter-test</module>
</modules>
<properties>
<mybatis.jpa.extra.version>3.1</mybatis.jpa.extra.version><!--project version-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.version>17</jdk.version>
<servlet-api.version>6.0.0</servlet-api.version>
......@@ -57,7 +56,7 @@
</properties>
<name>mybatis-jpa-extra</name>
<description>简化MyBatis CUID操作,增强SELECT分页查询</description>
<description>mybatis-jpa-extra-parent</description>
<url>https://github.com/dromara/mybatis-jpa-extra</url>
<issueManagement>
......@@ -476,7 +475,7 @@
</execution>
</executions>
</plugin>
<!-- Gpg Signature 本地打包要注释-->
<!-- Gpg Signature 本地打包要注释
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
......@@ -491,7 +490,7 @@
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
</project>
\ No newline at end of file