Spring boot: Hibernate аннотация - PullRequest
0 голосов
/ 09 мая 2019

Я начинаю весеннюю загрузку, и у меня возникла проблема с аннотацией ManyToMany и ассоциацией класса

У меня проблема с настройкой отношения один ко многим в моем аннотированном объекте.

Я впервые использую Hibernate и не могу заставить его работать со своей схемой. У меня есть следующее: изображение моей диаграммы: [1]: https://zupimages.net/up/19/19/9flp.png "Диаграмма"

the error is :

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-05-09 13:17:56.020  INFO 10668 --- [  restartedMain] c.p.pfa.projetpfa.ProjetpfaApplication   : Starting ProjetpfaApplication on DESKTOP-QO4NQ82 with PID 10668 (C:\Users\mr-el\Desktop\BOOTSPRING\projetpfa\target\classes started by mr-el in C:\Users\mr-el\Desktop\BOOTSPRING\projetpfa)
2019-05-09 13:17:56.025  INFO 10668 --- [  restartedMain] c.p.pfa.projetpfa.ProjetpfaApplication   : No active profile set, falling back to default profiles: default
2019-05-09 13:17:56.407  INFO 10668 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-05-09 13:17:56.408  INFO 10668 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-05-09 13:17:57.615  INFO 10668 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-09 13:17:57.691  INFO 10668 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 65ms. Found 1 repository interfaces.
2019-05-09 13:17:58.284  INFO 10668 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b0ecf46f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-09 13:17:58.713  INFO 10668 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8443 (http)
2019-05-09 13:17:58.764  INFO 10668 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-09 13:17:58.764  INFO 10668 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-05-09 13:17:58.922  INFO 10668 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-09 13:17:58.922  INFO 10668 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2514 ms
2019-05-09 13:17:59.490  INFO 10668 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-05-09 13:17:59.596  INFO 10668 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-05-09 13:17:59.651  INFO 10668 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-05-09 13:17:59.713  INFO 10668 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.9.Final}
2019-05-09 13:17:59.721  INFO 10668 --- [  restartedMain] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-05-09 13:17:59.851  INFO 10668 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-05-09 13:18:00.610  INFO 10668 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-05-09 13:18:01.053  WARN 10668 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.projet.pfa.projetpfa.models.Competence, at table: formateur, for columns: [org.hibernate.mapping.Column(competences)]
2019-05-09 13:18:01.055  INFO 10668 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-05-09 13:18:01.062  INFO 10668 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2019-05-09 13:18:01.066  INFO 10668 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-09 13:18:01.087  INFO 10668 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-09 13:18:01.096 ERROR 10668 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.projet.pfa.projetpfa.models.Competence, at table: formateur, for columns: [org.hibernate.mapping.Column(competences)]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at com.projet.pfa.projetpfa.ProjetpfaApplication.main(ProjetpfaApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_201]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.4.RELEASE.jar:2.1.4.RELEASE]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: com.projet.pfa.projetpfa.models.Competence, at table: formateur, for columns: [org.hibernate.mapping.Column(competences)]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:402) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 21 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: com.projet.pfa.projetpfa.models.Competence, at table: formateur, for columns: [org.hibernate.mapping.Column(competences)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:486) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:453) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:226) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:624) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.mapping.RootClass.validate(RootClass.java:267) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:466) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) ~[hibernate-core-5.3.9.Final.jar:5.3.9.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 25 common frames omitted

Класс Fromateur:

package com.projet.pfa.projetpfa.models;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.Entity;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;


@Entity
@Table(name="Formateur")
public class Formateur {


    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long idForamteur;
    private String NomFormateur;
    private String PrenomFormateur;
    private String EmailFormateur;
    private String TeleFormateur;
    private String TypeFormateur;
    private String LoginFormateur;
    private String PasswordFormateur;

    private Competence competences;
    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
        name = "assos1", 
        joinColumns = { @JoinColumn(name = "idForamteur") }, 
        inverseJoinColumns = { @JoinColumn(name = "IdCompetence") }
    )
    Set<Competence> projects = new HashSet<>();

    public Formateur() {

    }
    public String getNomFormateur() {
        return NomFormateur;
    }
    public void setNomFormateur(String nomFormateur) {
        NomFormateur = nomFormateur;
    }
    public String getPrenomFormateur() {
        return PrenomFormateur;
    }
    public void setPrenomFormateur(String prenomFormateur) {
        PrenomFormateur = prenomFormateur;
    }
    public String getEmailFormateur() {
        return EmailFormateur;
    }
    public void setEmailFormateur(String emailFormateur) {
        EmailFormateur = emailFormateur;
    }
    public String getTeleFormateur() {
        return TeleFormateur;
    }
    public void setTeleFormateur(String teleFormateur) {
        TeleFormateur = teleFormateur;
    }
    public String getTypeFormateur() {
        return TypeFormateur;
    }
    public void setTypeFormateur(String typeFormateur) {
        TypeFormateur = typeFormateur;
    }
    public String getLoginFormateur() {
        return LoginFormateur;
    }
    public void setLoginFormateur(String loginFormateur) {
        LoginFormateur = loginFormateur;
    }
    public String getPasswordFormateur() {
        return PasswordFormateur;
    }
    public void setPasswordFormateur(String passwordFormateur) {
        PasswordFormateur = passwordFormateur;
    }
    public Long getidForamteur() {
        return idForamteur;
    }
    public Competence getCompetences() {
        return competences;
    }
    public void setCompetences(Competence competences) {
        this.competences = competences;
    }



}

