Данные вызова связи один ко многим реализованы с помощью таблицы соединений (3 таблицы) - PullRequest
0 голосов
/ 09 июля 2019

Я работаю над веб-приложением на Java, используя Spring MVC и Hibernate в качестве фреймворка.

Мне нужно написать код javascript в JSP, где мне нужно вызывать данные из другой таблицы, которая связана с основной таблицей с помощью третьей таблицы, чтобы сохранить реализацию «один ко многим».

Здесь у меня есть основной стол tblDiscipline, второй стол tblCompetenteProf и таблица соединения tblCompetenteProfDisciplina, и я хочу получить список competenteProf, где idDisciplina = x.

Это то, что я пробовал до сих пор:

<td class="font-weight-bold">6.1</td>
            <td class="font-weight-bold">Competențe profesionale</td>
                <td>${disciplina.tblcompetenteprofdisciplinasByIdDisciplin}</td>
CREATE TABLE tblDiscipline
(
    idDisciplina   INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    idUniversitate INT                            NOT NULL,
    idFacultate    INT                            NOT NULL,
    idDomeniu      INT                            NOT NULL,
    idDepartament  INT                            NOT NULL
) ENGINE = INNODB;

CREATE TABLE tblCompetenteProf
(
    idCompetentaProf  INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    codCompetentaProf VARCHAR(3),
    competentaProf    LONGTEXT
) ENGINE = INNODB;

