Hello :)
So, there is a form with sending comments.Чего хочу - the user enters the text of the comment, sends, without reloading the page, a new list of comments is displayed, in which the top one is just sent. Occurs with AJAX . When it was on pure JDBC , everything worked as it should. Now I rewrite Hibernate - the old list is displayed after the form is submitted, if the page is reloaded, the list is updated. I use JSF - PrimeFaces implementation
Submit Form:<h:form>
<p:inputTextarea id="textResponse" value="#{currentUser.response}" requiredMessage="!" placeholder="Напишите отзыв"> <f:validateRequired /> </p:inputTextarea> <h:message id="message_textResponse" for="textResponse" style="color:red"/> <h:commandButton class="reg_button" action="#{currentUser.addResponse}" value="Отправить"> <f:ajax execute="textResponse" render="@form" /> </h:commandButton> <c:forEach var="resp" items="#{initIndex.resps}"> <table class="responseTable"> <tr><td class="oneLine">#{resp.users.name} #{resp.users.family}</td> <td class="dateLine">#{resp.date.toString()}</td></tr> <tr><td class="responseLine" colspan="2">#{resp.text}</td></tr> </table> </c:forEach> </h:form>
Next, there are 2 Managed Bean .currentUser :
`
@Named(value = "currentUser") @SessionScoped public class UsersBean implements Serializable { private Integer id = -1; private String response; ResponseDAO respDAO; /** * Creates a new instance of UsersBean */ public UsersBean() { respDAO = new ResponseDAO(); } public void addResponse() { if (id != -1) { respDAO.addResponse(id, response); } response = ""; } /** * геттеры, сеттеры */ } `
InitIndex :
`
@ManagedBean @ViewScoped public class InitIndex implements Serializable { private List<Response> resps = null; private ResponseDAO myRespDAO; @PostConstruct public void init() { myRespDAO = new ResponseDAO(); resps = getResps(); } /** * @return the resps */ public List<Response> getResps() { //return new ConnectWithDB().getResponses(); return myRespDAO.getResponses(); } /** * @param resps the resps to set */ public void setResps(ArrayList<Response> resps) { this.resps = resps; } } `
And, actually, the ResponseDAO class, in which a review is written and we get a list of reviews. Here, I think, lies the mistake ...
` public class ResponseDAO implements AutoCloseable { private final Session session; public ResponseDAO() { this.session = NewHibernateUtil.getSessionFactory().openSession(); //Создание hibernate сессии } //добавить отзыв пользователя в БД public void addResponse(int userId, String text){ //создаю объект Отзыв Response resp = createResponse(text, userId); Transaction tx = null; try { //записываю объект tx = session.beginTransaction(); session.save(resp); session.flush(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } } //создать объект отзыв public Response createResponse(String text, int userId) { Response resp = new Response(); resp.setText(text); Users user2 = (Users)session.createQuery("from Users where id = :paramId") .setParameter("paramId", userId).list().get(0); resp.setUsers(user2); resp.setDate(new java.util.Date()); return resp; } //Получение списка отзывов public List<Response> getResponses() { List<Response> resp = session.createQuery("FROM Response ORDER BY date DESC").list(); return resp; } @Override public void close() { if (session != null && session.isOpen()) { session.close(); } } } `
SessionScopedwas taken from javax.enterprise.context.SessionScoped, fixed it right. Also, got rid of the@Namedannotation. Nothing has changed ... I will debug more thoroughly. - Natalia