目录
两段代码比较
Ctrl+Shift+减号 对代码进行折叠
连接数据库生成实体类(适合生成重复性高的代码)
将下面内容复制进去
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
//类型映射
typeMapping = [
(~/(?i)tinyint|smallint|mediumint|int/) : "Integer",
(~/(?i)bool|bit/) : "Boolean",
(~/(?i)float|double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp|date|time/) : "Date",
(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
(~/(?i)/) : "String"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}
def generate(table, dir) {
def className = javaName(table.getName(), true)
def fields = calcFields(table)
//包名
packageName = getPackageName(dir)
//UTF-8编码
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
printWriter.withPrintWriter {out -> generate(out, className, fields)}
}
def getPackageName(dir) {
return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
String genSerialID()
{
return "\tprivate static final long serialVersionUID = "+Math.abs(new Random().nextLong())+"L;"
}
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
commoent: col.getComment(),
]]
}
}
def javaName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
//最终生成输出
def generate(out, className, fields) {
out.println "package $packageName"
out.println ""
out.println "import java.io.Serializable;"
//识别类型生成包名
Set types = new HashSet()
fields.each() {
types.add(it.type)
}
if (types.contains("Date")) {
out.println "import java.util.Date;"
}
if (types.contains("InputStream")) {
out.println "import java.io.InputStream;"
}
out.println ""
out.println "public class $className implements Serializable {"
out.println ""
out.println genSerialID()
out.println ""
fields.each() {
if (it.commoent != "") {
out.println "\t// ${it.commoent.toString()}"
}
out.println "\tprivate ${it.type} ${it.name};"
}
out.println ""
fields.each() {
out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
out.println "\t\treturn ${it.name};"
out.println "\t}"
out.println ""
out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
out.println "\t\tthis.${it.name} = ${it.name};"
out.println "\t}"
out.println ""
}
out.println "}"
}
然后选择生成目录
目标生成格式:
package www.demo.com;
import java.io.Serializable;
public class TUser implements Serializable {
private static final long serialVersionUID = 1972551940242835771L;
// 唯一标识(注:数据库中写了COMMENT的才会有,否则为null)
private Integer id;
// 账号
private String account;
// 用户名
private String userName;
// 密码
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
如果不满意上面的代码可以自定义
如下为自定义的动态sql生成代码
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
//类型映射
typeMapping = [
(~/(?i)tinyint|smallint|mediumint|int/) : "Integer",
(~/(?i)bool|bit/) : "Boolean",
(~/(?i)float|double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp|date|time/) : "Date",
(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
(~/(?i)/) : "String"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}
def generate(table, dir) {
beanName = javaName(table.getName(), true)
//小写
lBeanName = removeCharAt(beanName, 0).toString().toLowerCase()
//首写字母大写
uBeanName = lBeanName.substring(0,1).toUpperCase() + lBeanName.substring(1)
className = beanName + "DynamicSql"
def fields = calcFields(table)
//包名
packageName = getPackageName(dir)
//UTF-8编码
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
printWriter.withPrintWriter {out -> generate(out, className, fields)}
}
static String removeCharAt(String str, int i) {
return str.substring(0, i)+str.substring(i+1);
}
def javaName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
commoent: col.getComment(),
]]
}
}
def getPackageName(dir) {
return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
//最终生成输出
def generate(out, className, fields) {
out.println "package $packageName"
out.println ""
out.println "import www.demo.com.model.$beanName;"
out.println "import www.demo.com.utils.common.StringUtil;"
out.println "import org.apache.ibatis.jdbc.SQL;"
out.println ""
out.println "public class $className " + "{"
//insert
out.println "\tpublic String insert$uBeanName($beanName $lBeanName) {"
out.println "\t\tString s = new SQL() {"
out.println "\t\t\t{"
out.println "\t\t\t\tINSERT_INTO(\"t_$lBeanName\");"
fields.each() {
out.println "\t\t\t\tif (StringUtil.isNotNULL($lBeanName" + ".get${it.name.capitalize()}())) {"
out.println "\t\t\t\t\tVALUES(\"${it.name}\", \"#{${it.name}}\");"
out.println "\t\t\t\t}"
}
out.println "\t\t\t}"
out.println "\t\t}.toString();"
out.println "\t\treturn s;"
out.println "\t}"
//select
out.println "\tpublic String select$uBeanName($beanName $lBeanName) {"
out.println "\t\tString s = new SQL() {"
out.println "\t\t\t{"
out.println "\t\t\t\tSELECT(\"*\");"
out.println "\t\t\t\tFROM(\"t_$lBeanName\");"
fields.each() {
out.println "\t\t\t\tif (StringUtil.isNotNULL($lBeanName" + ".get${it.name.capitalize()}())) {"
out.println "\t\t\t\t\tWHERE(\"${it.name}=#{${it.name}}\");"
out.println "\t\t\t\t}"
}
out.println "\t\t\t}"
out.println "\t\t}.toString();"
out.println "\t\treturn s;"
out.println "\t}"
//update
out.println "\tpublic String update$uBeanName($beanName $lBeanName) {"
out.println "\t\tString s = new SQL() {"
out.println "\t\t\t{"
out.println "\t\t\t\tUPDATE(\"t_$lBeanName\");"
fields.each() {
out.println "\t\t\t\tif (StringUtil.isNotNULL($lBeanName" + ".get${it.name.capitalize()}())) {"
out.println "\t\t\t\t\tSET(\"${it.name}=#{${it.name}}\");"
out.println "\t\t\t\t}"
}
out.println "\t\t\t}"
out.println "\t\t}.toString();"
out.println "\t\treturn s;"
out.println "\t}"
out.println "}"
}
生成效果
package www.demo.com;
import org.apache.ibatis.jdbc.SQL;
import www.demo.com.model.TUser;
import www.demo.com.utils.common.StringUtil;
public class TUserDynamicSql {
public String insertUser(TUser user) {
String s = new SQL() {
{
INSERT_INTO("t_user");
if (StringUtil.isNotNULL(user.getId())) {
VALUES("id", "#{id}");
}
if (StringUtil.isNotNULL(user.getUserName())) {
VALUES("userName", "#{userName}");
}
if (StringUtil.isNotNULL(user.getPassword())) {
VALUES("password", "#{password}");
}
}
}.toString();
return s;
}
public String selectUser(TUser user) {
String s = new SQL() {
{
SELECT("*");
FROM("t_user");
if (StringUtil.isNotNULL(user.getId())) {
WHERE("id=#{id}");
}
if (StringUtil.isNotNULL(user.getUserName())) {
WHERE("userName=#{userName}");
}
if (StringUtil.isNotNULL(user.getPassword())) {
WHERE("password=#{password}");
}
}
}.toString();
return s;
}
public String updateUser(TUser user) {
String s = new SQL() {
{
UPDATE("t_user");
if (StringUtil.isNotNULL(user.getId())) {
SET("id=#{id}");
}
if (StringUtil.isNotNULL(user.getUserName())) {
SET("userName=#{userName}");
}
if (StringUtil.isNotNULL(user.getPassword())) {
SET("password=#{password}");
}
}
}.toString();
return s;
}
}
如下为自定义的动态sql生成代码,有下划线的字段名
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
/*
* Available context bindings:
* SELECTION Iterable<DasObject>
* PROJECT project
* FILES files helper
*/
//类型映射
typeMapping = [
(~/(?i)tinyint|smallint|mediumint|int/) : "Integer",
(~/(?i)bool|bit/) : "Boolean",
(~/(?i)float|double|decimal|real/) : "Double",
(~/(?i)datetime|timestamp|date|time/) : "Date",
(~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
(~/(?i)/) : "String"
]
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}
def generate(table, dir) {
beanName = javaName(table.getName(), true)
lBeanName = removeCharAt(beanName, 0).toString().toLowerCase()
uBeanName = lBeanName.substring(0, 1).toUpperCase() + lBeanName.substring(1)
className = beanName + "DynamicSql"
def fields = calcFields(table)
//包名
packageName = getPackageName(dir)
//UTF-8编码
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
printWriter.withPrintWriter { out -> generate(out, className, fields) }
}
static String removeCharAt(String str, int i) {
return str.substring(0, i) + str.substring(i + 1);
}
def javaName(str, capitalize) {
def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
.collect { Case.LOWER.apply(it).capitalize() }
.join("")
.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
def calcFields(table) {
DasUtil.getColumns(table).reduce([]) { fields, col ->
def spec = Case.LOWER.apply(col.getDataType().getSpecification())
def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
fields += [[
name : javaName(col.getName(), false),
type : typeStr,
commoent: col.getComment(),
]]
}
}
def getPackageName(dir) {
return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}
/***
* 下划线命名转为驼峰命名
*/
static String UnderlineToHump(String para) {
StringBuilder result = new StringBuilder()
String a = para.split("_")
for (String s : a) {
if (!para.contains("_")) {
result.append(s)
continue
}
if (result.length() == 0) {
result.append(s.toLowerCase())
} else {
result.append(s.substring(0, 1).toUpperCase());
result.append(s.substring(1).toLowerCase())
}
}
return result.toString()
}
/***
* 驼峰命名转为下划线命名
*/
static String HumpToUnderline(String para) {
StringBuilder sb = new StringBuilder(para)
int temp = 0
if (!para.contains("_")) {
for (int i = 0; i < para.length(); i++) {
if (Character.isUpperCase(para.charAt(i))) {
sb.insert(i + temp, "_")
temp += 1
}
}
}
return sb.toString().toLowerCase()
}
//最终生成输出
def generate(out, className, fields) {
out.println "package $packageName"
out.println ""
out.println "import www.demo.com.model.$beanName;"
out.println "import www.demo.com.utils.common.StringUtil;"
out.println "import org.apache.ibatis.jdbc.SQL;"
out.println ""
out.println "public class $className " + "{"
//selectPaging
out.println "\tpublic String selectPaging$uBeanName" + "Common(PagePojo pojo, boolean isTotal) {"
out.println "\t\tMap condition = pojo.getCondition();"
out.println "\t\tString s = new SQL() {"
out.println "\t\t\t{"
out.println "\t\t\t\tif (isTotal){"
out.println "\t\t\t\t\tSELECT(\"COUNT(*)\");"
out.println "\t\t\t\t}else {"
out.println "\t\t\t\t\tSELECT(\"*\");"
out.println "\t\t\t\t}"
out.println "\t\t\t\tFROM(\"t_$lBeanName\");"
fields.each() {
String name = it.name
String underLineName = HumpToUnderline(name)
out.println "\t\t\t\tif (StringUtil.isNotNull(condition.get(\"${it.name}\"))) {"
out.println "\t\t\t\t\tWHERE(\"${underLineName}=#{${it.name}}\");"
out.println "\t\t\t\t}"
}
out.println "\t\t\t}"
out.println "\t\t}.toString();"
out.println "\t\treturn s;"
out.println "\t}"
out.println "}"
}
生成效果
public class TUserDynamicSql {
public String selectPagingUserCommon(PagePojo pojo, boolean isTotal) {
Map condition = pojo.getCondition();
String s = new SQL() {
{
if (isTotal){
SELECT("COUNT(*)");
}else {
SELECT("*");
}
FROM("t_user");
if (StringUtil.isNotNull(condition.get("id"))) {
WHERE("id=#{id}");
}
if (StringUtil.isNotNull(condition.get("account"))) {
WHERE("account=#{account}");
}
if (StringUtil.isNotNull(condition.get("userName"))) {
WHERE("user_name=#{userName}");
}
if (StringUtil.isNotNull(condition.get("password"))) {
WHERE("password=#{password}");
}
}
}.toString();
return s;
}
}
HTTP Client
自动生成
手动生成(文件需要放在项目下任意位置)
- http文件:后缀为.http即可
- 通用配置:
- http-client.env.json(公共配置,放不重要的数据)
- http-client.private.env.json(私有配置,放重要的,敏感的数据)
例子:
get-requests.http
### Get request with a header
GET https://httpbin.org/ip
Accept: application/json
### Get request with parameter
GET https://httpbin.org/get?show_env=1
Accept: application/json
### Get request with environment variables
GET {{host}}/get?show_env={{show_env}}
Accept: application/json
###
auth-requests.http
### Basic authorization.
GET https://httpbin.org/basic-auth/user/passwd
Authorization: Basic user passwd
### Basic authorization with variables.
GET https://httpbin.org/basic-auth/user/passwd
Authorization: Basic {{username}} {{password}}
### Digest authorization.
GET https://httpbin.org/digest-auth/realm/user/passwd
Authorization: Digest user passwd
### Digest authorization with variables.
GET https://httpbin.org/digest-auth/realm/user/passwd
Authorization: Digest {{username}} {{password}}
### Authorization by token, part 1. Retrieve and save token.
POST https://httpbin.org/post
Content-Type: application/json
{
"token": "my-secret-token"
}
> {% client.global.set("auth_token", response.body.json.token); %}
### Authorization by token, part 2. Use token to authorize.
GET https://httpbin.org/headers
Authorization: Bearer {{auth_token}}
post-requests.http
### Send POST request with json body
POST https://httpbin.org/post
Content-Type: application/json
{
"id": 999,
"value": "content"
}
### Send POST request with body as parameters
POST https://httpbin.org/post
Content-Type: application/x-www-form-urlencoded
id=999&value=content
### Send a form with the text and file fields
POST https://httpbin.org/post
Content-Type: multipart/form-data; boundary=WebAppBoundary
--WebAppBoundary
Content-Disposition: form-data; name="element-name"
Content-Type: text/plain
Name
--WebAppBoundary
Content-Disposition: form-data; name="data"; filename="data.json"
Content-Type: application/json
< ./request-form-data.json
--WebAppBoundary--
test-responses.http
### Successful test: check response status is 200
GET https://httpbin.org/status/200
> {%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
});
%}
### Failed test: check response status is 200
GET https://httpbin.org/status/404
> {%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
});
%}
### Check response status and content-type
GET https://httpbin.org/get
> {%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
});
client.test("Response content-type is json", function() {
var type = response.contentType.mimeType;
client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'");
});
%}
### Check response body
GET https://httpbin.org/get
> {%
client.test("Headers option exists", function() {
client.assert(response.body.hasOwnProperty("headers"), "Cannot find 'headers' option in response");
});
%}
http-client.env.json
{
"test": {
"host": "https://httpbin.org",
"show_env": "1",
// Define all sensitive information in http-client.private.env.json
"username": "",
"password": ""
}
}
http-client.private.env.json
{
"test": {
"username": "user",
"password": "passwd"
}
}