Ошибка «javax.persistence.TransactionRequiredException» при использовании AOP - PullRequest
0 голосов
/ 29 апреля 2020

У меня есть проект, который показывает данные из базы данных (PL SQL), используя Spring- MVC и Hibernate. Я решил добавить AOP в проект, но на первом этапе я получил javax.persistence.TransactionRequiredException. Когда я удаляю аннотацию @Aspect, я не получаю исключения. Исключение:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)

Вот коды: Один из моих доменов:

package com.okan.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.ApplicationScope;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.context.annotation.SessionScope;

@Component
@SessionScope
@Entity
@Table(name = "LOGIN_DB")
public class Kullanici {

    @Id
    @Column(name = "USER_NAME")
    @NotEmpty(message = "Boş geçilemez gardaş")
    private String kullaniciAdi;

    @Column(name = "PASSWORD")
    @NotEmpty(message = "Boş geçilemez gardaş")
    private String sifre;

    @Column(name = "NAME")
    private String ad;

    @Column(name = "SURNAME")
    private String soyad;

    @Column(name = "ROLE")
    private String rol;

    @Column(name = "DURUM")
    private Integer durum;


    public Integer getDurum() {
        return durum;
    }

    public void setDurum(Integer durum) {
        this.durum = durum;
    }

    public String getKullaniciAdi() {
        return kullaniciAdi;
    }

    public void setKullaniciAdi(String kullaniciAdi) {
        this.kullaniciAdi = kullaniciAdi;
    }

    public String getSifre() {
        return sifre;
    }

    public void setSifre(String sifre) {
        this.sifre = sifre;
    }

    public String getAd() {
        return ad;
    }

    public void setAd(String ad) {
        this.ad = ad;
    }

    public String getSoyad() {
        return soyad;
    }

    public void setSoyad(String soyad) {
        this.soyad = soyad;
    }

    public String getRol() {
        return rol;
    }

    public void setRol(String rol) {
        this.rol = rol;
    }

    public Kullanici(String kullaniciAdi, String sifre, String ad, String soyad, String rol) {
        this.kullaniciAdi = kullaniciAdi;
        this.sifre = sifre;
        this.ad = ad;
        this.soyad = soyad;
        this.rol = rol;
    }

    public Kullanici() {
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Kullanici other = (Kullanici) obj;
        if (kullaniciAdi == null) {
            if (other.kullaniciAdi != null)
                return false;
        } else if (!kullaniciAdi.equals(other.kullaniciAdi))
            return false;
        if (sifre == null) {
            if (other.sifre != null)
                return false;
        } else if (!sifre.equals(other.sifre))
            return false;
        return true;
    }

}

Один из контроллеров:

package com.okan.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.okan.domain.Kullanici;
import com.okan.service.KullaniciServisi;

@Controller
public class AnaSayfaController {

    @Autowired
    KullaniciServisi kullaniciServisi;

    @GetMapping("/")
    public String girisEkrani(Model m) {

        Kullanici k1= kullaniciServisi.kullaniciGetir();

        m.addAttribute("kullanici", k1);
        return "giris-ekrani";
    }

    @RequestMapping("/index")
    public String anaSayfa() {
        if(!kullaniciServisi.kullaniciVarMı())
            return "redirect:/";
        return "index";
    }

    @PostMapping("/girisYap")
    public String girisYap(@Valid @ModelAttribute("kullanici") Kullanici kullanici, BindingResult br) {
        String kullaniciAdi=kullanici.getKullaniciAdi();
        String sifre=kullanici.getSifre();
        if(br.hasErrors())
            return "giris-ekrani";
        if(kullaniciServisi.girisYap(kullaniciAdi, sifre))
        return "index";
        br.rejectValue("kullaniciAdi", "error.kullanici", "Hatalı kullanıcı adı/şifre!");
        return "giris-ekrani";
    }
}

Одна из служб:

package com.okan.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.okan.dao.KullaniciDAO;
import com.okan.domain.Kullanici;
import com.okan.domain.Ogretmen;

@Service
public class KullaniciServisiImpl implements KullaniciServisi {

