我正在尝试连接到现有表并在我的应用程序中使用它。 但是,当我尝试在我的 Controller 中访问我的信息时,它返回 null。
代码:
build.gradle(相关部分)
dependencies {
classpath "org.grails:grails-gradle-plugin:$grailsVersion"
classpath "org.grails.plugins:hibernate5:${gormVersion-".RELEASE"}"
classpath "org.grails.plugins:views-gradle:1.1.6"
}
apply plugin:"org.grails.grails-web"
apply plugin:"org.grails.plugins.views-json"
dependencies {
compile "org.grails.plugins:hibernate5:6.1.9"
compile "org.hibernate:hibernate-ehcache"
runtime 'mysql:mysql-connector-java:5.1.40'
}
application.yml(相关部分)
hibernate:
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
dataSource:
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username: abc
password: ''
environments:
development:
dataSource:
dbCreate: create-drop
url: jdbc:mysql://localhost:3306/moocs?useSSL=false
test:
dataSource:
dbCreate: update
url: jdbc:mysql://localhost:3306/moocs?useSSL=false
production:
dataSource:
dbCreate: none
url: jdbc:mysql://localhost:3306/moocs?useSSL=false
properties:
jmxEnabled: true
initialSize: 5
maxActive: 50
minIdle: 5
maxIdle: 25
maxWait: 10000
maxAge: 600000
timeBetweenEvictionRunsMillis: 5000
minEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1
validationQueryTimeout: 3
validationInterval: 15000
testOnBorrow: true
testWhileIdle: true
testOnReturn: false
jdbcInterceptors: ConnectionState
defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED
型号
class MoocModel {
String title
String institution
String url
Boolean free
String platform
}
数据库表
+--------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+----------------+
| primary_key_column | bigint(20) | NO | PRI | NULL | auto_increment |
| free | bit(1) | NO | | NULL | |
| title | varchar(255) | NO | | NULL | |
| url | varchar(255) | NO | | NULL | |
| platform | varchar(255) | NO | | NULL | |
| institution | varchar(255) | NO | | NULL | |
+--------------------+--------------+------+-----+---------+----------------+
Controller
import MoocModel
import grails.rest.*
import grails.converters.*
class TableController {
static responseFormats = ['json', 'xml']
def index() {
def mm = MoocModel
render mm.get(5) as JSON // want to display entry with id == 5
}
}
我得到一个空数组,println mm.get(5)
返回 null
所以我认为没有与数据库建立连接。
最佳答案
您需要将您的字段映射到数据库列。默认情况下,grails 使用“id”列作为主键。 所以尝试添加到 MoocModel 中:
static mapping = {
id name: 'primary_key_column'
}
关于mysql - 将 Grails Gorm 连接到预先存在的 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49624772/