尝试使用 mysql 学习带有外键和一对多关系关系的 Spring Boot 但是

Posted

技术标签:

【中文标题】尝试使用 mysql 学习带有外键和一对多关系关系的 Spring Boot 但是【英文标题】:trying to learn Springboot with foreign key and one to many relationship relationship using mysql but 【发布时间】:2019-03-09 19:51:29 【问题描述】:

试图在 Spring Boot 中获取外键一对多关系,但我没有得到什么是错误和解决方案 Project struture

这是我的用户模型类 打包在.cubereum.Phoenix_backend.models;

    import java.util.Date;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToMany;
    import javax.persistence.TableGenerator;

    import com.fasterxml.jackson.annotation.JsonIgnore;

    import lombok.ToString;
    @Entity

    public class User 

          @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "user_id", updatable = false, nullable = false)
        private int user_id;
        @Column(name = "active")
        private boolean active;
        @Column(name = "department")
        private String department;
        @Column(name = "division")
        private String division;
        @Column(name = "email")
        private String email;
        @Column(name = "employee_id")
        private String employee_id;
        @Column(name = "mobile_number")
        private String mobile_number;
        @Column(name = "first_name")
        private String first_name;
        @Column(name = "last_name")
        private String last_name;
        @Column(name = "nickname")
        private String nickname;
        @Column(name = "landline_number")
        private String landline_number;
        @Column(name = "role_id")
        private String role_id;
        @Column(name = "title")
        private String title;
        @Column(name = "city")
        private String city;
        @Column(name = "username")
        private String username;
        @Column(name = "passwords")
        private String passwords;
        @Column(name = "created_by")
        private String created_by;

        @Column(name = "created_date")
        private Date created_date;
        @Column(name = "modified_by")
        private String modified_by;
        @Column(name = "modified_date")
        private Date modified_date;
        @Column(name = "manager")
        private String manager;
            @JoinColumn(name = "org_id")
            @OneToMany
        @JsonIgnore
           private Organization organization;

            public Organization getOrganization() 
                return organization;
            
            public void setOrganization(Organization organization) 
                this.organization = organization;
               


    

这是我的组织模型类 打包在.cubereum.Phoenix_backend.models;

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

import javax.persistence.*;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.ToString;
@Entity

public class Organization 

      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "org_id", updatable = false, nullable = false)
       private int org_id;
    @Column(name = "org_code")  private int org_code;
    @Column(name = "org_name")  private String org_name;
    @Column(name = "org_description")  private String org_description;
    @Column(name = "parent_org")  private String parent_org;
    @Column(name = "address")  private String address;
    @Column(name = "contact_number")  private String contact_number;
    @Column(name = "created_by")  private String created_by;
    @Column(name = "created_date")  private Date created_date;
    @Column(name = "last_modified_by")  private String last_modified_by;
    @Column(name = "last_modified_date")  private Date last_modified_date;

    @ManyToOne
    private Set<User> roles = new HashSet<>(0);
public Set<User> getRoles() 
        return roles;
    

    public void setRoles(Set<User> roles) 
        this.roles = roles;
    



这是我的用户服务类

package in.cubereum.Phoenix_backend.endpoints;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import in.cubereum.Phoenix_backend.repository.Userrepository;

@RestController
@RequestMapping(path = "/main")
@Component
@CrossOrigin(origins = "*")
public class UserService 
      @Autowired
        private Userrepository userrepository;

这是我的组织存储库接口

package in.cubereum.Phoenix_backend.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import in.cubereum.Phoenix_backend.models.Organization;

@Repository
public interface Organizationrepository extends JpaRepository<Organization, String>


这是我的用户存储库

package in.cubereum.Phoenix_backend.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import in.cubereum.Phoenix_backend.models.User;
@Repository
public interface Userrepository extends JpaRepository<User, String>

这是我的主要应用程序类

package in.cubereum.Phoenix_backend;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@SpringBootApplication(scanBasePackages="in.cubereum.Phoenix_backend.repository")
@EnableJpaRepositories(basePackages = "in.cubereum.Phoenix_backend.repository")
public class Phoenix_backendApplication extends SpringBootServletInitializer


     @Bean
        public WebMvcConfigurer corsConfigurer() 
            return new WebMvcConfigurerAdapter() 
                @Override
                public void addCorsMappings(CorsRegistry registry) 
                    registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:");
                
            ;
        
    @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) 
            return application.sources(Phoenix_backendApplication.class);
        

    public static void main(String[] args) 
        SpringApplication.run(Phoenix_backendApplication.class, args);
    

这是我的 build.gradle 文件

buildscript 
    repositories 
        mavenCentral()
    
    dependencies 
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.3.RELEASE")
    


apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'in.cubereum'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories 
    mavenCentral()

// In this section you declare where to find the dependencies of your project
repositories 
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()


dependencies 

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation 'com.google.guava:guava:23.0'
    // This dependency is exported to consumers, that is to say found on their compile classpath.
// https://mvnrepository.com/artifact/org.apache.commons/commons-math3
compile group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'


    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'
        compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.4.RELEASE'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent
compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.0.3.RELEASE', ext: 'pom'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.3.RELEASE'

// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.47'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml
compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.9.6'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:2.0.4.RELEASE'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json
compile group: 'org.springframework.boot', name: 'spring-boot-starter-json', version: '2.0.5.RELEASE'
    // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind'
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
compile group: 'com.googlecode.json-simple', name: 'json-simple'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools
compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.4.RELEASE'
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile group: 'org.hibernate', name: 'hibernate-core', version: '4.1.4.Final'
// https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api
compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'

// https://mvnrepository.com/artifact/org.projectlombok/lombok
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.6'


这是我得到的控制台输出

17:36:28.478 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
17:36:28.481 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/, /spring-boot/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter/target/classes/]
17:36:28.481 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/home/cubereum/workspace/Phoenix_backend/bin/]

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

2018-10-04 17:36:29.008  INFO 20416 --- [  restartedMain] i.c.P.Phoenix_backendApplication         : Starting Phoenix_backendApplication on cubereum with PID 20416 (/home/cubereum/workspace/Phoenix_backend/bin started by cubereum in /home/cubereum/workspace/Phoenix_backend)
2018-10-04 17:36:29.012  INFO 20416 --- [  restartedMain] i.c.P.Phoenix_backendApplication         : No active profile set, falling back to default profiles: default
2018-10-04 17:36:29.140  INFO 20416 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4eaf4b3d: startup date [Thu Oct 04 17:36:29 IST 2018]; root of context hierarchy
2018-10-04 17:36:31.116  INFO 20416 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d548bd60] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-10-04 17:36:31.675  INFO 20416 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-10-04 17:36:31.722  INFO 20416 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-10-04 17:36:31.722  INFO 20416 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-10-04 17:36:31.734  INFO 20416 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
2018-10-04 17:36:31.841  INFO 20416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-10-04 17:36:31.842  INFO 20416 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2710 ms
2018-10-04 17:36:32.041  INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-10-04 17:36:32.047  INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-04 17:36:32.047  INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-04 17:36:32.047  INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-04 17:36:32.048  INFO 20416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-04 17:36:32.182  WARN 20416 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
2018-10-04 17:36:32.190  INFO 20416 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-10-04 17:36:32.225  INFO 20416 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-10-04 17:36:32.233 ERROR 20416 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1708) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:581) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:741) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at in.cubereum.Phoenix_backend.Phoenix_backendApplication.main(Phoenix_backendApplication.java:34) [bin/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.4.RELEASE.jar:2.0.4.RELEASE]
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at org.springframework.util.Assert.notEmpty(Assert.java:450) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.data.jpa.mapping.JpaMetamodelMappingContext.<init>(JpaMetamodelMappingContext.java:54) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:88) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:43) ~[spring-data-jpa-2.0.8.RELEASE.jar:2.0.8.RELEASE]
    at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:141) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1704) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    ... 21 common frames omitted

【问题讨论】:

IllegalArgumentException: At least one JPA metamodel must be present的可能重复 @ManyToOne private Set&lt;User&gt; roles = new HashSet&lt;&gt;(0);去掉初始化 【参考方案1】:

我认为你使用MyISAM 引擎,使用InnoDB。支持Foreign Keys

将此行添加到您的application.properties

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL57InnoDBDialect

【讨论】:

以上是关于尝试使用 mysql 学习带有外键和一对多关系关系的 Spring Boot 但是的主要内容,如果未能解决你的问题,请参考以下文章

powerdesigner如何设置主外键关系?

mysql外键使用

MySQL多表

如何创建表单来编辑一对多关系?

mysql 5.7 使用主键约束

MySQL 基础