    @Autowired
    KullaniciDAO kullaniciDAO;

    @Transactional
    @Override
    public Kullanici kullaniciGetir() {

        return kullaniciDAO.kullaniciGetir();
//      return null;
    }

    @Transactional
    @Override
    public boolean girisYap(String kullaniciAdi, String sifre) {

        return kullaniciDAO.girisYap(kullaniciAdi, sifre);
    }

    @Transactional
    @Override
    public boolean kullaniciVarMı() {
        // TODO Auto-generated method stub
        return kullaniciDAO.kullaniciVarMı();
    }

    @Transactional
    @Override
    public Map<Integer, Ogretmen> getOgretmenler() {
        // TODO Auto-generated method stub
        return kullaniciDAO.getOgretmenler();
    }



}

DAO:

package com.okan.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.okan.domain.Kullanici;
import com.okan.domain.Ogretmen;

@Repository
public class KullaniciDAOImlp implements KullaniciDAO {



    @Autowired
    Kullanici kullanici;

    @Autowired
    SessionFactory sessionFactory;

    @Override
    public Kullanici kullaniciGetir() {

        return kullanici;
    }

    @Transactional
    @Override
    public boolean girisYap(String kullaniciAdi, String sifre) {
        Session session = sessionFactory.getCurrentSession();
        Kullanici kullaniciKontrol;
        try {
            kullaniciKontrol = session.get(Kullanici.class, kullaniciAdi);          
            if (kullaniciKontrol.getSifre().equals(sifre)) {
                kullanici.setAd(kullaniciKontrol.getAd());
                kullanici.setSoyad(kullaniciKontrol.getSoyad());
                kullanici.setKullaniciAdi(kullaniciAdi);
                kullanici.setSifre(sifre);
                kullanici.setRol(kullaniciKontrol.getRol());
                return true;
            }
        } catch (Exception e) {

        }

        return false;
    }

    @Override
    public boolean kullaniciVarMı() {
        if(kullanici.getKullaniciAdi()==null)
            return false;
        return true;
    }

    @Override
    public Map<Integer, Ogretmen> getOgretmenler() {
        Session session = sessionFactory.getCurrentSession();
        List<Ogretmen> ogretmenList=session.createQuery("from Ogretmen", Ogretmen.class).getResultList();
        Map<Integer, Ogretmen> getOgretmenler=new HashMap<Integer, Ogretmen>();
        for (Ogretmen ogr : ogretmenList){
            getOgretmenler.put(ogr.getId(), ogr);
        }
        return getOgretmenler;
    }

}

AOPConfig. java

package com.okan.aop;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.okan")
@EnableAspectJAutoProxy
public class AOPConfig {

}

AspectDemo. java

package com.okan.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Aspect
@Component
//@Repository
public class AspectDemo {

    @Transactional
    @Pointcut("execution (* getId*(..))")
    public void getPC() {

    }

    @Transactional
    @Before("getPC()")
    public void getAdvice() {
        System.out.println("*\nBir Get methodu çalıştı\n*");
    }
}

spring- mvc -сервлет. xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Step 3: Enable component scanning -->
    <context:component-scan base-package="com.okan" />

    <!-- Step 4: Enable conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Step 5: Spring MVC view resolver Configuration -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>


   <!-- Step 1: Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="oracle.jdbc.OracleDriver" />
        <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521/xe" />
        <property name="user" value="jsf" />
        <property name="password" value="jsf" /> 

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="3" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>  

    <!-- Step 2: Hibernate session factory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.okan.domain" />
        <property name="hibernateProperties">
           <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>    

    <!-- Step 3: Hibernate transaction manager -->
    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Step 4: Enable configuration of transaction annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" /> 

    <!--Resources dosyalarını okuyacağım yer -->
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

    <!--Hata mesajlarını okuyacağım yer -->
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames" value="resources/message" />
    </bean>

<!--    <bean id="kullanici" 
        class="com.okan.domain.kullanici">
        <property name="kullanici" ref="kullanici"/>
    </bean>
    -->
</beans>

Стоит ли упоминать об АОП в весенне-mvc -сервлете. xml? Если да, то как? Спасибо.

...