英文:
How to read table with hibernate and ajax request
问题
我有以下代码从我的数据库中检索数据。我在Wildfly和MySQL服务器上运行。
以下代码段应返回所有可用的用户组。
@WebServlet(urlPatterns = {"/groups_list"})
public class UserGroupList extends HttpServlet {
/**
* 获取所有可用的用户组
* @param request
* @param response
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Session session = HibernateHelper.getSessionFactory().openSession();
List<UserGroup> userGroups = session.createQuery("FROM UserGroup UG").getResultList();
ObjectMapper objectMapper = new ObjectMapper();
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userGroups);
response.getWriter().println(json);
} catch(Exception e) {
response.getWriter().println(e.getMessage());
}
}
}
以下代码段应返回所有可用的用户。
@WebServlet(urlPatterns = {"/users_list"})
public class UsersList extends HttpServlet {
/**
* 获取所有可用的用户
* @param request
* @param response
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Session session = HibernateHelper.getSessionFactory().openSession();
List<User> users = session.createQuery("FROM User s").getResultList();
ObjectMapper objectMapper = new ObjectMapper();
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(users);
response.getWriter().println(json);
} catch(Exception e) {
response.getWriter().println(e.getMessage());
}
}
}
Ajax请求如下发送:
$(function() {
// 获取所有用户组
$.ajax({
type: 'GET',
url: 'http://localhost:8080/shopping_cart/groups_list',
dataType: 'json',
success: function(data){
},
error: function(data){
toastr.error('错误。无法获取用户组。')
}
});
// 获取所有用户
$.ajax({
type: "GET",
url: "http://localhost:8080/shopping_cart/users_list",
dataType: "json",
contentType: "application/json",
success: function(response) {
console.log(response);
},
error: function(data){
toastr.error('错误。无法获取用户组。')
}
});
});
我的User实体如下:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private int id;
@Embedded
private Person person;
@Column(columnDefinition = "VARCHAR(255)")
private String image;
@ManyToOne
@JoinColumn(name="user_group_id", nullable = false, referencedColumnName = "user_group_id")
private UserGroup userGroup;
我的User Group实体如下:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_group_id")
private int id;
@NotNull
@Column(nullable = false, columnDefinition = "VARCHAR(20)")
private String name;
@NotNull
@Column(nullable = false, columnDefinition = "TEXT")
private String permission;
@OneToMany(mappedBy="userGroup",
cascade={CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.LAZY)
private List<User> users = new ArrayList<User>();
然而,如果我使用上述代码并返回表中的所有数据,如果数据不存在,我在浏览器控制台窗口中会得到一个空数组作为响应。下次发送请求时,我会得到以下错误:
Infinite recursion (StackOverflowError) (through reference chain: models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->...)
英文:
I have the following code to retrieve data from my db. Im running on wildfly and MySQL servers.
The below snippet should return all the user groups available.
@WebServlet(urlPatterns = {"/groups_list"})
public class UserGroupList extends HttpServlet {
/**
* Get all users groups available
* @param request
* @param response
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Session session = HibernateHelper.getSessionFactory().openSession();
List<UserGroup> userGroups= session.createQuery("FROM UserGroup UG").getResultList();
ObjectMapper objectMapper = new ObjectMapper();
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userGroups);
response.getWriter().println(json);
} catch(Exception e) {
response.getWriter().println(e.getMessage());
}
}
}
The below snippet should return all the users available.
@WebServlet(urlPatterns = {"/users_list"})
public class UsersList extends HttpServlet {
/**
* Get all users available
* @param request
* @param response
* @throws IOException
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Session session = HibernateHelper.getSessionFactory().openSession();
List<User> users = session.createQuery("FROM User s").getResultList();
ObjectMapper objectMapper = new ObjectMapper();
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(users);
response.getWriter().println(json);
} catch(Exception e) {
response.getWriter().println(e.getMessage());
}
}
}
The ajax requests are sent as below:
$(function() {
// Fetch all user groups
$.ajax({
type: 'GET',
url: 'http://localhost:8080/shopping_cart/groups_list',
dataType:'json',
success: function(data){
},
error: function(data){
toastr.error('Error. Couldn\'t fetch user groups.')
}
});
// Fetch all users
$.ajax({
type: "GET",
url: "http://localhost:8080/shopping_cart/users_list",
dataType: "json",
contentType: "application/json",
success: function(response) {
console.log(response);
},
error: function(data){
toastr.error('Error fetching user goups.')
}
});
});
My User entity is shown:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private int id;
@Embedded
private Person person;
@Column(columnDefinition = "VARCHAR(255)")
private String image;
@ManyToOne
@JoinColumn(name="user_group_id", nullable = false, referencedColumnName = "user_group_id")
private UserGroup userGroup;
My User Group Entity:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_group_id")
private int id;
@NotNull
@Column(nullable = false, columnDefinition = "VARCHAR(20)")
private String name;
@NotNull
@Column(nullable = false, columnDefinition = "TEXT")
private String permission;
@OneToMany(mappedBy="userGroup",
cascade={CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.LAZY)
private List<User> users = new ArrayList<User>();
However, I might use the exact code above and return all the data available in the tables, and if the data is not there I get an empty array as the response in the browser console window.
The next time I send the request, I get the following:
Infinite recursion (StackOverflowError) (through reference chain: models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]->org.hibernate.collection.internal.PersistentBag[0]->models.User["userGroup"]->models.UserGroup["users"]-
答案1
得分: 0
代码部分不需要翻译,以下是你提供的内容的中文翻译:
可能的原因是您没有真正向客户端返回任何错误,这是由于这个原因:
catch(Exception e) {
e.printStackTrace();
}
另外,如果您打开了 Hibernate 会话,您必须在 final
块中关闭它。
Jackson 在将实体转换为 JSON 时出现无限处理 User -> UserGroup -> User
的原因是:
您可以通过使用额外的 Jackson 注解来解决此问题。
我建议您更改您的模型:
UserGroup
是表格数据,所以您不必在那里存储用户。
只需从 UserGroup
中移除这部分:
private List<User> users = new ArrayList<User>();
英文:
The reason can be that you don't really return any error to the client, cause of this
catch(Exception e) {
e.printStackTrace();
}
Also, if you opened Hibernate session you have to close it in the final
block.
The reason that Jackson during converting entities to JSON infinitely processes User -> UserGroup -> User
You can fix the issue using additional Jackson annotations
I would like to advice you to change your model:
UserGroup
is tabular data, so you don't have to store users there.
Just remove this from UserGroup
private List<User> users = new ArrayList<User>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论