CREATE TABLE tblCompetenteProfDisciplina
(
    idCompetentaProfDisciplina INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
    idCompetentaProf           INT                            NOT NULL,
    idDisciplina               INT                            NOT NULL,

    CONSTRAINT FOREIGN KEY (idDisciplina)
        REFERENCES tblDiscipline (idDisciplina) ON DELETE CASCADE ON UPDATE CASCADE,

    CONSTRAINT FOREIGN KEY (idCompetentaProf)
        REFERENCES tblCompetenteProf (idCompetentaProf) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = INNODB;

Мои классы сущностей выглядят так

TblDiscipline:

@Entity
@Audited
package com.pages.model;

import javax.persistence.*;
import java.util.*;
import org.hibernate.envers.Audited;

@Entity
@Audited
public class Tbldiscipline {
    private int idDisciplina;
    private int idUniversitate;
    private int idFacultate;
    private int idDomeniu;
    private int idDepartament;
    private Collection<Tblcompetenteprofdisciplina>tblcompetenteprofdisciplinasByIdDisciplina;
 @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idDisciplina", nullable = false)
    public int getIdDisciplina() {
        return idDisciplina;
    }

    public void setIdDisciplina(int idDisciplina) {
        this.idDisciplina = idDisciplina;
    }

    @Basic
    @Column(name = "idUniversitate", nullable = true)
    public int getIdUniversitate() {
        return idUniversitate;
    }

    public void setIdUniversitate(int idUniversitate) {
        this.idUniversitate = idUniversitate;
    }

    @Basic
    @Column(name = "idFacultate", nullable = true)
    public int getIdFacultate() {
        return idFacultate;
    }

    public void setIdFacultate(int idFacultate) {
        this.idFacultate = idFacultate;
    }

    @Basic
    @Column(name = "idDomeniu", nullable = true)
    public int getIdDomeniu() {
        return idDomeniu;
    }

    public void setIdDomeniu(int idDomeniu) {
        this.idDomeniu = idDomeniu;
    }

    @Basic
    @Column(name = "idDepartament", nullable = true)
    public int getIdDepartament() {
        return idDepartament;
    }

    public void setIdDepartament(int idDepartament) {
        this.idDepartament = idDepartament;
    }

    @OneToMany(mappedBy = "tbldisciplineByIdDisciplina")
    public Collection<Tblcompetenteprofdisciplina> getTblcompetenteprofdisciplinasByIdDisciplina() {
        return tblcompetenteprofdisciplinasByIdDisciplina;
    }



TblCompetenteProfDisciplina:


    private int idCompetentaProfDisciplina;
        private int idCompetentaProf;
        private int idDisciplina;
        private Tblcompetenteprof tblcompetenteprofByIdCompetentaProf;
        private Tbldiscipline tbldisciplineByIdDisciplina;

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "idCompetentaProfDisciplina", nullable = false)
        public int getIdCompetentaProfDisciplina() {
            return idCompetentaProfDisciplina;
        }

        public void setIdCompetentaProfDisciplina(int idCompetentaProfDisciplina) {
            this.idCompetentaProfDisciplina = idCompetentaProfDisciplina;
        }

        @Basic
        @Column(name = "idCompetentaProf", nullable = false)
        public int getIdCompetentaProf() {
            return idCompetentaProf;
        }

        public void setIdCompetentaProf(int idCompetentaProf) {
            this.idCompetentaProf = idCompetentaProf;
        }

        @Basic
        @Column(name = "idDisciplina", nullable = false)
        public int getIdDisciplina() {
            return idDisciplina;
        }

        public void setIdDisciplina(int idDisciplina) {
            this.idDisciplina = idDisciplina;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Tblcompetenteprofdisciplina that = (Tblcompetenteprofdisciplina) o;
            return idCompetentaProfDisciplina == that.idCompetentaProfDisciplina &&
                    idCompetentaProf == that.idCompetentaProf &&
                    idDisciplina == that.idDisciplina;
        }
            @ManyToOne(fetch = FetchType.EAGER)
            @JoinColumn(name = "idCompetentaProf", referencedColumnName = "idCompetentaProf",
                    nullable = false, insertable = false, updatable = false)
            public Tblcompetenteprof getTblcompetenteprofByIdCompetentaProf() {
                return tblcompetenteprofByIdCompetentaProf;
            }

            public void setTblcompetenteprofByIdCompetentaProf(Tblcompetenteprof tblcompetenteprofByIdCompetentaProf) {
                this.tblcompetenteprofByIdCompetentaProf = tblcompetenteprofByIdCompetentaProf;
            }

            @ManyToOne(fetch = FetchType.EAGER)
            @JoinColumn(name = "idDisciplina", referencedColumnName = "idDisciplina",
                    nullable = false, insertable = false, updatable = false)
            public Tbldiscipline getTbldisciplineByIdDisciplina() {
                return tbldisciplineByIdDisciplina;
            }

            public void setTbldisciplineByIdDisciplina(Tbldiscipline tbldisciplineByIdDisciplina) {
                this.tbldisciplineByIdDisciplina = tbldisciplineByIdDisciplina;
            }

Чтобы получить список всех строк tblCompetenteProf WHERE idDisciplina = 1 (например). disciplina - это имя атрибута, определенное в моем контроллере:

@Controller
public class DisciplinaController {
    private static final Logger logger = Logger.getLogger(DisciplinaController.class);

    public DisciplinaController() {
        System.out.println("DisciplinaController()");
    }

    @Autowired
    private DisciplinaService disciplinaService;
    @Autowired
    private CompetentaProfService competentaProfService;

    @RequestMapping(value = "/disciplina")
    public ModelAndView listDisciplina(ModelAndView model) throws IOException {
        List<Tbldiscipline> listDisciplina = disciplinaService.getAllDiscipline();
        model.addObject("listDisciplina", listDisciplina);
        model.setViewName("Disciplina");
        return model;
    }

    @RequestMapping(value = "/newDisciplina", method = RequestMethod.GET)
    public ModelAndView newDisciplina(ModelAndView model){
        Tbldiscipline disciplina = new Tbldiscipline();
        model.addObject("disciplina", disciplina);
        model.setViewName("DisciplinaFormular");
        return model;
    }

    @RequestMapping(value = "/saveDisciplina", method = RequestMethod.POST)
    public ModelAndView saveDisciplina(@ModelAttribute Tbldiscipline disciplina){
        if (disciplina.getIdDisciplina() == 0){
            disciplinaService.addDisciplina(disciplina);
        } else{
            disciplinaService.updateDisciplina(disciplina);
        }

        return new ModelAndView("redirect:/disciplina");
    }


    @RequestMapping(value = "/deleteDisciplina", method = RequestMethod.GET)
    public ModelAndView deleteDisciplina(HttpServletRequest request) {
        int disciplinaid = Integer.parseInt(request.getParameter("idDisciplina"));
        disciplinaService.deleteDisciplina(disciplinaid);
        return new ModelAndView("redirect:/disciplina");
    }

    @RequestMapping(value = "/editDisciplina", method = RequestMethod.GET)
    public ModelAndView editDisciplina(HttpServletRequest request){
        int idDisciplina = Integer.parseInt(request.getParameter("idDisciplina"));
        Tbldiscipline disciplina = disciplinaService.getDisciplina(idDisciplina);
        ModelAndView model = new ModelAndView("DisciplinaFormular");
        model.addObject("disciplina", disciplina);

        return model;
    }

    @RequestMapping(value = "/viewDisciplina", method = RequestMethod.GET)
    public ModelAndView updateDisciplina(HttpServletRequest request){
        int idDisciplina = Integer.parseInt(request.getParameter("idDisciplina"));
        Tbldiscipline disciplina = disciplinaService.getDisciplina(idDisciplina);
        ModelAndView model = new ModelAndView("DisciplinaVizualizare");
        model.addObject("disciplina", disciplina);

        return model;
    }


    @RequestMapping(value = "/viewPDF", method = RequestMethod.POST)
    public ModelAndView viewPDF(@ModelAttribute DisciplineListContainer disciplineListContainer) throws Exception{
        List<Tbldiscipline> tbldisciplineList = disciplineListContainer.getTbldisciplines();
        return new ModelAndView("viewPDF", "Disciplina", tbldisciplineList);
    }

    @RequestMapping(value = "/downloadPDF", method = RequestMethod.GET)
    public ModelAndView downloadExcel() {
        List<Tbldiscipline> listDisciplina = new ArrayList<Tbldiscipline>();
        return new ModelAndView("pdfView", "listDisciplina", listDisciplina);
    }

    @RequestMapping(value = "/downloadPDFDisciplina", method = RequestMethod.GET)
    public ModelAndView downloadDisciplina(HttpServletRequest request){
        int idDisciplina = Integer.parseInt(request.getParameter("idDisciplina"));
        Tbldiscipline disciplina = disciplinaService.getDisciplina(idDisciplina);
        return new ModelAndView("pdfViewDisciplina", "disciplina", disciplina);
    }
My DisciplineView looks like this:

```javascript

    <c:set var="contextPath" value="${pageContext.request.contextPath}"/>

    <!DOCTYPE html>

    <body>
        <form action="/viewDisciplina" method="get">
            <div align="center">
            <div class="container">

                <p style="padding-bottom: 50px"></p>

                <h1>
                    Disciplina: ${disciplina.denumireDisciplina}
                </h1>
            <h2>6.Competențe specifice acumulate</h2>
            <table class="table table-bordered">
                <tbody>
                <tr>
                    <td class="font-weight-bold">6.1</td>
                    <td class="font-weight-bold">Competențe profesionale</td>
                    <td>${disciplina.tblcompetenteprofdisciplinasByIdDisciplina}</td>
                </tr>

                </tbody>
            </table>
        </form>
    </body>

</html>

Это ошибка, которую я получаю:

HTTP ERROR 500 Проблема доступа / viewDisciplina. Причина:

Server Error Caused by: org.apache.jasper.JasperException: An exception occurred processing JSP page

/ WEB-INF / pages / DisciplinaVizualizare.jsp в строке 253

250: 251: 6,1 252: Competen? E profesionale 253:
$ {schollina.tblcompetenteprofdisciplinasByIdDisciplina} 254: 255: 256: <% - <br> $ {Disciplina.tblcompetenteprofdisciplinasByIdDisciplina.} -%>

Stacktrace: в org.apache.jasper.servlet.JspServletWrapper.handleJspException (JspServletWrapper.java:568) в org.apache.jasper.servlet.JspServletWrapper.service (JspServletWrapper.java:470) в org.apache.jasper.servlet.JspServlet.serviceJspFile (JspServlet.java:405) в org.apache.jasper.servlet.JspServlet.service (JspServlet.java:349) в org.eclipse.jetty.jsp.JettyJspServlet.service (JettyJspServlet.java:107) в javax.servlet.http.HttpServlet.service (HttpServlet.java:790) в org.eclipse.jetty.servlet.ServletHolder.handle (ServletHolder.java:808) в org.eclipse.jetty.servlet.ServletHandler.doHandle (ServletHandler.java:587) в org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:143) в org.eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:595) в org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:223) в org.eclipse.jetty.server.handler.ContextHandler.doHandle (ContextHandler.java:1127) в org.eclipse.jetty.servlet.ServletHandler.doScope (ServletHandler.java:515) в org.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185) в org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1061) в org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:141) в org.eclipse.jetty.server.Dispatcher.forward (Dispatcher.java:191) в org.eclipse.jetty.server.Dispatcher.forward (Dispatcher.java:72) в org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel (InternalResourceView.java:168) в org.springframework.web.servlet.view.AbstractView.render (AbstractView.java:303) в org.springframework.web.servlet.DispatcherServlet.render (DispatcherServlet.java:1244) в org.springframework.web.servlet.DispatcherServlet.processDispatchResult (DispatcherServlet.java:1027) в org.springframework.web.servlet.DispatcherServlet.doDispatch (DispatcherServlet.java:971) в org.springframework.web.servlet.DispatcherServlet.doService (DispatcherServlet.java:893) в org.springframework.web.servlet.FrameworkServlet.processRequest (FrameworkServlet.java:970) в org.springframework.web.servlet.FrameworkServlet.doGet (FrameworkServlet.java:861) в javax.servlet.http.HttpServlet.service (HttpServlet.java:687) в org.springframework.web.servlet.FrameworkServlet.service (FrameworkServlet.java:846) в javax.servlet.http.HttpServlet.service (HttpServlet.java:790) в org.eclipse.jetty.servlet.ServletHolder.handle (ServletHolder.java:808) вorg.eclipse.jetty.servlet.ServletHandler.doHandle (ServletHandler.java:587) в org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:143) в org.eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:577) в org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:223) в org.eclipse.jetty.server.handler.ContextHandler.doHandle (ContextHandler.java:1127) в org.eclipse.jetty.servlet.ServletHandler.doScope (ServletHandler.java:515) в org.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185) в org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1061) в org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:141) в org.eclipse.jetty.server.handler.ContextHandlerCollection.handle (ContextHandlerCollection.java:215) в org.eclipse.jetty.server.handler.HandlerCollection.handle (HandlerCollection.java:110) в org.eclipse.jetty.server.handler.HandlerWrapper.handle (HandlerWrapper.java:97) в org.eclipse.jetty.server.Server.handle (Server.java:499) в org.eclipse.jetty.server.HttpChannel.handle (HttpChannel.java:310) в org.eclipse.jetty.server.HttpConnection.onFillable (HttpConnection.java:257) в org.eclipse.jetty.io.AbstractConnection $ 2.run (AbstractConnection.java:540) в org.eclipse.jetty.util.thread.QueuedThreadPool.runJob (QueuedThreadPool.java:635) в org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.run (QueuedThreadPool.java:555) at java.lang.Thread.run (Thread.java:745) Причина: org.hibernate.LazyInitializationException: не удалось лениво инициализировать коллекция ролей: com.pages.model.Tbldiscipline.tblcompetenteprofdisciplinasByIdDisciplina, не удалось инициализировать прокси - нет сеанса в org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException (AbstractPersistentCollection.java:576) в org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded (AbstractPersistentCollection.java:215) в org.hibernate.collection.internal.AbstractPersistentCollection.initialize (AbstractPersistentCollection.java:555) в org.hibernate.collection.internal.AbstractPersistentCollection.read (AbstractPersistentCollection.java:143) в org.hibernate.collection.internal.PersistentBag.toString (PersistentBag.java:526) в org.apache.el.lang.ELSupport.coerceToString (ELSupport.java:426) в org.apache.el.lang.ELSupport.coerceToType (ELSupport.java:446) в org.apache.el.ExpressionFactoryImpl.coerceToType (ExpressionFactoryImpl.java:47) в javax.el.ELContext.convertToType (ELContext.java:232) в org.apache.el.ValueExpressionImpl.getValue (ValueExpressionImpl.java:189) в org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate (PageContextImpl.java:956) в org.apache.jsp.WEB_002dINF.pages.DisciplinaVizualizare_jsp._jspService (DisciplinaVizualizare_jsp.java:489) в org.apache.jasper.runtime.HttpJspBase.service (HttpJspBase.java:70) в javax.servlet.http.HttpServlet.service (HttpServlet.java:790) в org.apache.jasper.servlet.JspServletWrapper.service (JspServletWrapper.java:432) ... еще 47 Вызвано: org.hibernate.LazyInitializationException: не удалось лениво инициализировать коллекцию ролей: com.pages.model.Tbldiscipline.tblcompetenteprofdisciplinasByIdDisciplina, не удалось инициализировать прокси - нет сеанса в org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException (AbstractPersistentCollection.java:576) в org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded (AbstractPersistentCollection.java:215) в org.hibernate.collection.internal.AbstractPersistentCollection.initialize (AbstractPersistentCollection.java:555) вorg.hibernate.collection.internal.AbstractPersistentCollection.read (AbstractPersistentCollection.java:143) в org.hibernate.collection.internal.PersistentBag.toString (PersistentBag.java:526) в org.apache.el.lang.ELSupport.coerceoELSupport.java:426) в org.apache.el.lang.ELSupport.coerceToType (ELSupport.java:446) в org.apache.el.ExpressionFactoryImpl.coerceToType (ExpressionFactoryImpl.java:47Tecon.Text.TecontextToTeTeText.Tecontext)(ELContext.java:232) в org.apache.el.ValueExpressionImpl.getValue (ValueExpressionImpl.java:189) в org.apache.jasper.runtime.PageContextImpl.pprietaryEvaluate (PageContextImpl.jspg. Atache) at9.WEB_002dINF.pages.DisciplinaVizualizare_jsp._jspService (DisciplinaVizualizare_jsp.java:489) в org.apache.jasper.runtime.HttpJspBase.service (HttpJspBase.java:70) htpv.tvв org.apache.jasper.servlet.JspServletWrapper.service (JspServletWrapper.java:432) в org.apache.jasper.servlet.JspServlet.serviceJspFile (JspServlet.java:405) в org.apache.jasper.servlet.JspServlet.service (JspServlet.java:349) в org.eclipse.jetty.jsp.JettyJspServlet.service (JettyJspServletserv: javservice) java.http.HttpServlet.service (HttpServlet.java:790) в org.eclipse.jetty.servlet.ServletHolder.handle (ServletHolder.java:808) в org.eclipse.jetty.servlet.ServletHandlerj ServletHandler.Herler) в org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:143) в org.eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:595) в org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:223) в org.eclipse.jetty.server.handler.ContextHandler.doHandle (ContextHandler.java:1127) в org.eclipse.jetty.servlet.ServletHandler.jSvler.doScope (515) в org.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185) в org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1061) в org.eclipse.jet.server.handler.ScopedHandler.handle (ScopedHandler.java:141) в org.eclipse.jetty.server.Dispatcher.forward (Dispatcher.java:191) в org.eclipse.jetty.server.Dispatcher.forward (Dispatcher.java:72)в org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel (InternalResourceView.java:168) в org.springframework.web.servlet.view.AbstractView.render (AbstractView.java:303) в org.springframelet.web.DispatcherServlet.render (DispatcherServlet.java:1244) в org.springframework.web.servlet.DispatcherServlet.processDispatchResult (DispatcherServlet.java:1027) в org.springframework.web.servlet.ervisserv (Dispatcher)org.springframework.web.FrameworkServlet.java:861) на javax.servlet.http.HttpServlet.service (HttpServlet.java:687) на org.springframework.web.servlet.FrameworkServlet.service (FrameworkServlet.java:846) на javax.servlet.http.HttpServlet.service (HttpServlet.java:790) на org.eclipse.jetty.letol.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serv.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.Serlet.(ServletHolder.java:808) в org.eclipse.jetty.servlet.ServletHandler.doHandle (ServletHandler.java:587) в org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java3): 14eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:577) в org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:223) в org.eclipse.jetty.server.Handler.Conte.doHandle (ContextHandler.java:1127) в org.eclipse.jetty.servlet.ServletHandler.doScope (ServletHandler.java:515) вorg.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185) в org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1061) в org.eclipse.jetty.ser.ОбработчикJava: 110) в org.eclipse.jetty.server.handler.HandlerWrapper.handle (HandlerWrapper.java:97) в org.eclipse.jetty.server.Server.handle (Server.java:499) в org.eclipse.jetty.server.HttpChannel.handle (HttpChannel.java:310) в org.eclipse.jetty.server.HttpConnection.onFillable (HttpConnection.java:257) в org.eclipse.jetty.io.AbstractConnection $ 2.rjavaConnection:540) по адресу org.eclipse.jetty.util.thread.QueuedThreadPool.runJob (QueuedThreadPool.java:635) по адресу org.eclipse.jetty.util.thread.QueuedThreadPool $ 3.Thread.run (Thread.java:745)

DisciplineController:

I have no errors. What I am actually trying to do is to obtain something like:

        <tr>
            <td class="font-weight-bold">6.1</td>
            <td class="font-weight-bold">Competențe profesionale</td>
            <td>${disciplina.tblcompetenteprofdisciplinasByIdDisciplin}</td>
        </tr>


Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...