当前位置: 首页 > 知识库问答 >
问题:

尝试使用mysql学习带外键的Springboot和一对多关系,但是

李胤
2023-03-14

试图在SpringBoot中获得外键一对多关系,但我不知道什么是错误和解决方案项目结构

这是我的用户模型类包。立方厘米。凤凰城。模型;

    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;
            }   


    }

这是我的组织模型课程包。立方厘米。凤凰城。模型;

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);
    }
}

这是我的身材。梯度锉

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

共有1个答案

徐俊人
2023-03-14

我想你是使用MyISAM引擎,使用InnoDB。它支持外键。

将此行添加应用程序中。属性

spring。jpa。财产。冬眠方言=组织。冬眠地方话mysql57innodbdialent

 类似资料:
  • 对于我正在构建的一个类似论坛的网站,我有PHP类'user'和'post‘。用户有一个帖子数组。如何与关系数据库中的连接相似?在“post”上有一个外键,指向一个“user”?这对我来说是有意义的,因为这是一对一的关系,而“user”到“post”是一对多的,就我所见。欢迎有任何想法-谢谢!

  • 问题内容: 我有两个非常简单的对象,并且一个对象应在一组“一对多”关系中包含另一个对象。对象已正确插入数据库中,但“子项”表中的外键始终为“ null”。 我不知道为什么: 这是测试对象,它将子对象保持在其集合中: 这是子对象,它包含指向“ TestObj”的反向链接: 我使用以下代码来持久化此对象: 有人可以解释一下为什么会这样吗? 问题答案: 这很简单:您永远不会初始化中的字段(应将其命名为C

  • 问题内容: 我有两个非常简单的对象,并且一个对象应在一组“一对多”关系中包含另一个对象。对象已正确插入数据库中,但是“子项”表中的外键始终为“ null”。 我不知道为什么: 这是测试对象,它将子对象保持在其集合中: 这是子对象,它包含指向“ TestObj”的反向链接: 我使用以下代码来持久化此对象: 有人可以解释一下为什么会这样吗? 问题答案: 这很简单:您永远不会初始化中的字段(应将其命名为

  • 问题内容: 我有两个非常简单的对象,并且一个对象应在一组“一对多”关系中包含另一个对象。对象已正确插入数据库中,但“子项”表中的外键始终为“ null”。 我不知道为什么: 这是测试对象,它将子对象固定在其集合中: 这是子对象,它包含指向“ TestObj”的反向链接: 我用下面的代码坚持这个对象: 有人可以解释一下为什么会这样吗? 问题答案: 这很简单:您永远不会初始化中的字段(应将其命名为Ch

  • 这是项目迁移 这是时间表 这样用户就可以迁移了 这是我的项目模型 这是我的时间表模型: 这是我的用户模型 现在,我从项目返回我的查询 这是可以的,但user_id用户在timesheets.user_id我不能得到它的时间表,并得到它 此控制器按时间表中的项目id返回项目和时间表,但时间表中的用户id我不知道如何将其输入系统

  • 问题内容: 我在个人课程和汽车课程之间有一对多的关系。一个人可以拥有许多汽车,反之亦然。我正在使用Restful API发布数据。我的注释和Get服务运行正常,但是我的后服务在每次尝试插入新数据时都抛出“ 。子表插入为” 。 这是我的代码的一部分。 人.java 汽车.java 我的服务等级: 问题答案: 此注释: 有两个后果: 暗示这是关系的拥有方。这意味着,每当要在和之间建立关系时, 都需要通