grails+oracle 一次实际操作记录

本文详细记录了在使用Grails和Oracle进行API调用时,如何配置log4j日志、显示SQL语句、连接Oracle数据库以及解决在Controller中保存Domain对象时的问题。包括日志配置、SQL语句显示、数据库连接设置、Domain对象保存时的约束设置等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求很简单,保存一个api调用时的相关信息,利用grails+oracle来进行开发。
实际编码过程中,却出现很多问题,特此记录,以备查阅。

基本设置

log4j配置
在Config.groovy中:

log4j.main = {
 //更改此处的error为info、debug即可更改log的基本
    error  'org.codehaus.groovy.grails.web.servlet',        // controllers
           'org.codehaus.groovy.grails.web.pages',          // GSP
           'org.codehaus.groovy.grails.web.sitemesh',       // layouts
           'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
           'org.codehaus.groovy.grails.web.mapping',        // URL mapping
           'org.codehaus.groovy.grails.commons',            // core / classloading
           'org.codehaus.groovy.grails.plugins',            // plugins
           'org.codehaus.groovy.grails.orm.hibernate',      // hibernate integration
           'org.springframework',
           'org.hibernate',
           'net.sf.ehcache.hibernate'
}

sql语句显示配置
在DataSource.groovy中的environments中:

development {
        dataSource {
            dbCreate = "update"
            url = "jdbc:oracle:thin:@192.168.10.77:1521:orcl"
            logSql = true //显示sql语句
        }
    }

在idea中开启debug模式
在BuildConfig.groovy中,直接注释以下代码:

grails.project.fork = [
    // configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
    //  compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],

    // configure settings for the test-app JVM, uses the daemon by default
    test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
    // configure settings for the run-app JVM
    //run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
    run: [maxMemory: 768, minMemory: 64, debug: true, maxPerm: 256, forkReserve:false],
    // configure settings for the run-war JVM
    war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
    // configure settings for the Console UI JVM
    console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]

添加如下代码:

run:false

然后点击idea的debug启动就能正常调试了。

连接oracle设置

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "oracle.jdbc.driver.OracleDriver"
    username = "name"
    password = "pwd"
    dialect = org.hibemate.dialect.Oracle10Dialect
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4
    singleSession = true // configure OSIV singleSession mode
    flush.mode = 'manual' // OSIV session flush mode outside of transactional context
}

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:oracle:thin:@192.168.1.17:1521:orcl"
            logSql = true //显示sql语句
        }
    }
}

先建表,后建domain

grails一般是先有domain,然后运行让其自动构建表.此处是已经存在了数据库表,根据表来构建domain class,诸多细节,于此记录:
指定表

  • 为domain class指定表,需要用到如下语法:
static mapping = {
        table 'API_MONITOR_SOB1'
}
  • 禁用domain的version字段:
static mapping = {
        table 'API_MONITOR_SOB1'
        version false
}
static mapping = {
        table 'API_MONITOR_SOB1'
        version false
        id generator: 'sequence',column:'MONID',params: [sequence:'api_monitor_sob1_sequence']
}
  • 为属性指定不同名的字段
    此处需要注意oracle数据库的大小写显著,字段名称一定要符合数据库设置,否则可能出现“**未指定列”的异常。
static mapping = {
        table 'API_MONITOR_SOB1'
        version false
        id generator: 'sequence',column:'MONID',params: [sequence:'api_monitor_sob1_sequence']
        userId column: 'USERID' //USERID数据库表的字段名称
        paramStr column: 'PARAMSTR'
}

controller中domain的save方法无反应

在实际开发中,遇到在controller中调用save方法保存domain,结果sql不见发出,异常也没有抛出,数据库里面也没有记录,检查之后是因为domain的constraints为空的话,grails会默认所有domain属性not null,保存时也不会提交反馈,更不会抛出异常,如果要显示具体是哪些字段数据不符合约束规范,可用如下代码打印显示:

if(!m.save()){  
    m.errors.allErrors.each{  
        println it  
    }  
}  

因此,最好是将constraints设置好约束。参加:http://akunamotata.iteye.com/blog/1742859

是为记,后面有内容再补充。

### 实现Grails中通过GSP页面实现Excel文件的数据导入功能 要在Grails应用程序中实现Excel数据导入功能,可以按照以下方法设计并开发: #### 1. 添加依赖项 为了处理Excel文件,需要引入第三方库来解析Excel文档。常用的库有Apache POI或JXL。可以通过`build.gradle`文件添加这些依赖。 ```groovy dependencies { implementation 'org.apache.poi:poi-ooxml:5.2.3' // Apache POI用于读取Excel文件 } ``` 此操作允许程序支持`.xls`和`.xlsx`格式的文件[^3]。 --- #### 2. 创建控制器逻辑 创建一个专门负责上传和解析Excel文件的控制器。例如,名为`ImportController.groovy`。 ```groovy class ImportController { def index() {} def upload() { MultipartFile file = request.getFile('excelFile') if (file && !file.isEmpty()) { try { Workbook workbook = new XSSFWorkbook(file.getInputStream()) Sheet sheet = workbook.getSheetAt(0) for (Row row : sheet) { Cell cellA = row.getCell(0) Cell cellB = row.getCell(1) String valueA = cellA?.stringCellValue ?: "" String valueB = cellB?.stringCellValue ?: "" println "Value A: $valueA, Value B: $valueB" // 将数据保存到数据库或其他存储位置 } flash.message = "成功导入 ${sheet.getLastRowNum()} 条记录." } catch (Exception e) { flash.error = "发生错误: ${e.getMessage()}" } } else { flash.error = "未选择任何文件!" } redirect(action: 'index') } } ``` 在此代码片段中,使用了Apache POI中的`XSSFWorkbook`类来加载Excel文件,并逐行遍历工作表的内容[^4]。 --- #### 3. 设计GSP视图 在`grails-app/views/import/index.gsp`中定义HTML表单以供用户上传Excel文件。 ```html <!DOCTYPE html> <html> <head> <title>Excel 数据导入</title> </head> <body> <h1>Excel 文件导入</h1> <g:if test="${flash.message}"> <div class="message">${flash.message}</div> </g:if> <g:if test="${flash.error}"> <div class="error">${flash.error}</div> </g:if> <form action="${createLink(controller:'import', action:'upload')}" method="post" enctype="multipart/form-data"> <label for="excelFile">请选择 Excel 文件:</label><br/> <input type="file" id="excelFile" name="excelFile"/><br/><br/> <button type="submit">上传并导入</button> </form> </body> </html> ``` 这段代码提供了一个简单的界面让用户可以选择本地计算机上的Excel文件并通过POST请求提交给服务器[^5]。 --- #### 4. 配置路由 确保应用能够识别新的动作路径,在`UrlMappings.groovy`中加入如下配置: ```groovy "/import"(controller:"import", action:"index") "/import/upload"(controller:"import", action:"upload") ``` 这一步使得URL `/import`指向默认显示页而`/import/upload`则接收来自用户的文件上传请求[^6]。 --- #### 5. 测试与优化 测试整个流程是否正常运作,包括但不限于验证不同类型的Excel文件兼容性、异常情况下的反馈机制以及性能表现等方面。如果发现某些特定场景下存在问题,则需进一步调整和完善相应部分。 --- ### 注意事项 - **安全性**:应考虑对上传文件进行病毒扫描及大小限制。 - **用户体验**:可增加进度条等功能提升交互体验。 - **扩展性**:未来可能还需要支持更多种类电子表格软件产生的文件格式转换需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值