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

问题描述 投票:2回答:2

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

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

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

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

pom.hml

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

UserRepository

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开发的新手。请帮忙。谢谢。

java mysql eclipse maven spring-data-jpa
2个回答
2
投票

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

  1. spring.datasource.url = JDBC:MySQL的://本地主机/测试
  2. spring.datasource.username = DBUSER
  3. spring.datasource.password = DBPASS
  4. spring.datasource.driver类名= 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 Environment:当前目录的A / config子目录。当前目录A classpath / config包类路径根目录

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


1
投票

当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>
© www.soinside.com 2019 - 2024. All rights reserved.