Java 如何使用maven和jpa在eclipse中连接mysql数据库?

Java 如何使用maven和jpa在eclipse中连接mysql数据库?,java,mysql,eclipse,maven,spring-data-jpa,Java,Mysql,Eclipse,Maven,Spring Data Jpa,我想从eclipse连接到mysql数据库。我想创建一个RESTAPI并在mysql数据库中插入数据 我正在使用sqlyog连接到mysql,我已经安装了一个xammp服务器,打开了mysql,我的项目位于路径C:\xampp\tomcat\webapps\ 我通过提供从xammp服务器运行mysql的端口连接了sql yog 现在我创建了一个maven项目,其中包括jpa依赖项和属性 pom.xml <?xml version="1.0" encoding="UTF-8"?>

我想从eclipse连接到mysql数据库。我想创建一个RESTAPI并在mysql数据库中插入数据

我正在使用sqlyog连接到mysql,我已经安装了一个xammp服务器,打开了mysql,我的项目位于路径C:\xampp\tomcat\webapps\

我通过提供从xammp服务器运行mysql的端口连接了sql yog

现在我创建了一个maven项目,其中包括jpa依赖项和属性

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>

    <groupId>com.creditone</groupId>
    <artifactId>creditone</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>creditone</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RC1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    </dependencies>

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

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>
主控制器

 package com.creditone.creditone;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.creditone.creditone.User;
import com.creditone.creditone.UserRepository;

@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
    @Autowired // This means to get the bean called userRepository
               // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

    @GetMapping(path="/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }
}
尝试使用此代码检查数据库是否正在连接并能够执行CRUD操作

但当我运行此程序时,我得到的错误如下:

       main] c.c.creditone.CreditoneApplication       : Starting CreditoneApplication on Siddhi with PID 18728 (C:\xampp\tomcat\webapps\creditone\target\classes started by siddhi in C:\xampp\tomcat\webapps\creditone)
2018-02-20 12:31:45.726  INFO 18728 --- [           main] c.c.creditone.CreditoneApplication       : No active profile set, falling back to default profiles: default
2018-02-20 12:31:45.756  INFO 18728 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6328d34a: startup date [Tue Feb 20 12:31:45 IST 2018]; root of context hierarchy
2018-02-20 12:31:46.881  INFO 18728 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$99fd5bbe] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-02-20 12:31:47.169  INFO 18728 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-02-20 12:31:47.176  INFO 18728 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-02-20 12:31:47.176  INFO 18728 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
2018-02-20 12:31:47.181  INFO 18728 --- [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: [C:\Program Files\Java\jre1.8.0_161\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_161/bin/server;C:/Program Files/Java/jre1.8.0_161/bin;C:/Program Files/Java/jre1.8.0_161/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files\Git\bin;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\MySQL\MySQL Utilities 1.6\;C:\Users\Intel\AppData\Local\Microsoft\WindowsApps;;C:\Windows\System32;;.]
2018-02-20 12:31:47.236  INFO 18728 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-02-20 12:31:47.236  INFO 18728 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1483 ms
2018-02-20 12:31:47.339  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-02-20 12:31:47.389  WARN 18728 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
2018-02-20 12:31:47.390  INFO 18728 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2018-02-20 12:31:47.402  INFO 18728 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-02-20 12:31:47.406 ERROR 18728 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
如何解决这个问题?我不熟悉eclipse和web开发。请帮忙。
谢谢。

当Spring找不到application.properties文件或找不到数据源时,会引发此异常

  • 检查application.properties是否位于src/main/resources下。另外,请从属性文件中删除\u2013
  • 您尚未指定mysql端口,您确定可以直接从命令行连接它吗
  • 因为您是从eclipse运行的,所以请确保您已经适当地添加了启动类,并且具有@SpringBootApplication

    <properties>
        <start-class>org.xxx.xxx.YourClassName</start-class>
    </properties>
    
    
    org.xxx.xxx.YourClassName
    

  • 您的application.properties似乎有错误的条目。您只需要以下4项

  • spring.datasource.url=jdbc:mysql://localhost/test
  • spring.datasource.username=dbuser
  • spring.datasource.password=dbpass
  • spring.datasource.driver类名=com.mysql.jdbc.driver
  • 这里描述的是:

    您的application.properties位于哪里

    SpringApplication将从以下位置的application.properties文件加载属性,并将其添加到Spring环境中: 当前目录的/config子目录。 当前目录 类路径/配置包 类路径根


    尝试添加到my mysql connector Hi,在pom.xml mysql connector java中添加了mysql connector,但仍然给出相同的错误@Sauloairest这一个:mysql mysql连接器java 8.0.9-rc请检查添加的版本是否受管理:5.1.45@sauloaire无法添加版本8.0.9-rc。试图添加版本2.0.0.RC1,但出现错误,缺少工件id。@SauloAiresHi,尝试了此操作,仍然得到相同的错误@Chidshow在没有指定密码的情况下如何连接?想不出任何其他解决方案!我尝试了以下方法:spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=root-spring.datasource.driver类名=com.mysql.jdbc.driver。。。properties位于javaResources/src/main/resources中。但这并没有起作用@Patrick Lauhoff您是否仍然收到“无法为数据库类型NONE确定嵌入式数据库驱动程序类”错误?
    package com.creditone.creditone;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity // This tells Hibernate to make a table out of this class
    public class User {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Integer id;
    
        private String name;
    
        private String email;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
    
    }
    
           main] c.c.creditone.CreditoneApplication       : Starting CreditoneApplication on Siddhi with PID 18728 (C:\xampp\tomcat\webapps\creditone\target\classes started by siddhi in C:\xampp\tomcat\webapps\creditone)
    2018-02-20 12:31:45.726  INFO 18728 --- [           main] c.c.creditone.CreditoneApplication       : No active profile set, falling back to default profiles: default
    2018-02-20 12:31:45.756  INFO 18728 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6328d34a: startup date [Tue Feb 20 12:31:45 IST 2018]; root of context hierarchy
    2018-02-20 12:31:46.881  INFO 18728 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$99fd5bbe] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
    2018-02-20 12:31:47.169  INFO 18728 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2018-02-20 12:31:47.176  INFO 18728 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-02-20 12:31:47.176  INFO 18728 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
    2018-02-20 12:31:47.181  INFO 18728 --- [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: [C:\Program Files\Java\jre1.8.0_161\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre1.8.0_161/bin/server;C:/Program Files/Java/jre1.8.0_161/bin;C:/Program Files/Java/jre1.8.0_161/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files\Git\bin;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\MySQL\MySQL Utilities 1.6\;C:\Users\Intel\AppData\Local\Microsoft\WindowsApps;;C:\Windows\System32;;.]
    2018-02-20 12:31:47.236  INFO 18728 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-02-20 12:31:47.236  INFO 18728 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1483 ms
    2018-02-20 12:31:47.339  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-02-20 12:31:47.342  INFO 18728 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-02-20 12:31:47.389  WARN 18728 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    2018-02-20 12:31:47.390  INFO 18728 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
    2018-02-20 12:31:47.402  INFO 18728 --- [           main] ConditionEvaluationReportLoggingListener : 
    
    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2018-02-20 12:31:47.406 ERROR 18728 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 
    
    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Cannot determine embedded database driver class for database type NONE
    
    Action:
    
    If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    
    <properties>
        <start-class>org.xxx.xxx.YourClassName</start-class>
    </properties>