Я кодирую вместе с некоторым учебником udemy, но я пытаюсь использовать тимелеаф вместо jsp. Это моя форма html:
<!DOCTYPE html>
<html xmlns:th = "http://www.thymeleaf.org" lang = "eng">
<head>
<meta charset = "UTF-8" />
<title>Save Customer</title>
<link rel = "stylesheet" type = "text/css" th:href = "@{/style.css}" />
<link rel = "stylesheet" type = "text/css" th:href = "@{/add-customer-style.css}" />
</head>
<body>
<div class = "wrapper">
<div class = "header">
<h2>CRM - Customer Relationship Manager</h2>
</div>
</div>
<div class = "container">
<h3>Save Customer</h3>
<form action = "#" th:action = "@{/customer/saveCustomer}" th:object = "${customer}" method = "post">
<!--need to associate this data with customer id-->
<input type = "hidden" th:field = "*{id}">
<table>
<tbody>
<tr>
<td><label for = "">First name:</label></td>
<td><input type = "text" th:field = "*{firstName}"></td>
</tr>
<tr>
<td><label for = "">Last name:</label></td>
<td><input type = "text" th:field = "*{lastName}"></td>
</tr>
<tr>
<td><label for = "">email:</label></td>
<td><input type = "text" th:field = "*{email}"></td>
</tr>
<tr>
<td><label for = ""></label></td>
<td><input type = "submit" value = "save" class = "save"></td>
</tr>
</tbody>
</table>
</form>
<p>
<a th:href = "@{/customer/list}">Back to list</a>
</p>
</div>
</body>
</html>
а это мой дао имп:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManagerFactory;
import java.util.List;
@Repository
public class CustomerDAOImpl implements CustomerDAO {
//need to inject the session factory
private SessionFactory hibernateFactory;
@Autowired
public CustomerDAOImpl(EntityManagerFactory factory) {
if (factory.unwrap(SessionFactory.class) == null){
throw new NullPointerException("factory is not a hibernate factory");
}
this.hibernateFactory = factory.unwrap(SessionFactory.class);
}
@Override
public List<Customer> getCustomers() {
//get the current hibernate session
var currentSession = hibernateFactory.openSession();
//create a query... sort by last name
var theQuery = currentSession.createQuery("from Customer order by lastName", Customer.class);
// execute query and get result list
//return the results
return theQuery.getResultList();
}
@Override
public void saveCustomer(Customer theCustomer) {
// get current hibernate session
var currentSession = hibernateFactory.openSession();
// save the customer... finally LOL
currentSession.saveOrUpdate(theCustomer);
}
@Override
public Customer getCustomer(int theId) {
// get the current hibernate session
var currentSession = hibernateFactory.openSession();
// now retrieve/read from database using the primary key
return currentSession.get(Customer.class, theId);
}
когда я нажимаю кнопку «Обновить», он заполняет форму данными объекта, которые я хочу обновить. Но после нажатия кнопки «Сохранить» ничего не меняется. Есть идеи, почему? Я трачу второй день, пытаясь заставить его работать ...
PS Может что-то не так с фабрикой сессий?
Или со скрытым вводом?
Добро пожаловать в переполнение стека. Пожалуйста, не размещайте ссылки на код, xml и т. д., Вместо этого включите их в свой вопрос.
Что ж, вы обойдете управление транзакциями Spring, и зачем вообще использовать SessionFactory
вместо обычного Entitymanager
.
Поскольку в учебнике использовалась фабрика сеансов. Как новичок, я не знаю, какой из них лучше.
Ах, чувак! Это работает! Пожалуйста, вернитесь к моей теме, чтобы я мог отметить решение :) Я использовал entityManager вместо сеанса, и все отлично!
Попробуйте добавить @Transactional
в метод обслуживания, который вызывает saveCustomer
.
Добавьте соответствующий код в вопрос вместо ссылки на pastecode.