我在 hibernate 上使用
產生 JSON 的 java
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// 把 hibernate 的方法包在 DAO 裡面再包在 service 裡面
ProductService service = new ProductService(session);
List<Product> resultList = service.selectAll();
Gson gson = new Gson();
String jsonString = gson.toJson(resultList);
out.print(jsonString);
out.close();
把資料傳到javascript, 本來是沒問的的. 但後來在Java Bean上加了 many to one 之後就只會rollback.
many to one 的 java bean
@Entity @Table(name = "Product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id @Column(name = "P_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int P_ID;
@Column(name = "P_Name")
private String P_Name;
@Transient
private String P_Type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PT_ID")
private ProductType productType;
public Product() {}
One to many 的 java bean
@Entity @Table(name = "ProductType")
public class ProductType implements Serializable {
private static final long serialVersionUID = 1L;
@Id @Column(name = "PT_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int PT_ID;
@Column(name = "PT_Name")
private String PT_Name;
public ProductType() {}
public ProductType(int id, String name, String type, int stock, double cost, double price, String image) {
this.PT_ID = id;
this.PT_Name = name;
}
public int getPT_ID() {
return PT_ID;
}
public void setPT_ID(int pT_ID) {
PT_ID = pT_ID;
}
public String getPT_Name() {
return PT_Name;
}
public void setPT_Name(String pT_Name) {
PT_Name = pT_Name;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
但後來產生 JSON 的 java 檔中發現其實有成功取得資料, 因為可以console出來. 但就出現這個錯誤訊息:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.gson.internal.bind.ReflectiveTypeAdapterFactory (file:/C:/DataSource/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HibernateProjectTest/WEB-INF/lib/gson-2.8.2.jar) to field java.lang.reflect.Method.clazz
WARNING: Please consider reporting this to the maintainers of com.google.gson.internal.bind.ReflectiveTypeAdapterFactory
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
所以是Gson出現問題嗎?