Класс Ассос1:

package com.projet.pfa.projetpfa.models;

import java.util.Date;


import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Entity;

@Entity
@Table(name="Assos1")
public class Assos1 {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private Date DateAppretisage ;


    public Assos1 ()
    {

    }

    public Date getDateAppretisage() {
        return DateAppretisage;
    }

    public void setDateAppretisage(Date dateAppretisage) {
        DateAppretisage = dateAppretisage;
    }

    public Long getId() {
    return id;
    }


}

Класс компетенции:

package com.projet.pfa.projetpfa.models;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;


@Entity
@Table(name="Competence")

public class Competence {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int IdCompetence;
    private String NomCompetence;
    private String DesicrptionComptence;
    private String  Diplome;
    private Date DateDplome ;
       @ManyToMany(mappedBy = "competences" , fetch = FetchType.LAZY)
        private Set<Formateur> employees = new HashSet<>();
    public Competence() {

    }
    public String getNomCompetence() {
        return NomCompetence;
    }
    public void setNomCompetence(String nomCompetence) {
        NomCompetence = nomCompetence;
    }
    public String getDesicrptionComptence() {
        return DesicrptionComptence;
    }
    public void setDesicrptionComptence(String desicrptionComptence) {
        DesicrptionComptence = desicrptionComptence;
    }
    public String getDiplome() {
        return Diplome;
    }
    public void setDiplome(String diplome) {
        Diplome = diplome;
    }
    public Date getDateDplome() {
        return DateDplome;
    }
    public void setDateDplome(Date dateDplome) {
        DateDplome = dateDplome;
    }
    public int getIdCompetence() {
        return IdCompetence;
    }


}

Свойства приложения:

spring.datasource.url=jdbc:mysql://localhost:3306/crudapi
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties..hibernate.dialect=org.hibernate.dialect.MySQL5Dialect


server.port: 8443

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.projet.pfa</groupId>
    <artifactId>projetpfa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>projetpfa</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
        <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1 Ответ

0 голосов
/ 09 мая 2019

Я рекомендую вам блог Влада Михалча, я так много узнал о Hibernate. Здесь вы также можете найти примеры отношений ManyToMany

И вам следует избегать имен столбцов, как, например, joinColumns = { @JoinColumn(name = "id_foramteur") } вместо j oinColumns = { @JoinColumn(name = "idForamteur") }.

А с помощью Lombok вы можете избавиться от геттера и сеттера с помощью одной аннотации.

...