官方地址:https://projectlombok.org/
GitHub:https://github.com/rzwitserloot/lombok
指導說明文檔:http://jnb.ociweb.com/jnb/jnbJan2010.html
===============================================================================================================
本來來說,lombok作為一個目前為止【2017-11-27】java並未將其作為標准來推廣。還有很多人問使用它是否合適。
這里不做這種討論!!!
===============================================================================================================
在使用之前,要明確一點,在開發過程中,一般情況下,僅使用@Data 即可滿足生成entity類的大部分情況。
摘自指導文檔:
Essentially, using @Data on a class is the same as annotating the class with a default @ToString and @EqualsAndHashCode as well as annotating each field with both @Getter and @Setter.
實質上,在一個類上使用@Data與用默認的@ToString和@EqualsAndHashCode注釋這個類以及用@Getter和@Setter注釋每個字段是一樣的。
===============================================================================================================
使用起來:
一.安裝lombok插件【idea使用為例】

二.項目引入lombok依賴
<!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
版本這里不給了,想使用最新版本的,可以自己加上。
三.lombok注解使用詳解
在上面安裝插件的時候,可以看到有很多的注解是被支持的:

官方的指導文檔,時間久遠。所以就找到下面的注解進行詳解。
@Getter and @Setter
【屬性級別,生成本屬性的get和set方法】
AccessLevel.PROTECTED 默認生成的方法為public,此屬性可以設置生成方法的訪問修飾符【非必須】
轉化前:
package com.sxd.entity; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; public class Order { @Getter @Setter private String orderId; @Getter(AccessLevel.PROTECTED) @Setter private User user; @Getter @Setter(AccessLevel.NONE) private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public void setOrderId(String orderId) { this.orderId = orderId; } public String getOrderId() { return this.orderId; } public void setUser(User user) { this.user = user; } protected User getUser() { return this.user; } public String getProductName() { return this.productName; } }

=============================================================================
@ToString
【類級別,生成自定義的toString()方法】
exclude="{字段1,字段2}" 生成的toString()不包含哪些字段【非必須】
callSuper=true 如果繼承的有父類的話,可以設置callSuper 讓其調用父類的toString()方法【非必須】
轉化前:
package com.sxd.entity; import lombok.ToString; @ToString(exclude = {"orderId","user"},callSuper = false) public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public String toString() { return "Order(productName=" + this.productName + ")"; } }

不使用上述屬性值的話:
轉化前:
package com.sxd.entity; import lombok.ToString; @ToString public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public String toString() { return "Order(orderId=" + this.orderId + ", user=" + this.user + ", productName=" + this.productName + ")"; } }

===================================================================================
@EqualsAndHashCode
【類級別,生成自定義的equals()方法和HashCode()方法】
exclude="{字段1,字段2}" 生成的方法不包含哪些字段【非必須】
callSuper=true 如果繼承的有父類的話,可以設置callSuper 讓其調用父類的方法【非必須】
轉化前:
package com.sxd.entity; import lombok.EqualsAndHashCode; @EqualsAndHashCode(exclude = {"orderId","user"},callSuper = false) public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public int hashCode() { int PRIME = 59;int result = 1;Object $productName = this.productName;result = result * 59 + ($productName == null ? 43 : $productName.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof Order; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Order)) { return false; } Order other = (Order)o; if (!other.canEqual(this)) { return false; } Object this$productName = this.productName;Object other$productName = other.productName;return this$productName == null ? other$productName == null : this$productName.equals(other$productName); } }

=====================================================================================
@NonNull
【屬性級別,驗證不能為null的注解,如果執行加了這個注解的setter方法時設置為Null,拋異常java.lang.NullPointerException】
轉化前:
package com.sxd.entity; import lombok.Getter; import lombok.NonNull; import lombok.Setter; public class Order { private String orderId; private User user; @NonNull @Getter @Setter private String productName; public Order() { } }
編譯后:
package com.sxd.entity; import lombok.NonNull; public class Order { private String orderId; private User user; @NonNull private String productName; public void setProductName(@NonNull String productName) { if (productName == null) { throw new NullPointerException("productName"); } this.productName = productName; } @NonNull public String getProductName() { return this.productName; } }
如果去執行setter方法並賦值Null,則報錯:

注意報錯行數:

===========================================================================================
@NoArgsConstructor
【類級別,生成無參構造方法】
focus=true 當類中有final字段沒有被初始化時,編譯器會報錯,此時可用@NoArgsConstructor(force = true),然后就會為沒有初始化的final字段設置默認值 0 / false / null。對於具有約束的字段(例如@NonNull字段),不會生成檢查或分配,因此請注意,正確初始化這些字段之前,這些約束無效。
轉化前:
package com.sxd.entity; import lombok.NoArgsConstructor; @NoArgsConstructor(force = true) public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; }
=====================================================================================
@RequiredArgsConstructor
【類級別,生成有 或 無參的靜態方法,用於獲取本對象】
staticName = "自定義靜態方法名"
轉化前:
package com.sxd.entity; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(staticName = "build") public class Order { private String orderId; private User user; private String productName; }
轉化后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public static Order build() { return new Order(); } }

===============================================================================
@AllArgsConstructor
【類級別,生成全參構造方法】
轉化前:
package com.sxd.entity; import lombok.AllArgsConstructor; @AllArgsConstructor public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; import java.beans.ConstructorProperties; public class Order { private String orderId; private User user; private String productName; @ConstructorProperties({"orderId", "user", "productName"}) public Order(String orderId, User user, String productName) { this.orderId = orderId;this.user = user;this.productName = productName; } }

================================================================================
@Data
【類級別,此注解為lombok中最常用注解】
【@Data 包含了@ToString,@EqualsAndHashCode,@Getter / @Setter和@RequiredArgsConstructor的功能】
staticConstructor="靜態實例化方法名"
轉化前:
package com.sxd.entity; import lombok.Data; @Data(staticConstructor = "build") public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public static Order build() { return new Order(); } public int hashCode() { int PRIME = 59;int result = 1;Object $orderId = getOrderId();result = result * 59 + ($orderId == null ? 43 : $orderId.hashCode());Object $user = getUser();result = result * 59 + ($user == null ? 43 : $user.hashCode());Object $productName = getProductName();result = result * 59 + ($productName == null ? 43 : $productName.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof Order; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Order)) { return false; } Order other = (Order)o; if (!other.canEqual(this)) { return false; } Object this$orderId = getOrderId();Object other$orderId = other.getOrderId(); if (this$orderId == null ? other$orderId != null : !this$orderId.equals(other$orderId)) { return false; } Object this$user = getUser();Object other$user = other.getUser(); if (this$user == null ? other$user != null : !this$user.equals(other$user)) { return false; } Object this$productName = getProductName();Object other$productName = other.getProductName();return this$productName == null ? other$productName == null : this$productName.equals(other$productName); } public void setOrderId(String orderId) { this.orderId = orderId; } public void setUser(User user) { this.user = user; } public void setProductName(String productName) { this.productName = productName; } public String toString() { return "Order(orderId=" + getOrderId() + ", user=" + getUser() + ", productName=" + getProductName() + ")"; } public String getOrderId() { return this.orderId; } public User getUser() { return this.user; } public String getProductName() { return this.productName; } }

@Accessors
【類級別,控制get、set方法】
- fluent boolean值,默認為false。此字段主要為控制生成的getter和setter方法前面是否帶get/set;false帶,true不帶
- chain boolean值,默認false。如果設置為true,setter返回的是此對象,方便鏈式調用方法
- prefix 設置前綴 例如:@Accessors(prefix = "abc") private String abcAge 當生成get/set方法時,會把此前綴去掉
轉化前:【注意三個屬性設值以及生成】
package com.sxd.entity; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(fluent = false,chain = false,prefix = "aaa") public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public String toString() { return "Order(orderId=" + this.orderId + ", user=" + this.user + ", productName=" + this.productName + ")"; } public int hashCode() { int PRIME = 59;int result = 1;Object $orderId = this.orderId;result = result * 59 + ($orderId == null ? 43 : $orderId.hashCode());Object $user = this.user;result = result * 59 + ($user == null ? 43 : $user.hashCode());Object $productName = this.productName;result = result * 59 + ($productName == null ? 43 : $productName.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof Order; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Order)) { return false; } Order other = (Order)o; if (!other.canEqual(this)) { return false; } Object this$orderId = this.orderId;Object other$orderId = other.orderId; if (this$orderId == null ? other$orderId != null : !this$orderId.equals(other$orderId)) { return false; } Object this$user = this.user;Object other$user = other.user; if (this$user == null ? other$user != null : !this$user.equals(other$user)) { return false; } Object this$productName = this.productName;Object other$productName = other.productName;return this$productName == null ? other$productName == null : this$productName.equals(other$productName); } }

