Форум программистов, компьютерный форум, киберфорум
Java: Spring, Spring Boot
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.72/29: Рейтинг темы: голосов - 29, средняя оценка - 4.72
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249

Spring mvc org.hibernate.LazyInitializationExceptio­n: could not initialize proxy - no Session

25.01.2017, 15:23. Показов 6568. Ответов 21

Студворк — интернет-сервис помощи студентам
Добрый день. Помогите исправить ошибку.
Проблема после AJAX запроса:
JavaScript
1
2
3
4
5
6
7
8
9
$.ajax({
        url: '/electronsun/admin/saveproduct',
        type: 'POST',
        data: {
            id: id,
            column: column,
            value: value
        }
    })
данные попадают в контроллер:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@Controller
@RequestMapping(value = "/admin")
public class AdminProductController {
 
    @Autowired
    private ProductService productService;
 
    @RequestMapping("/product")
    public String login(ModelMap model) {
        return "admin/product";
    }
 
    @RequestMapping(value = "/loadproducts", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody List<Product> loadProducts (){
        return productService.getAll();
    }
 
    @RequestMapping(value = "/saveproduct", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody Product saveProduct(@RequestParam Long id, @RequestParam("column") String column,
                                             @RequestParam("value") String value ) {
        Product product = productService.get(id);
        if (Objects.equals(column, "name")){
            product.setName(value);
        }else if (Objects.equals(column, "description")){
            product.setDescription(value);
        }else if (Objects.equals(column, "price")){
            product.setPrice(Double.parseDouble(value));
        }else if (Objects.equals(column, "discount")){
            product.setDiscount(Integer.parseInt(value));
        }else if (Objects.equals(column, "maxLed")){
            product.setMaxLed(Integer.parseInt(value));
        }
        return productService.save(product);
    }
 
}

entity
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
@Entity
@Table(name = "products", uniqueConstraints={@UniqueConstraint(columnNames={"name"})})
public class Product  extends NamedEntity {
    @Column(name = "description")
    private String description;
 
    @Column(name = "price", nullable = false)
    private double price;
    /**
     * скидка в процентах
     */
    @Column(name = "discount")
    private int discount;
 
    /**
     * Цена со скидкой
     */
    @Column(name = "discount_price")
    private double discountPrice;
 
    /**
     * кол-во светодиодов в приборе
     */
    @Column(name = "maxLed", nullable = false)
    private int maxLed;
 
    public Product() {
    }
 
    public Product(Long id, String name, String description, double price) {
        super(id, name);
        this.description = description;
        this.price = price;
    }
 
    public Product(Long id, String name, String description, double price, int maxLed) {
        super(id, name);
        this.description = description;
        this.price = price;
        this.maxLed = maxLed;
    }
 
    public String getDescription() {
        return description;
    }
 
    public void setDescription(String description) {
        this.description = description;
    }
 
    public double getPrice() {
        return price;
    }
 
    public void setPrice(double price) {
        this.price = price;
    }
 
    public double getDiscount() {
        return discount;
    }
 
    public void setDiscount(int discount) {
        this.discount = discount;
        discountPrice = (price * discount) / 100;
    }
 
    public double getDiscountPrice() {
        return discountPrice;
    }
 
    public int getMaxLed() {
        return maxLed;
    }
 
    public void setMaxLed(int maxLed) {
        this.maxLed = maxLed;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
 
        Product product = (Product) o;
 
        if (Double.compare(product.price, price) != 0) return false;
        return description.equals(product.description);
    }
 
    @Override
    public int hashCode() {
        int result = super.hashCode();
        long temp;
        result = 31 * result + description.hashCode();
        temp = Double.doubleToLongBits(price);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        return result;
    }
}
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
25.01.2017, 15:23
Ответы с готовыми решениями:

Hibernate + could not initialize proxy - no Session
Есть вот такой метод: @Override public Collection getAllCategories() { List&lt;Category&gt; categories = null; ...

Spring-mvc session
Добрый день уважаемые форумчане. Работаю над проектом на spring-mvc 4.1.1 , столкнулся с задачей хранения информации пользователя в сессии....

Spring MVC + Hibernate
При добавлении обьекта в БД возникает исключение org.springframework.web.util.NestedServletException: Request processing failed;...

21
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
25.01.2017, 15:25  [ТС]
ошибка
org.hibernate.LazyInitializationExceptio n: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitiali zer.initialize(AbstractLazyInitializer.j ava:147)
at org.hibernate.proxy.AbstractLazyInitiali zer.getImplementation(AbstractLazyInitia lizer.java:260)
at org.hibernate.proxy.pojo.javassist.Javas sistLazyInitializer.invoke(JavassistLazy Initializer.java:73)
at model.Product_$$_jvste27_4.setName(Produ ct_$$_jvste27_4.java)
at web.product.AdminProductController.saveP roduct(AdminProductController.java:42)
at sun.reflect.NativeMethodAccessorImpl.inv oke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.inv oke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl .invoke(DelegatingMethodAccessorImpl.jav a:43)
at java.lang.reflect.Method.invoke(Method.j ava:498)
at org.springframework.web.method.support.I nvocableHandlerMethod.doInvoke(Invocable HandlerMethod.java:220)
at org.springframework.web.method.support.I nvocableHandlerMethod.invokeForRequest(I nvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.meth od.annotation.ServletInvocableHandlerMet hod.invokeAndHandle(ServletInvocableHand lerMethod.java:116)
at org.springframework.web.servlet.mvc.meth od.annotation.RequestMappingHandlerAdapt er.invokeHandlerMethod(RequestMappingHan dlerAdapter.java:827)
at org.springframework.web.servlet.mvc.meth od.annotation.RequestMappingHandlerAdapt er.handleInternal(RequestMappingHandlerA dapter.java:738)
at org.springframework.web.servlet.mvc.meth od.AbstractHandlerMethodAdapter.handle(A bstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.Dispatch erServlet.doDispatch(DispatcherServlet.j ava:963)
at org.springframework.web.servlet.Dispatch erServlet.doService(DispatcherServlet.ja va:897)
at org.springframework.web.servlet.Framewor kServlet.processRequest(FrameworkServlet .java:970)
at org.springframework.web.servlet.Framewor kServlet.doPost(FrameworkServlet.java:87 2)
at javax.servlet.http.HttpServlet.service(H ttpServlet.java:648)
at org.springframework.web.servlet.Framewor kServlet.service(FrameworkServlet.java:8 46)
at javax.servlet.http.HttpServlet.service(H ttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilt erChain.internalDoFilter(ApplicationFilt erChain.java:291)
at org.apache.catalina.core.ApplicationFilt erChain.doFilter(ApplicationFilterChain. java:206)
at org.apache.tomcat.websocket.server.WsFil ter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilt erChain.internalDoFilter(ApplicationFilt erChain.java:239)
at org.apache.catalina.core.ApplicationFilt erChain.doFilter(ApplicationFilterChain. java:206)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:317)
at org.springframework.security.web.access. intercept.FilterSecurityInterceptor.invo ke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access. intercept.FilterSecurityInterceptor.doFi lter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.access. ExceptionTranslationFilter.doFilter(Exce ptionTranslationFilter.java:114)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.session .SessionManagementFilter.doFilter(Sessio nManagementFilter.java:137)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.AnonymousAuthenticationFilter.do Filter(AnonymousAuthenticationFilter.jav a:111)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.rememberme.RememberMeAuthenticat ionFilter.doFilter(RememberMeAuthenticat ionFilter.java:158)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.servlet api.SecurityContextHolderAwareRequestFil ter.doFilter(SecurityContextHolderAwareR equestFilter.java:170)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.savedre quest.RequestCacheAwareFilter.doFilter(R equestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.AbstractAuthenticationProcessing Filter.doFilter(AbstractAuthenticationPr ocessingFilter.java:200)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.logout.LogoutFilter.doFilter(Log outFilter.java:116)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.csrf.Cs rfFilter.doFilterInternal(CsrfFilter.jav a:124)
at org.springframework.web.filter.OncePerRe questFilter.doFilter(OncePerRequestFilte r.java:107)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.header. HeaderWriterFilter.doFilterInternal(Head erWriterFilter.java:64)
at org.springframework.web.filter.OncePerRe questFilter.doFilter(OncePerRequestFilte r.java:107)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.context .request.async.WebAsyncManagerIntegratio nFilter.doFilterInternal(WebAsyncManager IntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRe questFilter.doFilter(OncePerRequestFilte r.java:107)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.context .SecurityContextPersistenceFilter.doFilt er(SecurityContextPersistenceFilter.java :105)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.FilterC hainProxy.doFilterInternal(FilterChainPr oxy.java:214)
at org.springframework.security.web.FilterC hainProxy.doFilter(FilterChainProxy.java :177)
at org.springframework.web.filter.Delegatin gFilterProxy.invokeDelegate(DelegatingFi lterProxy.java:346)
at org.springframework.web.filter.Delegatin gFilterProxy.doFilter(DelegatingFilterPr oxy.java:262)
at org.apache.catalina.core.ApplicationFilt erChain.internalDoFilter(ApplicationFilt erChain.java:239)
at org.apache.catalina.core.ApplicationFilt erChain.doFilter(ApplicationFilterChain. java:206)
at org.springframework.web.filter.Character EncodingFilter.doFilterInternal(Characte rEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRe questFilter.doFilter(OncePerRequestFilte r.java:107)
at org.apache.catalina.core.ApplicationFilt erChain.internalDoFilter(ApplicationFilt erChain.java:239)
at org.apache.catalina.core.ApplicationFilt erChain.doFilter(ApplicationFilterChain. java:206)
at org.apache.catalina.core.StandardWrapper Valve.invoke(StandardWrapperValve.java:2 17)
at org.apache.catalina.core.StandardContext Valve.invoke(StandardContextValve.java:1 06)
at org.apache.catalina.authenticator.Authen ticatorBase.invoke(AuthenticatorBase.jav a:502)
at org.apache.catalina.core.StandardHostVal ve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportVa lve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAcces sLogValve.invoke(AbstractAccessLogValve. java:616)
at org.apache.catalina.core.StandardEngineV alve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdap ter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11P rocessor.process(AbstractHttp11Processor .java:1091)
at org.apache.coyote.AbstractProtocol$Abstr actConnectionHandler.process(AbstractPro tocol.java:673)
at org.apache.tomcat.util.net.AprEndpoint$S ocketProcessor.doRun(AprEndpoint.java:25 03)
at org.apache.tomcat.util.net.AprEndpoint$S ocketProcessor.run(AprEndpoint.java:2492 )
at java.util.concurrent.ThreadPoolExecutor. runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$ Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThrea d$WrappingRunnable.run(TaskThread.java:6 1)
at java.lang.Thread.run(Thread.java:745)
DEBUG DispatcherServlet [DispatcherServlet.java:1208] Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'exception/exception'; model is {exception=org.hibernate.LazyInitializat ionException: could not initialize proxy - no Session}
org.hibernate.LazyInitializationExceptio n: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitiali zer.initialize(AbstractLazyInitializer.j ava:147)
at org.hibernate.proxy.AbstractLazyInitiali zer.getImplementation(AbstractLazyInitia lizer.java:260)
at org.hibernate.proxy.pojo.javassist.Javas sistLazyInitializer.invoke(JavassistLazy Initializer.java:73)
at model.Product_$$_jvste27_4.setName(Produ ct_$$_jvste27_4.java)
at web.product.AdminProductController.saveP roduct(AdminProductController.java:42)
at sun.reflect.NativeMethodAccessorImpl.inv oke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.inv oke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl .invoke(DelegatingMethodAccessorImpl.jav a:43)
at java.lang.reflect.Method.invoke(Method.j ava:498)
at org.springframework.web.method.support.I nvocableHandlerMethod.doInvoke(Invocable HandlerMethod.java:220)
at org.springframework.web.method.support.I nvocableHandlerMethod.invokeForRequest(I nvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.meth od.annotation.ServletInvocableHandlerMet hod.invokeAndHandle(ServletInvocableHand lerMethod.java:116)
at org.springframework.web.servlet.mvc.meth od.annotation.RequestMappingHandlerAdapt er.invokeHandlerMethod(RequestMappingHan dlerAdapter.java:827)
at org.springframework.web.servlet.mvc.meth od.annotation.RequestMappingHandlerAdapt er.handleInternal(RequestMappingHandlerA dapter.java:738)
at org.springframework.web.servlet.mvc.meth od.AbstractHandlerMethodAdapter.handle(A bstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.Dispatch erServlet.doDispatch(DispatcherServlet.j ava:963)
at org.springframework.web.servlet.Dispatch erServlet.doService(DispatcherServlet.ja va:897)
at org.springframework.web.servlet.Framewor kServlet.processRequest(FrameworkServlet .java:970)
at org.springframework.web.servlet.Framewor kServlet.doPost(FrameworkServlet.java:87 2)
at javax.servlet.http.HttpServlet.service(H ttpServlet.java:648)
at org.springframework.web.servlet.Framewor kServlet.service(FrameworkServlet.java:8 46)
at javax.servlet.http.HttpServlet.service(H ttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilt erChain.internalDoFilter(ApplicationFilt erChain.java:291)
at org.apache.catalina.core.ApplicationFilt erChain.doFilter(ApplicationFilterChain. java:206)
at org.apache.tomcat.websocket.server.WsFil ter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilt erChain.internalDoFilter(ApplicationFilt erChain.java:239)
at org.apache.catalina.core.ApplicationFilt erChain.doFilter(ApplicationFilterChain. java:206)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:317)
at org.springframework.security.web.access. intercept.FilterSecurityInterceptor.invo ke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access. intercept.FilterSecurityInterceptor.doFi lter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.access. ExceptionTranslationFilter.doFilter(Exce ptionTranslationFilter.java:114)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.session .SessionManagementFilter.doFilter(Sessio nManagementFilter.java:137)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.AnonymousAuthenticationFilter.do Filter(AnonymousAuthenticationFilter.jav a:111)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.rememberme.RememberMeAuthenticat ionFilter.doFilter(RememberMeAuthenticat ionFilter.java:158)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.servlet api.SecurityContextHolderAwareRequestFil ter.doFilter(SecurityContextHolderAwareR equestFilter.java:170)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.savedre quest.RequestCacheAwareFilter.doFilter(R equestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.AbstractAuthenticationProcessing Filter.doFilter(AbstractAuthenticationPr ocessingFilter.java:200)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.authent ication.logout.LogoutFilter.doFilter(Log outFilter.java:116)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.csrf.Cs rfFilter.doFilterInternal(CsrfFilter.jav a:124)
at org.springframework.web.filter.OncePerRe questFilter.doFilter(OncePerRequestFilte r.java:107)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at org.springframework.security.web.header. HeaderWriterFilter.doFilterInternal(Head erWriterFilter.java:64)
at org.springframework.web.filter.OncePerRe questFilter.doFilter(OncePerRequestFilte r.java:107)
at org.springframework.security.web.FilterC hainProxy$VirtualFilterChain.doFilter(Fi lterChainProxy.java:331)
at
0
Эксперт Java
 Аватар для KEKCoGEN
2399 / 2224 / 565
Регистрация: 28.12.2010
Сообщений: 8,672
25.01.2017, 22:23
kostrorod, попробуйте навесить аннотацию @Transactional на saveProduct
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
25.01.2017, 22:50  [ТС]
Ошибка сохраняется
0
14 / 14 / 16
Регистрация: 02.03.2013
Сообщений: 27
25.01.2017, 22:51
Покажите код методов:
productService.get(id) и productService.save(product), а также NamedEntity
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
25.01.2017, 23:07  [ТС]
productService
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Service("productService")
public class ProductServiceImpl implements ProductService {
    private final Logger log = LoggerFactory.getLogger(getClass());
 
    @Autowired
    private ProductRepository repository;
 
    @Override
    public Product save(Product product) throws NotFoundException {
        Assert.notNull(product, "Продукт не должен быть пустым");
        log.info("save " + product);
        return repository.save(product);
    }
 
    @Override
    public Product get(Long id) throws NotFoundException {
        log.info("get " + id);
        return ExceptionUtil.checkNotFoundWithId(repository.get(id), id);
    }
 
    @Override
    public List<Product> getAll() {
        log.info("getAll");
        return repository.getAll();
    }
 
    @Override
    public void delete(Long id) {
        log.info("delete" + id);
        repository.delete(id);
    }
}

NamedEntity
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@MappedSuperclass
public class NamedEntity extends BaseEntity {
    @NotEmpty
    @Column(name = "name", nullable = false)
    protected String name;
 
    public NamedEntity() {
    }
 
    protected NamedEntity(Long id, String name) {
        super(id);
        this.name = name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getName() {
        return this.name;
    }
 
    @Override
    public String toString() {
        return name;
    }
}


Добавлено через 8 минут
ExceptionUtil
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ExceptionUtil {
    private ExceptionUtil() {
    }
 
    public static void checkNotFoundWithId(boolean found, Long id) {
        checkNotFound(found, "id=" + id);
    }
 
    public static <T> T checkNotFoundWithId(T object, Long id) {
        return checkNotFound(object, "id=" + id);
    }
 
    public static <T> T checkNotFound(T object, String msg) {
        checkNotFound(object != null, msg);
        return object;
    }
 
    public static void checkNotFound(boolean found, String msg) {
        if (!found) {
            throw new NotFoundException("Данные не найдены для " + msg);
        }
    }
0
14 / 14 / 16
Регистрация: 02.03.2013
Сообщений: 27
25.01.2017, 23:14
и ещё ProductRepository
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
25.01.2017, 23:18  [ТС]
ProductRepository
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
public interface ProductRepository {
 
    Product save (Product product);
 
    Product get(Long id);
 
    List<Product> getAll();
 
    void delete(Long id);
}


ProxyProductRepository
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Transactional(readOnly = true)
public interface ProxyProductRepository extends JpaRepository<Product, Long> {
 
    @Transactional
    @Override
    Product save (Product product);
 
    @Override
    Product getOne(Long id);
 
    @Override
    List<Product> findAll();
 
    @Transactional
    @Override
    void delete(Long id);
}


DataJpaProductRepositoryImpl
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Repository
public class DataJpaProductRepositoryImpl implements ProductRepository {
 
    @Autowired
    private ProxyProductRepository proxy;
 
    @Override
    public Product save(Product product) {
        return proxy.save(product);
    }
 
    @Override
    public Product get(Long id) {
        return proxy.getOne(id);
    }
 
    @Override
    public List<Product> getAll() {
        return proxy.findAll();
    }
 
    @Override
    public void delete(Long id) {
        proxy.delete(id);
    }
}
0
14 / 14 / 16
Регистрация: 02.03.2013
Сообщений: 27
25.01.2017, 23:26
Попробуйте в ProxyProductRepository убрать
Цитата Сообщение от kostrorod Посмотреть сообщение
(readOnly = true)
и также вместо proxy.save(product) вызвать proxy.merge(product)
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
25.01.2017, 23:30  [ТС]
Цитата Сообщение от Skelotron Посмотреть сообщение
proxy.merge(product)
нет такого метода
0
14 / 14 / 16
Регистрация: 02.03.2013
Сообщений: 27
25.01.2017, 23:38
а в конфигурации спринга есть что-то наподобие
XML
1
<tx:annotation-driven />
?
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
25.01.2017, 23:45  [ТС]
XML
1
2
3
4
5
6
7
<!--@Transaction annotation support -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
 
 <!-- Need for Repository abstraction -->
    <jpa:repositories base-package="repository.datajpa" entity-manager-factory-ref="emf"
                      transaction-manager-ref="transactionManager"/>
    <context:component-scan base-package="repository.datajpa"/>
Добавлено через 5 минут
XML
1
2
3
4
<!--Обеспечивает работу с транзакциями в Spring -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf"/>
    </bean>
0
14 / 14 / 16
Регистрация: 02.03.2013
Сообщений: 27
26.01.2017, 00:10
Попробуйте убрать аннотацию @Transactional из Repository-классов и добавить её в ProductServiceImpl класс, а также создать метод в ProductService, в который поместить всю логику из метода saveProduct из класса AdminProductController, чтобы получилось что-то примерно такое
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class AdminProductController {
...
@RequestMapping(value = "/saveproduct", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody Product saveProduct(@RequestParam Long id, @RequestParam("column") String column,
                                             @RequestParam("value") String value ) {
        return productService.saveProduct(id, column, value);
    }
...
 
@Service
@Transactional
class ProductServiceImpl implements ProductService {
...
    public Product saveProduct(Long id, String column, String value) {
        Product product = get(id);
        if (Objects.equals(column, "name")){
            product.setName(value);
        }else if (Objects.equals(column, "description")){
            product.setDescription(value);
        }else if (Objects.equals(column, "price")){
            product.setPrice(Double.parseDouble(value));
        }else if (Objects.equals(column, "discount")){
            product.setDiscount(Integer.parseInt(value));
        }else if (Objects.equals(column, "maxLed")){
            product.setMaxLed(Integer.parseInt(value));
        }
        return save(product);
  }
}
1
 Аватар для KuKu
1563 / 1041 / 94
Регистрация: 17.04.2009
Сообщений: 2,995
26.01.2017, 01:00
Лучший ответ Сообщение было отмечено kostrorod как решение

Решение

Ошибка тут судя по всему:
Java
1
2
3
4
@Transactional(readOnly = true)
public interface ProxyProductRepository extends JpaRepository<Product, Long> {
    Product getOne(Long id);
}
Метод getOne возвращает не сам объект, а "ленивую ссылку" на него. Далее идет попытка использовать эту ленивую ссылку в контроллере, т.е. не в транзакции - поэтому и падает lazy exception. Надо использовать метод findOne или перенести всю логику из контроллера в сервис.

+ хорошая практика использовать @Transactional над реализацией сервисов, а не в интерфейсах или репозиториях, о чем писалось выше. Да и непонятно зачем лишний раз переписывать названия методов в ProxyProductRepository, когда они уже есть в JpaRepository.
1
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
26.01.2017, 09:49  [ТС]
Цитата Сообщение от KuKu Посмотреть сообщение
Метод getOne возвращает не сам объект, а "ленивую ссылку" на него.
Да действительно, даже после переброса логики по совету Skelotron ошибка осталась.
После изменения метода на findOne всё заработало.
А ведь в юзере метод findOne стоял. Я и думал, почему там все работает, а тут нет.
Благодарю за разбор полётов. Несколько дней убил на эту ошибку.

Добавлено через 15 минут
Решил добить этом метод. Поднастроил транзакции. Добавил подхватывание транзакции если нет и заработало с методом getOne

ProductService
Кликните здесь для просмотра всего текста
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Secured("ROLE_ADMIN")
public interface ProductService {
    @Transactional(propagation = Propagation.REQUIRED)
    Product save (Product product) throws NotFoundException;
 
    Product get(Long id) throws NotFoundException;
 
    List<Product> getAll();
 
    @Transactional
    void delete(Long id);
 
    @Transactional(propagation = Propagation.REQUIRED)
    Product update(Long id, String column, String value);
}
0
Эксперт Java
 Аватар для KEKCoGEN
2399 / 2224 / 565
Регистрация: 28.12.2010
Сообщений: 8,672
26.01.2017, 10:13
kostrorod, зачем вам транзакции на простых методах?
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
26.01.2017, 11:03  [ТС]
Цитата Сообщение от KEKCoGEN Посмотреть сообщение
зачем вам транзакции на простых методах?
save и delete простые методы? Вдруг в продакшен связь нарушится и что-то пойдёт не так, нужно откатить изменения.
0
Эксперт Java
 Аватар для KEKCoGEN
2399 / 2224 / 565
Регистрация: 28.12.2010
Сообщений: 8,672
26.01.2017, 11:05
Цитата Сообщение от kostrorod Посмотреть сообщение
Вдруг в продакшен связь нарушится и что-то пойдёт не так, нужно откатить изменения.

Цитата Сообщение от kostrorod Посмотреть сообщение
@Override
* * public Product save(Product product) throws NotFoundException {
* * * * Assert.notNull(product, "Продукт не должен быть пустым");
* * * * log.info("save " + product);
* * * * return repository.save(product);
* * }
Цитата Сообщение от kostrorod Посмотреть сообщение
@Override
* * public void delete(Long id) {
* * * * log.info("delete" + id);
* * * * repository.delete(id);
* * }
Что именно вы собираетесь откатывать в этих методах?
0
39 / 28 / 8
Регистрация: 14.04.2012
Сообщений: 249
26.01.2017, 11:25  [ТС]
Цитата Сообщение от KEKCoGEN Посмотреть сообщение
Что именно вы собираетесь откатывать в этих методах?
Не знаю, что вы предлагаете удалить транзакции?
0
Эксперт Java
378 / 370 / 114
Регистрация: 30.06.2010
Сообщений: 1,445
26.01.2017, 11:49
репозитории не должны открывать транзакции (кроме редких случаев), управление транзакциями должно осуществляться на уровне сервисов, а т.к. репозитории должны вызываться только из уровня сервисов, то они всегда будут в транзакции
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
26.01.2017, 11:49
Помогаю со студенческими работами здесь

Spring MVC + Hibernate project
Проконсультируйте, пожалуйста, по проекту дипломному. Функциональность(см. Use Case) как на этом сайте - https://hosgeldi.com/pol/ +...

Spring MVC, Hibernate - получаю exception
Пытаюсь подключить БД, используется Spring MCS и Hibernate, получаю исключение: type Exception report message Request processing...

Session scoped бины в Spring при сохранении в Redis через Spring Session
Меня интерисует опыт по части использования Spring бинов со скоупом Session. Пример кода, который приведен чуть ниже будет отлично...

Трудности с выводом данных Spring MVC + Hibernate
Проблема в том что я не могу вывести свои данные и таблицы которые есть в проекте даже если я удаляю те файлы все все равно оно выводит их....

Spring MVC + Hibernate, java.lang.ClassNotFoundException
Здравствуйте. Делаю сампл по вышеукаазаных технологиях, получаю следующие ошибки: org.apache.jasper.JasperException:...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а привычная функция main(). . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru