How to connect mysql database in eclipse using maven and jpa?

10,712

Solution 1

Your application.properties seems to have wrong entries. The only ones you need are the following 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

It is described here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connect-to-production-database

Also where is your application.properties located?

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment: A /config subdirectory of the current directory. The current directory A classpath /config package The classpath root

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

Solution 2

This exception is thrown by Spring when it is unable to find the application.properties file or unable to find the datasource.

  1. Check if the application.properties is under src/main/resources. Also, remove \u2013 from the properties file
  2. You have not specified the mysql port, are you sure you are able to connect it from command line directly?
  3. Since you are running from eclipse, make sure you have added the start-up class appropriately and have @SpringBootApplication

    <properties>
        <start-class>org.xxx.xxx.YourClassName</start-class>
    </properties>
    
Share:
10,712
Sid
Author by

Sid

Updated on June 14, 2022

Comments

  • Sid
    Sid almost 2 years

    I want to connect to mysql database from eclipse. I want to create a Rest Api and insert data in mysql database.

    I am using sqlyog to connect to mysql and I have installed a xammp server, turned on the mysql and my project is located at tihs path C:\xampp\tomcat\webapps\

    I have connected sql yog by giving the port on which mysql is running from xammp server.

    Now I have created one maven project, which includes jpa dependency and properties.

    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
    

    Main controller

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

    User

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

    Trying to use this code to check if database getting connect and able to perform CRUD operations.

    But as I run this I am getting error as :

           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).
    

    How to resolve this? I am new to eclipse and web development. Please help. Thank you.

    • Saulo Aires
      Saulo Aires about 6 years
      try to add to my mysql-connector
    • Sid
      Sid about 6 years
      Hi, added mysql connector in pom.xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> Still its giving same error. @SauloAires
    • Saulo Aires
      Saulo Aires about 6 years
      this one: <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.9-rc</version> </dependency> please check the version
    • Sid
      Sid about 6 years
      version added is managed:5.1.45 @SauloAires
    • Sid
      Sid about 6 years
      not working with adding version <version>8.0.9-rc</version> . Tried to add version <version>2.0.0.RC1</version> But it gives error, missing artifact id. @SauloAires
  • Sid
    Sid about 6 years
    Hi, tried this, still getting the same error. @Chids
  • Sid
    Sid about 6 years
    how to connect if no password specified?
  • CGS
    CGS about 6 years
    Couldn't think of any other solution!
  • Sid
    Sid about 6 years
    I tried this : spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ... application.properties is located in javaResources/src/main/resources . But dosent work. @Patrick Lauhof
  • Mehtrick
    Mehtrick about 6 years
    are you still getting the "Cannot determine embedded database driver class for database type NONE" error?