===========================================================
轉化前:【注意fluent】
package com.sxd.entity; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(fluent = true,chain = false) public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public void productName(String productName) { this.productName = productName; } public int hashCode() { int PRIME = 59;int result = 1;Object $orderId = orderId();result = result * 59 + ($orderId == null ? 43 : $orderId.hashCode());Object $user = user();result = result * 59 + ($user == null ? 43 : $user.hashCode());Object $productName = productName();result = result * 59 + ($productName == null ? 43 : $productName.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof Order; } public void orderId(String orderId) { this.orderId = orderId; } public void user(User user) { this.user = user; } public String toString() { return "Order(orderId=" + orderId() + ", user=" + user() + ", productName=" + productName() + ")"; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Order)) { return false; } Order other = (Order)o; if (!other.canEqual(this)) { return false; } Object this$orderId = orderId();Object other$orderId = other.orderId(); if (this$orderId == null ? other$orderId != null : !this$orderId.equals(other$orderId)) { return false; } Object this$user = user();Object other$user = other.user(); if (this$user == null ? other$user != null : !this$user.equals(other$user)) { return false; } Object this$productName = productName();Object other$productName = other.productName();return this$productName == null ? other$productName == null : this$productName.equals(other$productName); } public String orderId() { return this.orderId; } public User user() { return this.user; } public String productName() { return this.productName; } }

==============================================================================
轉化前:【注意chain】
package com.sxd.entity; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(fluent = false,chain = true) public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public Order setProductName(String productName) { this.productName = productName;return this; } public int hashCode() { int PRIME = 59;int result = 1;Object $orderId = getOrderId();result = result * 59 + ($orderId == null ? 43 : $orderId.hashCode());Object $user = getUser();result = result * 59 + ($user == null ? 43 : $user.hashCode());Object $productName = getProductName();result = result * 59 + ($productName == null ? 43 : $productName.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof Order; } public Order setOrderId(String orderId) { this.orderId = orderId;return this; } public Order setUser(User user) { this.user = user;return this; } public String toString() { return "Order(orderId=" + getOrderId() + ", user=" + getUser() + ", productName=" + getProductName() + ")"; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Order)) { return false; } Order other = (Order)o; if (!other.canEqual(this)) { return false; } Object this$orderId = getOrderId();Object other$orderId = other.getOrderId(); if (this$orderId == null ? other$orderId != null : !this$orderId.equals(other$orderId)) { return false; } Object this$user = getUser();Object other$user = other.getUser(); if (this$user == null ? other$user != null : !this$user.equals(other$user)) { return false; } Object this$productName = getProductName();Object other$productName = other.getProductName();return this$productName == null ? other$productName == null : this$productName.equals(other$productName); } public String getOrderId() { return this.orderId; } public User getUser() { return this.user; } public String getProductName() { return this.productName; } }

===================================================================
轉化前:【注意prefix】
package com.sxd.entity; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(fluent = false,chain = true,prefix = "product") public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; public class Order { private String orderId; private User user; private String productName; public String toString() { return "Order(orderId=" + this.orderId + ", user=" + this.user + ", productName=" + getName() + ")"; } public int hashCode() { int PRIME = 59;int result = 1;Object $orderId = this.orderId;result = result * 59 + ($orderId == null ? 43 : $orderId.hashCode());Object $user = this.user;result = result * 59 + ($user == null ? 43 : $user.hashCode());Object $productName = getName();result = result * 59 + ($productName == null ? 43 : $productName.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof Order; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Order)) { return false; } Order other = (Order)o; if (!other.canEqual(this)) { return false; } Object this$orderId = this.orderId;Object other$orderId = other.orderId; if (this$orderId == null ? other$orderId != null : !this$orderId.equals(other$orderId)) { return false; } Object this$user = this.user;Object other$user = other.user; if (this$user == null ? other$user != null : !this$user.equals(other$user)) { return false; } Object this$productName = getName();Object other$productName = other.getName();return this$productName == null ? other$productName == null : this$productName.equals(other$productName); } public Order setName(String productName) { this.productName = productName;return this; } public String getName() { return this.productName; } }

