如何使用Hibernate和Ajax请求读取表格。

huangapple go评论71阅读模式
英文:

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 = {&quot;/groups_list&quot;})
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&lt;UserGroup&gt; userGroups= session.createQuery(&quot;FROM UserGroup UG&quot;).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 = {&quot;/users_list&quot;})
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&lt;User&gt; users = session.createQuery(&quot;FROM User s&quot;).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: &#39;GET&#39;,
            url: &#39;http://localhost:8080/shopping_cart/groups_list&#39;,
            dataType:&#39;json&#39;,
            success: function(data){
     
            },
            error: function(data){
                toastr.error(&#39;Error. Couldn\&#39;t fetch user groups.&#39;)
            }
        });

        // Fetch all users
        $.ajax({  
            type: &quot;GET&quot;,  
            url: &quot;http://localhost:8080/shopping_cart/users_list&quot;,  
            dataType: &quot;json&quot;,  
            contentType: &quot;application/json&quot;,  
            success: function(response) {  
              console.log(response); 
            },  
            error: function(data){
                toastr.error(&#39;Error fetching user goups.&#39;)
      	    }
        });  
    });

My User entity is shown:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name=&quot;user_id&quot;)
    private int id;

    @Embedded
    private Person person;

    @Column(columnDefinition = &quot;VARCHAR(255)&quot;)
    private String image;

    @ManyToOne
    @JoinColumn(name=&quot;user_group_id&quot;, nullable = false, referencedColumnName = &quot;user_group_id&quot;)
    private UserGroup userGroup;

My User Group Entity:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name=&quot;user_group_id&quot;)
    private int id;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;VARCHAR(20)&quot;)
    private String name;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;TEXT&quot;)
    private String permission;

    @OneToMany(mappedBy=&quot;userGroup&quot;,
    cascade={CascadeType.PERSIST, CascadeType.MERGE},
    fetch = FetchType.LAZY)
    private List&lt;User&gt; users = new ArrayList&lt;User&gt;();

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[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-&gt;org.hibernate.collection.internal.PersistentBag[0]-&gt;models.User[&quot;userGroup&quot;]-&gt;models.UserGroup[&quot;users&quot;]-

答案1

得分: 0

代码部分不需要翻译,以下是你提供的内容的中文翻译:

可能的原因是您没有真正向客户端返回任何错误,这是由于这个原因:

catch(Exception e) {
  e.printStackTrace();
}

另外,如果您打开了 Hibernate 会话,您必须在 final 块中关闭它。

Jackson 在将实体转换为 JSON 时出现无限处理 User -> UserGroup -> User 的原因是:

您可以通过使用额外的 Jackson 注解来解决此问题。

https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue

我建议您更改您的模型:

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 -&gt; UserGroup -&gt; User

You can fix the issue using additional Jackson annotations

https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue

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&lt;User&gt; users = new ArrayList&lt;User&gt;();

huangapple
  • 本文由 发表于 2020年9月2日 18:05:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63703252.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定