Getting error while provide mySql Connection in spring boot application - mysql

I use sql work bench as sql editor . when I provide database
connection in my application I am get error . I get error when define
driver class name in yml file . I already added required dependency
in my gradlle.kt file. But I do not know why I am get this issue. here
is my db connection details
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/hospital-management
driverClassName: com.mysql.cj.jdbc.Driver
username: root
password: 12345678
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
show-sql: true
hibernate:
ddl-auto: update
banner:
location: classpath:banner.txt
app:
jwt:
secret: ArbitrarySecretKey
expiration-in-ms: 864000000
token:
prefix: Bearer
header:
string: Authorization
gradle.kt
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.5.5"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.5.31"
kotlin("plugin.spring") version "1.5.31"
kotlin("plugin.jpa") version "1.5.31"
}
group = "com.nillmani"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
// https://mvnrepository.com/artifact/org.modelmapper/modelmapper
implementation("org.modelmapper:modelmapper:2.3.6")
implementation("org.springframework.boot:spring-boot-starter-security")
// https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt
implementation("io.jsonwebtoken:jjwt:0.9.1")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
runtimeOnly("mysql:mysql-connector-java")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
I get error exact at this point
driverClassName: com.mysql.cj.jdbc.Driver
I get error for the name defination(com.mysql.cj.jdbc.Driver)
It works fine for me While I run this application in windows system
using sql yog. But getting issue in Mac os , in mac os I use sql work
bench as editor. what is the reason for this issue

This type of error raises for versioning issue . Here I use MYSQL5 , I
upgrade MYSQL5 to 8 . All the errors in driver class name vanished.
This trick works for me .Here No issue in my db connection
Before my depedency
runtimeOnly("mysql:mysql-connector-java")
after upgrade to
runtimeOnly("mysql:mysql-connector-java:8.0.25")

Related

Problems connecting Cloud Run Application to Cloud SQL using Spring boot