=========================================================================
@Cleanup
【代碼級別,清理資源/關閉資源注解】
轉化前:
public void testCleanUp() { try { @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(new byte[] {'Y','e','s'}); System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); } }
編譯后:
public void testCleanUp() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(new byte[]{'Y', 'e', 's'}); System.out.println(baos.toString()); } finally { baos.close(); } } catch (IOException e) { e.printStackTrace(); } }
=========================================================================
@Synchronized
【方法級別,同步/線程安全注解】
轉化前:
private DateFormat format = new SimpleDateFormat("MM-dd-YYYY"); @Synchronized public String synchronizedFormat(Date date) { return format.format(date); }
編譯后:
private final java.lang.Object $lock = new java.lang.Object[0]; private DateFormat format = new SimpleDateFormat("MM-dd-YYYY"); public String synchronizedFormat(Date date) { synchronized ($lock) { return format.format(date); } }
=========================================================================
@Wither
【屬性級別,提供了給final字段賦值的一種方法】
轉化前:
import lombok.AccessLevel; import lombok.NonNull; import lombok.experimental.Wither; public class WitherExample { @Wither private final int age; @Wither(AccessLevel.PROTECTED) @NonNull private final String name; public WitherExample(String name, int age) { if (name == null) throw new NullPointerException(); this.name = name; this.age = age; } }
編譯后:
import lombok.NonNull; public class WitherExample { private final int age; private @NonNull final String name; public WitherExample(String name, int age) { if (name == null) throw new NullPointerException(); this.name = name; this.age = age; } public WitherExample withAge(int age) { return this.age == age ? this : new WitherExample(age, name); } protected WitherExample withName(@NonNull String name) { if (name == null) throw new java.lang.NullPointerException("name"); return this.name == name ? this : new WitherExample(age, name); } }
==================================================================================
@Builder
【類級別,為你的類生成復雜的構建器API】
轉化前:
package com.sxd.entity; import lombok.Builder; @Builder public class Order { private String orderId; private User user; private String productName; }
編譯后:
package com.sxd.entity; import java.beans.ConstructorProperties; public class Order { private String orderId; private User user; private String productName; public static class OrderBuilder { private String orderId; private User user; private String productName; public String toString() { return "Order.OrderBuilder(orderId=" + this.orderId + ", user=" + this.user + ", productName=" + this.productName + ")"; } public Order build() { return new Order(this.orderId, this.user, this.productName); } public OrderBuilder productName(String productName) { this.productName = productName;return this; } public OrderBuilder user(User user) { this.user = user;return this; } public OrderBuilder orderId(String orderId) { this.orderId = orderId;return this; } } public static OrderBuilder builder() { return new OrderBuilder(); } @ConstructorProperties({"orderId", "user", "productName"}) Order(String orderId, User user, String productName) { this.orderId = orderId;this.user = user;this.productName = productName; } }
==============================================================
@Delegate
【屬性級別,同化所在屬性的類型的方法到本類中】
轉化前:【本屬性類型為String】
package com.sxd.entity; import lombok.experimental.Delegate; public class Order { private String orderId; private User user; @Delegate private String productName; }
編譯后:
package com.sxd.entity; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Locale; import java.util.stream.IntStream; public class Order { private String orderId; private User user; private String productName; public IntStream codePoints() { return this.productName.codePoints(); } public IntStream chars() { return this.productName.chars(); } public String intern() { return this.productName.intern(); } public char[] toCharArray() { return this.productName.toCharArray(); } public String trim() { return this.productName.trim(); } public String toUpperCase() { return this.productName.toUpperCase(); } public String toUpperCase(Locale arg0) { return this.productName.toUpperCase(arg0); } public String toLowerCase() { return this.productName.toLowerCase(); } public String toLowerCase(Locale arg0) { return this.productName.toLowerCase(arg0); } public String[] split(String arg0) { return this.productName.split(arg0); } public String[] split(String arg0, int arg1) { return this.productName.split(arg0, arg1); } public String replace(CharSequence arg0, CharSequence arg1) { return this.productName.replace(arg0, arg1); } public String replaceAll(String arg0, String arg1) { return this.productName.replaceAll(arg0, arg1); } public String replaceFirst(String arg0, String arg1) { return this.productName.replaceFirst(arg0, arg1); } public boolean contains(CharSequence arg0) { return this.productName.contains(arg0); } public boolean matches(String arg0) { return this.productName.matches(arg0); } public String replace(char arg0, char arg1) { return this.productName.replace(arg0, arg1); } public String concat(String arg0) { return this.productName.concat(arg0); } public CharSequence subSequence(int arg0, int arg1) { return this.productName.subSequence(arg0, arg1); } public String substring(int arg0, int arg1) { return this.productName.substring(arg0, arg1); } public String substring(int arg0) { return this.productName.substring(arg0); } public int lastIndexOf(String arg0, int arg1) { return this.productName.lastIndexOf(arg0, arg1); } public int lastIndexOf(String arg0) { return this.productName.lastIndexOf(arg0); } public int indexOf(String arg0, int arg1) { return this.productName.indexOf(arg0, arg1); } public int indexOf(String arg0) { return this.productName.indexOf(arg0); } public int lastIndexOf(int arg0, int arg1) { return this.productName.lastIndexOf(arg0, arg1); } public int lastIndexOf(int arg0) { return this.productName.lastIndexOf(arg0); } public int indexOf(int arg0, int arg1) { return this.productName.indexOf(arg0, arg1); } public int indexOf(int arg0) { return this.productName.indexOf(arg0); } public boolean endsWith(String arg0) { return this.productName.endsWith(arg0); } public boolean startsWith(String arg0) { return this.productName.startsWith(arg0); } public boolean startsWith(String arg0, int arg1) { return this.productName.startsWith(arg0, arg1); } public boolean regionMatches(boolean arg0, int arg1, String arg2, int arg3, int arg4) { return this.productName.regionMatches(arg0, arg1, arg2, arg3, arg4); } public boolean regionMatches(int arg0, String arg1, int arg2, int arg3) { return this.productName.regionMatches(arg0, arg1, arg2, arg3); } public int compareToIgnoreCase(String arg0) { return this.productName.compareToIgnoreCase(arg0); } public int compareTo(String arg0) { return this.productName.compareTo(arg0); } public boolean equalsIgnoreCase(String arg0) { return this.productName.equalsIgnoreCase(arg0); } public boolean contentEquals(CharSequence arg0) { return this.productName.contentEquals(arg0); } public boolean contentEquals(StringBuffer arg0) { return this.productName.contentEquals(arg0); } public byte[] getBytes() { return this.productName.getBytes(); } public byte[] getBytes(Charset arg0) { return this.productName.getBytes(arg0); } public byte[] getBytes(String arg0) throws UnsupportedEncodingException { return this.productName.getBytes(arg0); } @Deprecated public void getBytes(int arg0, int arg1, byte[] arg2, int arg3) { this.productName.getBytes(arg0, arg1, arg2, arg3); } public void getChars(int arg0, int arg1, char[] arg2, int arg3) { this.productName.getChars(arg0, arg1, arg2, arg3); } public int offsetByCodePoints(int arg0, int arg1) { return this.productName.offsetByCodePoints(arg0, arg1); } public int codePointCount(int arg0, int arg1) { return this.productName.codePointCount(arg0, arg1); } public int codePointBefore(int arg0) { return this.productName.codePointBefore(arg0); } public int codePointAt(int arg0) { return this.productName.codePointAt(arg0); } public char charAt(int arg0) { return this.productName.charAt(arg0); } public boolean isEmpty() { return this.productName.isEmpty(); } public int length() { return this.productName.length(); } }

