【问题标题】:How to connect mysql database in eclipse using maven and jpa?如何使用maven和jpa在eclipse中连接mysql数据库?
【发布时间】:2018-07-30 11:36:22
【问题描述】:

我想从 Eclipse 连接到 mysql 数据库。我想创建一个 Rest Api 并在 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>

application.properties

 spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.driverClassName = com.mysql.jdbc.Driver 
spring.datasource.name=test 
spring.datasource.username=root 
spring.datasource.driver-class-name= com.mysql.jdbc.Driver 
spring.jpa.database=mysql 
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect \u2013

主控制器

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

用户存储库

package com.creditone.creditone;

import org.springframework.data.repository.CrudRepository;

import com.creditone.creditone.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Long> {

}

用户

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


}

尝试使用此代码检查数据库是否连接并能够执行 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 开发的新手。请帮忙。 谢谢。

【问题讨论】:

  • 尝试添加到我的mysql-connector
  • 嗨,在 pom.xml 中添加了 mysql 连接器 mysqlmysql-connector-java 仍然给出同样的错误。 @SauloAires
  • 这个:mysqlmysql-connector-java8.0.9-rc请检查版本
  • 添加的版本是托管的:5.1.45 @SauloAires
  • 不适用于添加版本 8.0.9-rc 。试图添加版本 2.0.0.RC1 但它给出了错误,缺少工件 ID。 @SauloAires

标签: java mysql eclipse maven spring-data-jpa


【解决方案1】:

您的 application.properties 似乎有错误的条目。您唯一需要的是以下 4 个。

  1. spring.datasource.url=jdbc:mysql://localhost/test
  2. spring.datasource.username=dbuser
  3. spring.datasource.password=dbpass
  4. spring.datasource.driver-class-name=com.mysql.jdbc.Driver

这里有描述:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connect-to-production-database

您的 application.properties 位于何处?

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

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

【讨论】:

  • 我试过这个:spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=root spring.datasource.driver-class-name=com.mysql.jdbc。 Driver ... application.properties 位于 javaResources/src/main/resources 中。但剂量工作。 @Patrick Lauhof
  • 您是否仍然收到“无法确定数据库类型 NONE 的嵌入式数据库驱动程序类”错误?
【解决方案2】:

Spring在找不到application.properties文件或者找不到数据源时抛出这个异常。

  1. 检查 application.properties 是否在 src/main/resources 下。另外,从属性文件中删除 \u2013
  2. 你没有指定mysql端口,你确定可以直接从命令行连接吗?
  3. 由于您是从 eclipse 运行的,请确保您已正确添加启动类并具有 @SpringBootApplication

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

【讨论】:

  • 你好,试过了,还是一样的错误。 @Chids
  • 不指定密码如何连接?
  • 想不出其他解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-01
  • 2016-11-19
  • 2018-05-09
  • 2016-07-17
  • 2018-12-12
相关资源
最近更新 更多