如何将mariadb连接到springboot项目?

时间:2019-06-26 08:21:14

标签: java spring maven spring-boot spring-mvc

我根据mybatis/Spring-boot-starter.的Github主页指南制作了一个项目。

但是,在此项目中,正在创建db文件并正在编写代码。

但是我已经使用mariadb Tool制作了数据库。

所以我做了所有的事情。您现在要做的就是连接dbdb如何工作?

myDirectory: directory

我的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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>monitoring-smartcore</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>monitoring</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

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

</project>

MonitoringApplication.java

package com.smartcore.monitoring;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MonitoringApplication {

    public static void main(String[] args) {
        SpringApplication.run(MonitoringApplication.class, args);
    }

    private final User_infoMapper user_infoMapper;

    public MonitoringApplication(User_infoMapper user_infoMapper) {
        this.user_infoMapper = user_infoMapper;
      }

     @Bean
      CommandLineRunner sampleCommandLineRunner() {
        return args -> {
          User_info user_info = new User_info();
          user_info.set_user_login_id("Testid");
          user_info.set_password("test");
          user_info.set_nick_name("testnickname");
          user_info.set_real_name("testrealname");
          user_info.set_wallet_address("testwalladdress");
          user_infoMapper.insert(user_info);
          System.out.println(this.user_infoMapper.findById(user_info.getId()));
        };
      }

}

MonitoringApplicationTests:

package com.example.monitoringsmartcore;

import static org.hamcrest.CoreMatchers.containsString;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MonitoringApplicationTests {

      @ClassRule
      public static OutputCapture out = new OutputCapture();

    @Test
    public void contextLoads() {
        out.expect(containsString("idss,passwordd nickkk,reallnameee,testaddressssssss"));
    }

}

** DatabaseConfig.java **

package com.smartcore.monitoring.db;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@MapperScan(basePackages="com.smartcore.monitoring.db.mapper")
@EnableTransactionManagement
public class DatabaseConfig {

      @Bean
        public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
            final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            sessionFactory.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
            return sessionFactory.getObject();
        }

        @Bean
        public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
          final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
          return sqlSessionTemplate;
        }


}

  

application.properties文件是

spring.datasource.url=jdbc:mariadb://localhost:3306/mydb
spring.datasource.username=mydb
spring.datasource.password=mydb
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver

您需要一个解决方案。

谢谢。

我的错误是


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-06-26 18:16:37.232  INFO 3064 --- [           main] c.s.monitoring.MonitoringApplication     : Starting MonitoringApplication on ttttt-MacBookPro.local with PID 3064 (/Users/tttttt/Documents/workspace-spring-tool-suite-4-4.3.0.RELEASE/monitoring-smartcore/target/classes started by tttttt in /Users/tttttttt/Documents/workspace-spring-tool-suite-4-4.3.0.RELEASE/monitoring-smartcore)
2019-06-26 18:16:37.236  INFO 3064 --- [           main] c.s.monitoring.MonitoringApplication     : No active profile set, falling back to default profiles: default
2019-06-26 18:16:38.044  WARN 3064 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'monitoringApplication': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'user_infoMapper' defined in file [/Users/tttttttt/Documents/workspace-spring-tool-suite-4-4.3.0.RELEASE/monitoring-smartcore/target/classes/com/smartcore/monitoring/db/mapper/User_infoMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' 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 java.lang.IllegalStateException: Cannot load driver class: org.mysql.jdbc.Driver
2019-06-26 18:16:38.056  INFO 3064 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-26 18:16:38.081 ERROR 3064 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'monitoringApplication': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'user_infoMapper' defined in file [/Users/tttttt/Documents/workspace-spring-tool-suite-4-4.3.0.RELEASE/monitoring-smartcore/target/classes/com/smartcore/monitoring/db/mapper/User_infoMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' 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 java.lang.IllegalStateException: Cannot load driver class: org.mysql.jdbc.Driver
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:218) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1187) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8

1 个答案:

答案 0 :(得分:0)

好吧,首先,您应该在pom.xml中添加依赖项

[INFO   ] [Base        ] Start application main loop
[ERROR  ] [Base        ] No event listeners have been created
[ERROR  ] [Base        ] Application will leave
[INFO   ] [Base        ] Leaving application in progress...
[INFO   ] [Base        ] Leaving application in progress...
Traceback (most recent call last):

  File "<ipython-input-2-30ebdb31c7db>", line 17, in <module>
    PongApp().run()

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\app.py", line 855, in run
    runTouchApp()

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\base.py", line 506, in runTouchApp
    stopTouchApp()

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\base.py", line 521, in stopTouchApp
    EventLoop.close()

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\base.py", line 172, in close
    self.stop()

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\base.py", line 184, in stop
    provider.stop()

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\input\providers\wm_pen.py", line 111, in stop
    SetWindowLong_WndProc_wrapper(self.hwnd, self.old_windProc)

  File "C:\Users\almig\Anaconda3\lib\site-packages\kivy\input\providers\wm_common.py", line 122, in _closure
    oldAddr = func(hWnd, GWL_WNDPROC, cast(wndProc, c_void_p).value)

ArgumentError: argument 3: <class 'TypeError'>: wrong type

注意:您已经在.properties文件中写入了数据源。所以跳过这一步。

第二,设置数据访问类。或使用方便的模块。例如)DAO,Data JPA,MyBatis等... 就我而言,我只是使用DAO。

<dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
</dependency>
<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

第三,对其进行测试。

@Repository
public class SimpleMessageDAO {
  @Autowired JdbcTemplate jt;

  public List<Map<String, ?>> selectAll() {
    // if you don't know lambda, don't use it.
    return jt.query("select * from simple_message", (rs, rowNum) -> {
      Map<String, Object> map = new HashMap<>();
      map.put("user_login_id", rs.getInt(1));
      map.put("password", rs.getString(2));
      map.put("nick_name", rs.getString(3));
      return map;
    });
  }
}