==========================================================================
轉化前:【所在屬性類型為List】
package com.sxd.entity; import lombok.experimental.Delegate; import java.util.List; public class Order { private String orderId; private User user; private String productName; @Delegate private List<Integer> arrList; }
編譯后:
package com.sxd.entity; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Spliterator; import java.util.function.UnaryOperator; public class Order { private String orderId; private User user; private String productName; private List<Integer> arrList; public Spliterator<Integer> spliterator() { return this.arrList.spliterator(); } public List<Integer> subList(int arg0, int arg1) { return this.arrList.subList(arg0, arg1); } public ListIterator<Integer> listIterator(int arg0) { return this.arrList.listIterator(arg0); } public ListIterator<Integer> listIterator() { return this.arrList.listIterator(); } public int lastIndexOf(Object arg0) { return this.arrList.lastIndexOf(arg0); } public int indexOf(Object arg0) { return this.arrList.indexOf(arg0); } public Integer remove(int arg0) { return (Integer)this.arrList.remove(arg0); } public void add(int arg0, Integer arg1) { this.arrList.add(arg0, arg1); } public Integer set(int arg0, Integer arg1) { return (Integer)this.arrList.set(arg0, arg1); } public Integer get(int arg0) { return (Integer)this.arrList.get(arg0); } public void clear() { this.arrList.clear(); } public void sort(Comparator<? super Integer> arg0) { this.arrList.sort(arg0); } public void replaceAll(UnaryOperator<Integer> arg0) { this.arrList.replaceAll(arg0); } public boolean retainAll(Collection<?> arg0) { return this.arrList.retainAll(arg0); } public boolean removeAll(Collection<?> arg0) { return this.arrList.removeAll(arg0); } public boolean addAll(int arg0, Collection<? extends Integer> arg1) { return this.arrList.addAll(arg0, arg1); } public boolean addAll(Collection<? extends Integer> arg0) { return this.arrList.addAll(arg0); } public boolean containsAll(Collection<?> arg0) { return this.arrList.containsAll(arg0); } public boolean remove(Object arg0) { return this.arrList.remove(arg0); } public boolean add(Integer arg0) { return this.arrList.add(arg0); } public <T> T[] toArray(T[] arg0) { return this.arrList.toArray(arg0); } public Object[] toArray() { return this.arrList.toArray(); } public Iterator<Integer> iterator() { return this.arrList.iterator(); } public boolean contains(Object arg0) { return this.arrList.contains(arg0); } public boolean isEmpty() { return this.arrList.isEmpty(); } public int size() { return this.arrList.size(); } }