I am trying to connect a Spring application (using Kotlin and Gradle) to a Google Cloud SQL instance and database. I am getting the error message
java.lang.RuntimeException: [<project-name>:europe-west1:<db-instance>] The Cloud SQL Instance does not exist or your account is not authorized to access it. Please verify the instance connection name and check the IAM permissions for project "<project-name>"
I have followed the guide on how to connect carefully, but to no avail.
Relevant files
src/main/resources/application.yml
server:
port: ${PORT:8080}
spring:
liquibase:
change-log: classpath:liquibase/db.changelog.xml
contexts: production
cloud:
appId: <project-id>
gcp:
sql:
instance-connection-name: <instance-connection-name>
database-name: <db-name>
jpa:
hibernate:
dialect: org.hibernate.dialect.MySQL8Dialect
default_schema: <schema>
show_sql: true
ddl-auto: none
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
continue-on-error: true
initialization-mode: always
url: jdbc:mysql:///<db-name>?cloudSqlInstance=<instance-connection-name>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<user>&password=<password>
username: <user>
password: <password>
---
spring:
config:
activate:
on-profile: dev
jpa:
hibernate:
ddl-auto: create-drop
spring.jpa.database-platform: org.hibernate.dialect.H2Dialect
datasource:
url: jdbc:h2:mem:mydb
username: sa
password: password
driverClassName: org.h2.Driver
cloud:
gcp:
sql:
enabled: false
build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.6.5"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.6.10"
kotlin("plugin.spring") version "1.6.10"
kotlin("plugin.allopen") version "1.4.32"
kotlin("plugin.jpa") version "1.4.32"
kotlin("kapt") version "1.4.32"
}
allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.Embeddable")
annotation("javax.persistence.MappedSuperclass")
}
group = "com.<company>"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web:2.6.5")
implementation("org.springframework.boot:spring-boot-starter-webflux:2.6.5")
implementation("org.springframework.boot:spring-boot-starter-data-jpa:2.6.5")
implementation("org.springframework.cloud:spring-cloud-gcp-starter-sql-mysql:1.2.8.RELEASE")
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.10")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.10")
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.13.2")
implementation("com.fasterxml.jackson.core:jackson-annotations:2.13.2")
implementation("com.fasterxml.jackson.core:jackson-core:2.13.2")
implementation("com.fasterxml.jackson.core:jackson-databind:2.13.2.2")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.2")
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.2")
implementation("org.hibernate:hibernate-core:5.6.7.Final")
implementation("javax.persistence:javax.persistence-api:2.2")
implementation( "commons-codec:commons-codec:1.15")
implementation("io.github.microutils:kotlin-logging-jvm:2.1.21")
implementation("ch.qos.logback:logback-classic:1.2.11")
implementation("com.google.cloud.sql:mysql-socket-factory-connector-j-8:1.4.4")
runtimeOnly("com.h2database:h2:2.1.210")
runtimeOnly("org.springframework.boot:spring-boot-devtools:2.6.5")
testImplementation("org.springframework.boot:spring-boot-starter-test:2.6.5")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Dockerfile
FROM openjdk:17-alpine
ENV USER=appuser
# <placeholder> Replace context path for your own application
ENV JAVA_HOME=/opt/openjdk-17 \
HOME=/home/$USER \
CONTEXT_PATH=/aws-service-baseline
RUN adduser -S $USER
# <placeholder> Add additional packages for the docker container here
RUN apk add --no-cache su-exec
# <placeholder> Replace baseline.jar with your applications JAR file (defined in build.gradle.kts)
COPY Docker/runapp.sh build/libs/<application-name>-0.0.1-SNAPSHOT.jar $HOME/
RUN chmod 755 $HOME/*.sh && \
chown -R $USER $HOME
WORKDIR /home/$USER
CMD [ "./runapp.sh"]
Docker/runapp.sh
#!/bin/sh
set -e
# The module to start.
# <placeholder> Replace this with your own modulename (from module-info)
APP_JAR="<application-name>-0.0.1-SNAPSHOT.jar"
JAVA_PARAMS="-XshowSettings:vm"
echo " --- RUNNING $(basename "$0") $(date -u "+%Y-%m-%d %H:%M:%S Z") --- "
set -x
/sbin/su-exec "$USER:1000" "$JAVA_HOME/bin/java" "$JAVA_PARAMS $JAVA_PARAMS_OVERRIDE" -jar -Dserver.port=$PORT "$APP_JAR"
GCP details
I have made sure the SQL instances connection is added to the Cloud Run Revisions. The IAM roles for the compute service account also seem to be right. See images
IAM: https://i.stack.imgur.com/yYaC5.png
Database: https://i.stack.imgur.com/NErad.png
Cloud Run connection https://i.stack.imgur.com/fKTSZ.png
Additional details
When running ./gradlew bootRun on my local machine (with GCP credentials present), the App works properly with an SQL connection. It also works after running ./gradle bootRun to build the JAR file and run the JAR directly. It does not work out of the box when running in Docker, but if I add the GCP credentials to the Docker container locally, it connects to the Database.
Does anyone have any suggestions on what might be wrong? Any help much appreciated!
I have tried connecting locally and locally in a Docker container.
Figured it out! Human error of course. The Cloud Run Service was initially configured with another Services Account, and not the default Compute Engine Service account.

SQLInvalidAuthorizationSpecException: (conn=63818) Access denied for user 'ravi'#'hostname' (using password: YES)

I am able to connect cloud mysql server if I use hardcoded without externalizing it password=ravi#123 instead of the below, but at the moment I use the below format in order to use the value from the environment variable, it fails in spring boot. A hostname is our azure managed MySQL server host.
I googled enough StackOverflow solutions and tried multiple other options along with character encoding adding to connection string URL still no luck!
characterEncoding=UTF-8
url=jdbc:mysql://${mysql_host:hostname}:${mysql_port:3306}/ravidb?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false&autoReconnect=true&allowPublicKeyRetrieval=true
Could anybody help me to understand what I am missing? And what is the possible fix considering I have no option of modifying username or password?
application.yaml
spring:
profiles:
active: development
jackson:
serialization:
fail-on-empty-beans: false
datasource:
driver-class-name: org.mariadb.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mariadb://${mysql_host:hostname}:${mysql_port:3306}/ravidb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false&autoReconnect=true&allowPublicKeyRetrieval=true
username: ${mysql_user:ravi#ravidb}
password: ${mysql_password:ravi#123}
hikari:
auto-commit: true
connection-timeout: 20000
idle-timeout: 300000
max-lifetime: 1200000
maximum-pool-size: 12
minimum-idle: 5
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MariaDBDialect
format_sql: true
id:
new_generator_mappings: false
build.gradle
plugins {
id 'org.springframework.boot' version '2.3.9.RELEASE'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
id 'java'
id 'groovy'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
testCompile 'org.spockframework:spock-core:1.3-groovy-2.5'
testCompile 'org.spockframework:spock-spring:1.3-groovy-2.5'
compile 'org.apache.commons:commons-lang3:3.11'
compile 'org.javassist:javassist:3.24.0-GA'
runtime 'mysql:mysql-connector-java'
runtime 'org.mariadb.jdbc:mariadb-java-client:2.7.1'
compile 'junit:junit:4.12'
implementation 'org.mapstruct:mapstruct:1.3.1.Final'
implementation group: 'com.google.guava', name: 'guava', version: '23.0'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.3.1.Final'
testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.3.1.Final'
}
I wondered to see it worked if I just change key name mysql_password to mysql_pass
Issue reslved with this change:
spring.datasource.password=${mysql_pass:ravi#123}

Why I can not use a 5.7 nor a 5.6 mysql docker image instead of mysql 8 with terraform in windows?

I am testing a mysql_database inside a docker_container.mysql using terraform in windows, but every time I try to use an image different from mysql:8 inside the docker_image.mysql used by docker_container.mysql, terraform takes 5 minutes to create the mysql_database resource and throws the following error:
Error: Could not connect to server: dial tcp 127.0.0.1:3306: connectex: No connection could be made because the target machine actively refused it.
on main.tf line 33, in resource "mysql_database" "test":
33: resource "mysql_database" "test" {
And here is main.tf:
provider "docker" {
host = "npipe:////.//pipe//docker_engine"
}
resource "docker_image" "mysql" {
name = "mysql:8"
//keep_locally = true
}
resource "docker_container" "mysql" {
name = "mysql"
image = docker_image.mysql.latest
restart = "always"
env = [
"MYSQL_ROOT_PASSWORD=root"
]
volumes {
volume_name = "mysql-vol"
container_path = "/var/lib/mysql"
}
ports {
internal = 3306
external = 3306
}
}
provider "mysql" {
endpoint = "127.0.0.1:3306"
username = "root"
password = "root"
}
resource "mysql_database" "test" {
name = "test"
depends_on = [docker_container.mysql]
}
I am testing mysql image tags shown at https://hub.docker.com/_/mysql, specifically 5.6, 5.7 and 8, but only using mysql:8 seems to work Is there an other way in which I should reference those mysql image tags?
I tried to verify the issue, and I observed the same error as yours only for mysql 5.7 and 5.6 when you keep the same volumes.
After removing the following section from the terraform script
volumes {
volume_name = "mysql-vol"
container_path = "/var/lib/mysql"
}
and removing existing mysql docker images, mysql 5.6, mysql 5.7 and 8 worked as expected.
Btw, the error leading to failed connection was:
ERROR 2013 (HY000): Lost connection to MySQL server at 'handshake: reading initial communication packet', system error: 11

How to configure application.yml for mysql using Gorm in micronaut

I am trying to make a CRUD application in micronaut and groovy, i am using hibernate and GORM for validation,save,delete etc with mySql database and #Transactional.
While i run the application it runs fine but there is no tables initialized in mysql. While sending the Post request to save the Data in db i get following error
5:54:48.840 [nioEventLoopGroup-1-3] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: could not prepare statement
org.hibernate.exception.SQLGrammarException: could not prepare statement
Caused by: org.h2.jdbc.JdbcSQLException: Table "STUDENT" not found; SQL statement:
select this_.id as y0_ from student this_ where this_.name=? limit ? [42102-196]
My domain class code is:
#Entity
class Student {
String name
int age
String gender
String number
static constraints = {
name nullable:false, blank:false,unique:true
age nullable:true,blank:true,size: 1..5
gender nullable:true,blank:true
number size: 11..13,blank:true,unique:true,nullable:true
}
}
The code of my Controller is as follow:
#Transactional(readOnly = true)
#Controller("/")
class StudntController {
#Post("/save")
#Transactional
def save(#Body Object JSON)
{
def result = [:]
Student stu = new Student(name:
JSON?.name,gender:JSON?.gender)
stu.save(flush: true,failOnError: true)
result.put("Student",stu)
result.put("Message", "Student created successfully")
}
}
Here is my Application.yml configurations:
micronaut:
application:
name: mincronaut-crud
server:
port: 8080
---
hibernate:
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
environments:
development:
dataSource:
dbCreate: update
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
username: admin
password: qwerzxcv123
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
url: jdbc:mysql://192.168.1.121:3306/student
test:
dataSource:
dbCreate: update
url: jdbc:mysql://192.168.1.121:3306/student
production:
dataSource:
dbCreate: update
url: jdbc:mysql://192.168.1.121:3306/student
And atlast here are my build.gradle configurations:
plugins {
id "io.spring.dependency-management" version "1.0.6.RELEASE"
id "com.github.johnrengelman.shadow" version "4.0.2"
}
apply plugin:"application"
apply plugin:"groovy"
version "0.1"
group "mincronaut.crud"
repositories {
mavenLocal()
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
ext {
gormVersion = '6.1.9.RELEASE'
h2Version = '1.4.196'
tomcatJdbcVersion = '8.5.28'
}
dependencyManagement {
imports {
mavenBom 'io.micronaut:micronaut-bom:1.0.1'
}
}
dependencies {
compile "io.micronaut:micronaut-http-client"
compile "io.micronaut:micronaut-http-server-netty"
compile "io.micronaut:micronaut-runtime-groovy"
compile "io.micronaut:micronaut-validation"
compile "io.micronaut.configuration:micronaut-hibernate-gorm"
compileOnly "io.micronaut:micronaut-inject-groovy"
compile "org.grails:grails-datastore-gorm-
hibernate5:$gormVersion"
runtime "org.apache.tomcat:tomcat-jdbc:$tomcatJdbcVersion"
runtime 'mysql:mysql-connector-java:6.0.6'
runtime "ch.qos.logback:logback-classic:1.2.3"
runtime "com.h2database:h2:$h2Version"
testCompile "io.micronaut:micronaut-inject-groovy"
testCompile("org.spockframework:spock-core") {
exclude group: "org.codehaus.groovy", module: "groovy-all"
}
testCompile "junit:junit:4.12"
testCompile "io.micronaut:micronaut-inject-java"
testCompile "org.hamcrest:hamcrest-all:1.3"
}
shadowJar {
mergeServiceFiles()
}
run.jvmArgs('-noverify', '-XX:TieredStopAtLevel=1')
mainClassName = "mincronaut.crud.Application"
tasks.withType(GroovyCompile) {
groovyOptions.forkOptions.jvmArgs.add('-
Dgroovy.parameters=true')
}
Why the code after run doesnt create any table in database and why it is picking the h2 database even when my url in application is configured for mysql and i've also provided mysql plugin in build.gradle. Please help me out to configure mysql properly with gorm and groovy in micronaut.
I have just made this working CURD with MySQL. you can refer this post:
Micronaut MySQL delete record org.hibernate.HibernateException: No Session found for current thread

Using mongodb and hibernate with grails3

I need to run a Grails 3 app against MySql/Hibernate and MongoDB.
(Had is running on Grails 2.5 without an hitch).
I tried many different combinations, searched and tried related SO answers, but with no luck.
Used the latest Mongodb plugin doc for the configuration.
Using Grails 3.1.10:
grailsVersion=3.1.10
I started with the following details in build.gradle:
buildscript {
ext {
grailsVersion = project.grailsVersion
}
repositories {
mavenLocal()
maven { url "https://repo.grails.org/grails/core" }
}
dependencies {
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.8.2"
classpath "org.grails.plugins:hibernate4:5.0.10"
}
}
...
dependencies {
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.grails:grails-core"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-tomcat"
compile "org.grails:grails-dependencies"
compile "org.grails:grails-web-boot"
compile "org.grails.plugins:cache"
compile "org.grails.plugins:scaffolding"
compile "org.grails.plugins:hibernate4"
compile "org.hibernate:hibernate-ehcache"
console "org.grails:grails-console"
profile "org.grails.profiles:web"
runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.8.2"
testCompile "org.grails:grails-plugin-testing"
testCompile "org.grails.plugins:geb"
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
//databases
compile 'org.grails.plugins:mongodb:6.0.0.M2'
runtime 'mysql:mysql-connector-java:5.1.36'
...
}
The application.yml:
---
hibernate:
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
dataSource:
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
environments:
development:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost:3306/dbname
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username : "xxx"
password : "yyy"
properties:
maxActive : 50
maxIdle: 25
minIdle: 5
...
grails:
mongodb:
host: "localhost"
port: 27017
username: "blah"
password: "blah"
databaseName: "foo"
Now this gives me an error:
15:13:58.001 [QUIET] [system.out] ERROR org.springframework.boot.SpringApplication - Application startup failed
15:13:58.001 [QUIET] [system.out] java.lang.NoClassDefFoundError: org/grails/datastore/gorm/plugin/support/ConfigSupport
15:13:58.001 [QUIET] [system.out] at grails.plugins.mongodb.MongodbGrailsPlugin.doWithSpring(MongodbGrailsPlugin.groovy:42)
The MongoDB grails plugin does not find ConfigSupport
ConfigSupport.prepareConfig(config, (ConfigurableApplicationContext) applicationContext)
I then tried to add the following plugins in all orders possible:
//compile 'org.grails:grails-datastore-gorm-hibernate4:6.0.0.M2'
//compile 'org.grails:grails-datastore-core:4.0.0.M2'
//compile 'org.grails:grails-datastore-gorm-plugin-support:6.0.0.M2'
//compile 'org.springframework.data:spring-data-mongodb:1.9.2.RELEASE'
//compile 'org.mongodb:mongodb-driver:3.3.0'
//compile 'org.mongodb:mongo-java-driver:3.3.0'
No luck.
I also moved the mongodb: section down to the grails: section in the yml file. Same error.
So the question is how to get MongoDB running with MySql with grails3.
Ok, stupid me. I solved the puzzle using these simple dependency settings:
compile "org.springframework.boot:spring-boot-starter-logging"
compile "org.springframework.boot:spring-boot-autoconfigure"
compile "org.grails:grails-core"
compile "org.springframework.boot:spring-boot-starter-actuator"
compile "org.springframework.boot:spring-boot-starter-tomcat"
compile "org.grails:grails-dependencies"
compile "org.grails:grails-web-boot"
compile "org.grails.plugins:cache"
compile "org.grails.plugins:scaffolding"
compile "org.grails.plugins:hibernate4"
compile "org.hibernate:hibernate-ehcache"
console "org.grails:grails-console"
profile "org.grails.profiles:web"
runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.8.2"
testCompile "org.grails:grails-plugin-testing"
testCompile "org.grails.plugins:geb"
testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
//databases
compile 'org.grails.plugins:mongodb'
runtime 'mysql:mysql-connector-java:5.1.36'
runtime 'com.googlecode.json-simple:json-simple:1.1'
It seems that the following line made the difference:
compile 'org.grails.plugins:mongodb'
Omitting the version number. This should be explained in the docs a bit better. Usually it is a good thing defining versions, or is this too old fashioned these days? :-)
Happy to have it working
Ok I found correct previous answer for referring mongodb plugin, i.e. compile 'org.grails.plugins:mongodb' but I want to sum up with a brief checklist, having me a correctly running mixed solution (both hibernate + mysql and mongodb), after many trials and errors. So, in order to have a mixed mysql/mongo grails3 configuration, you have to
insert compile 'org.grails.plugins:mongodb' (without any version) in build.gradle (remember that there is no BuildConfig.groovy in grails 3, as documented here/grails2->3)
keep ordinary dependency to hibernate/mysql, for example: compile 'org.grails.plugins:hibernate4' compile 'org.hibernate:hibernate-ehcache' runtime 'mysql:mysql-connector-java:5.1.38'
set up correctly connections in application.yml, but I prefer old-style application.groovy, in grails-app/conf (as in older GRAILS), as below (remember that in GRAILS3 differently from 2 you have to use mongodb and no more mongo keyword)
use ordinary GRAILS entities for mysql mapping
and use static mapWith="mongo" inside mongo entities (as stated in GRAILS-mongo doc)
not use usual mysql Long id for mongo, but ObjectId id, and for it import org.bson.types.ObjectId
Application.groovy set up
grails {
mongodb {
host = "localhost"
port = 27017
username = mongouser
password= mongopasswd
databaseName = mongoDBname
}
}
environments {
development {
dataSource {
driverClassName = "com.mysql.jdbc.Driver"
username = ...
password = ...
dbCreate = "create"
url = "jdbc:mysql://127.0.0.1:3306/dbnameMysql"
}
}
}
That's all. Enjoy MongoDB.
Not sure I can help much other than show my config that is confirmed working.
I've recently converted a 2.4.4 app to 3.1.8, admittedly I'm using Oracle as my RDBMS rather than mysql.
In build.gradle I just have:
dependencies {
classpath "org.grails.plugins:hibernate4:5.0.6"
...
}
dependencies {
compile "org.grails.plugins:mongodb:5.0.0.RC1"
...
}
And in application.yml:
mongodb:
databaseName: 'myApp'
engine: mapping
The engine: mapping bit was crucial for me, it reverts to the previous persistence engine as described here http://gorm.grails.org/latest/mongodb/manual/index.html
The doWithSpring() closure in my MongodbGrailsPlugin.groovy looks like:
Closure doWithSpring() {
def initializer = new MongoDbDataStoreSpringInitializer(config, grailsApplication.getArtefacts(DomainClassArtefactHandler.TYPE).collect() { GrailsClass cls -> cls.clazz })
initializer.registerApplicationIfNotPresent = false
initializer.setSecondaryDatastore( manager.hasGrailsPlugin("hibernate") )
return initializer.getBeanDefinitions((BeanDefinitionRegistry)applicationContext)
}
No reference to ConfigSupport which may have been added (or not) in your later version or there's a dependency missing.