============================================================================
@SneakyThrows
【異常處理注解,這里不做詳細解釋】
轉化前:
@SneakyThrows public void testSneakyThrows() { throw new IllegalAccessException(); }
編譯后:
public void testSneakyThrows() { try { throw new IllegalAccessException(); } catch (java.lang.Throwable $ex) { throw lombok.Lombok.sneakyThrow($ex); } }
============================================================================
@_({注解1,注解2})或@_(注解) 配合onMethod=使用
【屬性級別,用於將注解放在注解中使用】
轉化前:
package com.sxd.entity; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Id; public class Order { @Getter(onMethod = @_({@Column,@Id})) @Setter private String id; }
編譯后:
package com.sxd.entity; import javax.persistence.Column; import javax.persistence.Id; public class Order { private String id; @Column @Id public String getId() { return this.id; } public void setId(String id) { this.id = id; } }

【注意:這個時而有用,時而報錯,具體問題依舊找不到~~~~~~~~~~~~具體看附錄2】
============================================================================================================
最后,如果使用了lombok的話,如何在實體類上聲明實體對數據表的映射?
注意:@Column等注解是可以直接放在字段上而不用放在get方法上
例如:創建不同包下同名的實體類User.java
自己寫get/set方法的User類如下:
package com.sxd.entity; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Entity @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator" ) public class User { private String id; private String username; private String password; private Integer age; @Id @GeneratedValue(generator = "uuid2") public String getId() { return id; } public void setId(String id) { this.id = id; } @Column(nullable = false) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Column(nullable = false) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Column(nullable = false) public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User() { } public User(String id, String username, String password, Integer age) { this.id = id; this.username = username; this.password = password; this.age = age; } @Override public String toString() { return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + '}'; } }
編譯完是:
package com.sxd.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity @GenericGenerator(name="uuid2", strategy="org.hibernate.id.UUIDGenerator") public class User { private String id; private String username; private String password; private Integer age; @Id @GeneratedValue(generator="uuid2") public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(nullable=false) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @Column(nullable=false) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Column(nullable=false) public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public User() {} public User(String id, String username, String password, Integer age) { this.id = id; this.username = username; this.password = password; this.age = age; } public String toString() { return "User{id='" + this.id + '\'' + ", username='" + this.username + '\'' + ", password='" + this.password + '\'' + ", age=" + this.age + '}'; } }
=================== ==================================
使用lombok之后如下:
package com.sxd.controller; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import org.hibernate.annotations.GenericGenerator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator" ) @Data(staticConstructor = "of") @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) public class User { @Id @GeneratedValue(generator = "uuid2")private String id; private String username; @Column(nullable = false) private String password; @Column(nullable = false) private Integer age; }
編譯完是:
package com.sxd.controller; import java.beans.ConstructorProperties; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; @Entity @GenericGenerator(name="uuid2", strategy="org.hibernate.id.UUIDGenerator") public class User { @Id @GeneratedValue(generator="uuid2") private String id; private String username; @Column(nullable=false) private String password; @Column(nullable=false) private Integer age; public User setAge(Integer age) { this.age = age;return this; } public String toString() { return "User(id=" + getId() + ", username=" + getUsername() + ", password=" + getPassword() + ", age=" + getAge() + ")"; } public int hashCode() { int PRIME = 59;int result = 1;Object $id = getId();result = result * 59 + ($id == null ? 43 : $id.hashCode());Object $username = getUsername();result = result * 59 + ($username == null ? 43 : $username.hashCode());Object $password = getPassword();result = result * 59 + ($password == null ? 43 : $password.hashCode());Object $age = getAge();result = result * 59 + ($age == null ? 43 : $age.hashCode());return result; } protected boolean canEqual(Object other) { return other instanceof User; } public User setId(String id) { this.id = id;return this; } public User setUsername(String username) { this.username = username;return this; } public User setPassword(String password) { this.password = password;return this; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof User)) { return false; } User other = (User)o; if (!other.canEqual(this)) { return false; } Object this$id = getId();Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) { return false; } Object this$username = getUsername();Object other$username = other.getUsername(); if (this$username == null ? other$username != null : !this$username.equals(other$username)) { return false; } Object this$password = getPassword();Object other$password = other.getPassword(); if (this$password == null ? other$password != null : !this$password.equals(other$password)) { return false; } Object this$age = getAge();Object other$age = other.getAge();return this$age == null ? other$age == null : this$age.equals(other$age); } @ConstructorProperties({"id", "username", "password", "age"}) public User(String id, String username, String password, Integer age) { this.id = id;this.username = username;this.password = password;this.age = age; } public String getId() { return this.id; } public String getUsername() { return this.username; } public String getPassword() { return this.password; } public Integer getAge() { return this.age; } public User() {} }
有一個疑問,映射注解放在屬性上和放在get方法上有什么區別???【看附錄3】
===============================================================附錄1:equals()方法和hashCode()方法的意義==========================================================
摘錄:
1.hashcode是用來查找的,如果你學過數據結構就應該知道,在查找和排序這一章有
例如內存中有這樣的位置
0 1 2 3 4 5 6 7
而我有個類,這個類有個字段叫ID,我要把這個類存放在以上8個位置之一,如果不用hashcode而任意存放,那么當查找時就需要到這八個位置里挨個去找,或者用二分法一類的算法。
但如果用hashcode那就會使效率提高很多。
我們這個類中有個字段叫ID,那么我們就定義我們的hashcode為ID%8,然后把我們的類存放在取得得余數那個位置。比如我們的ID為9,9除8的余數為1,那么我們就把該類存在1這個位置,如果ID是13,求得的余數是5,那么我們就把該類放在5這個位置。這樣,以后在查找該類時就可以通過ID除 8求余數直接找到存放的位置了。
2.但是如果兩個類有相同的hashcode怎么辦那(我們假設上面的類的ID不是唯一的),例如9除以8和17除以8的余數都是1,那么這是不是合法的,
回答是:可以這樣。那么如何判斷呢?在這個時候就需要定義 equals了。
也就是說,我們先通過 hashcode來判斷兩個類是否存放某個桶里,但這個桶里可能有很多類,那么我們就需要再通過 equals 來在這個桶里找到我們要的類。
那么。重寫了equals(),為什么還要重寫hashCode()呢?
想想,你要在一個桶里找東西,你必須先要找到這個桶啊,你不通過重寫hashcode()來找到桶,光重寫equals()有什么用啊
==============================================================附錄2:@Getter()等lombok注解配合hibernate的映射注解怎么使用===========================================================
如果在項目中真的使用lombok的注解的話,映射注解應該如何處理呢?
寥寥無幾的資料中有大概類似於如下的寫法:
@Getter(onMethod = @_({@Id,@Column(name="id",nullable=false),@GeneratedValue(strategy= GenerationType.AUTO)}))
@Setter
private Integer id;
親自試了一下,
如下:

報錯如下:

其實在@Getter()注解接口中定義如下:

但是具體怎么去寫,還沒有研究出來。
【如有解決方法,不吝賜教!!】
所以,最終按照並列將注解寫在屬性上,而不是在@Getter()注解中寫@Column()注解。
如下:
@Data(staticConstructor = "of") @NoArgsConstructor @AllArgsConstructor @Accessors(chain = true) @Entity @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator" ) public class Member { @Id @GeneratedValue(generator = "uuid2") @Column(name = "memberId") private String memberId; @OneToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH},fetch = FetchType.EAGER) private User user; @Column(name="memberGrade",nullable = false) @NonNull private Integer memberGrade; }
編譯完成如下:
package com.sxd.entity; import java.beans.ConstructorProperties; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import lombok.NonNull; import org.hibernate.annotations.GenericGenerator; @Entity @GenericGenerator(name="uuid2", strategy="org.hibernate.id.UUIDGenerator") public class Member { @Id @GeneratedValue(generator="uuid2") @Column(name="memberId") private String memberId; @OneToOne(cascade={javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.REFRESH}, fetch=FetchType.EAGER) private User user; @Column(name="memberGrade", nullable=false) @NonNull private Integer memberGrade; public String toString() { return "Member(memberId=" + getMemberId() + ", user=" + getUser() + ", memberGrade=" + getMemberGrade() + ")"; } public int hashCode() { int PRIME = 59;int result = 1;Object $memberId = getMemberId();result = result * 59 + ($memberId == null ? 43 : $memberId.hashCode());Object $user = getUser();result = result * 59 + ($user == null ? 43 : $user.hashCode());Object $memberGrade = getMemberGrade();result = result * 59 + ($memberGrade == null ? 43 : $memberGrade.hashCode());return result; } public Member setMemberId(String memberId) { this.memberId = memberId;return this; } public Member setUser(User user) { this.user = user;return this; } public Member setMemberGrade(@NonNull Integer memberGrade) { if (memberGrade == null) { throw new NullPointerException("memberGrade"); } this.memberGrade = memberGrade;return this; } protected boolean canEqual(Object other) { return other instanceof Member; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Member)) { return false; } Member other = (Member)o; if (!other.canEqual(this)) { return false; } Object this$memberId = getMemberId();Object other$memberId = other.getMemberId(); if (this$memberId == null ? other$memberId != null : !this$memberId.equals(other$memberId)) { return false; } Object this$user = getUser();Object other$user = other.getUser(); if (this$user == null ? other$user != null : !this$user.equals(other$user)) { return false; } Object this$memberGrade = getMemberGrade();Object other$memberGrade = other.getMemberGrade();return this$memberGrade == null ? other$memberGrade == null : this$memberGrade.equals(other$memberGrade); } @ConstructorProperties({"memberId", "user", "memberGrade"}) public Member(String memberId, User user, @NonNull Integer memberGrade) { if (memberGrade == null) { throw new NullPointerException("memberGrade"); } this.memberId = memberId;this.user = user;this.memberGrade = memberGrade; } public String getMemberId() { return this.memberId; } public User getUser() { return this.user; } @NonNull public Integer getMemberGrade() { return this.memberGrade; } public Member() {} }

那么最后看 附錄3,了解最后一個問題,映射注解放在屬性上和放在get方法上有什么區別?
=======================================================================附錄3:映射注解放在屬性上和放在get()方法上有什么區別======================================================================
摘錄自:http://blog.csdn.net/most_rabbitfishes/article/details/70904949
對於屬性字段和表的字段關系對應的注解屬性的位置,一般我們采用以下兩種方式:
第一種:
是把注解@Column(name ="xx")放在field上,一種是把注解放在get方法上一般放在field上看起來比較集中、清晰;
第二種:
是把注解@Column(name= "xx")放在get方法上,這種方式看起來比較散漫、不很清楚;
但是第一種方式這樣做實際上破壞了java面向對象的封裝性,原因是一般我們寫javaBean,成員變量通常定義為private,目的就是不讓別人來直接訪問的私有屬性,而我們把注解放在私有成員的變量上,就是默認hibernate可以直接訪問我們的私有的成員變量,所以我們定義屬性為private,就實際沒有多大意義,至於hibernate為什么能訪問,hibernate采用java的反射機制完全可以訪問私有成員變量!所以應該放在get方法上,第二種方式這個時候就顯得更加合理。
隨即,我采用了附錄2中實體用於hibernate自動生成數據表的表結構:

Hibernate自動幫我們建表:
如果我們采用注解的方式在我們的實體Bean上,又想通過掃描這些注解的Bean,通過Hibernate自動幫我們建表,那么你就會發現字段注解的位置不同甚至會影響到建表的結構,尤其是大字段、外鍵約束的生成效果。
如果采用第一種方式注解到私有字段上,這種幫我們建立表結構、約束條件和大字段Lob類型這些都是非常正常的,而通過第二種方式注解到get方法上,這種幫我們的建立的表大部分正常字段正常,而外鍵關聯的和大字段就會出現問題.
雖然項目的開發我們不采用hibernate幫我們自動建表,通常我們還是要手動的建表,所以這一些是對於通過Hibernate幫我們自動建表要考慮的!而實際開發中,已注解在get方法上為多數!
結論:如上 將注解建立在屬性上,生成的表結構,約束條件,外鍵等都正常,所以,如果你要使用hibernate的生成策略,在你建立好實體之后自動去建立數據表的話,同時使用lombok的注解和映射注解都放在屬性上是合適的!!!

