Micronaut MySQL удалить запись org.hibernate.HibernateException: сеанс не найден для текущего потока
Используя Micronaut Groovy GROM я смог прочитать данные из базы данных MySQL. но когда я пытаюсь удалить запись ее броска org.hibernate.HibernateException: No Session found for current thread
сообщение об ошибке.
curl -s http://localhost:8880/book/1
{"bookid":"1","name":"Java","id":1}
curl -s http://localhost:8880/book/delete/1
{"message":"Internal Server Error: Could not obtain current Hibernate Session; nested exception is org.hibernate.HibernateException: No Session found for current thread"}
Вот мой код контроллера:
package webapp
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import io.micronaut.http.annotation.Delete
import io.micronaut.http.HttpStatus
import io.micronaut.http.HttpResponse
import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import io.micronaut.spring.tx.annotation.Transactional;
@Slf4j
//@CompileStatic
@Controller("/book")
class BookController implements BooksApi {
final BookService bookService
BookController(BookService bookService) {
this.bookService = bookService
}
@Get("/list")
List<Book> listBooks() {
return bookService.findAll()
}
@Get("/count")
int Count(){
return bookService.count()
}
@Override
@Get("/{id}")
Book show(Long id) {
return bookService.find(id)
}
@Delete("/{id}")
Book delete(Long id) {
Book b= bookService.find(id)
if(b){
// b.delete(flush: true)
b.delete()
}
return b
}
@Post("/save")
def save(@Body Object JSON) {
String bookid=JSON?.bookid
String name=JSON?.name
def b =bookService.save(bookid,name)
return HttpResponse.created(b)
}
@Get("/")
String index() {
return "Hello World"
}
}
Могу ли я знать, что я делаю здесь не так?
Спасибо
Обновлен код 1 BookService
package webapp
import grails.gorm.services.Service
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull
import grails.gorm.transactions.Transactional;
@Service(Book)
interface BookService {
int count()
Book save(@NotBlank String bookid,@NotBlank String name)
List<Book> findAll()
Book find(@NotNull Long id)
@Transactional
Book delete(@NotNull Long id)
void deleteById(Long id)
}
1 ответ
Решение
С помощью Джеффа Брауна я заставляю его работать. Вот рабочий код.
Обслуживание:
package webapp
import grails.gorm.services.Service
import javax.validation.constraints.NotBlank
import javax.validation.constraints.NotNull
@Service(Book)
interface BookService {
int count()
Book save(@NotBlank String bookid, @NotBlank String name)
List<Book> findAll()
Book find(@NotNull Long id)
Book delete(@NotNull Long id)
}
контроллер
package webapp
import groovy.util.logging.Slf4j
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.*
@Slf4j
//@CompileStatic
@Controller("/book")
class BookController implements BooksApi {
final BookService bookService
BookController(BookService bookService) {
this.bookService = bookService
}
@Get("/list")
List<Book> listBooks() {
return bookService.findAll()
}
@Get("/count")
int Count() {
return bookService.count()
}
@Override
@Get("/{id}")
Book show(Long id) {
return bookService.find(id)
}
@Delete("/{id}")
Book delete(Long id) {
return bookService.delete(id)
}
@Post("/save")
def save(@Body Object JSON) {
String bookid = JSON?.bookid
String name = JSON?.name
def b = bookService.save(bookid, name)
return HttpResponse.created(b)
}
@Get("/")
String index() {
return "Book Service"
}
}
build.gradle
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 "webapp"
repositories {
mavenLocal()
mavenCentral()
maven { url "https://jcenter.bintray.com" }
}
dependencyManagement {
imports {
mavenBom 'io.micronaut:micronaut-bom:1.0.2'
}
}
ext {
gormVersion = '6.1.9.RELEASE'
h2Version = '1.4.196'
tomcatJdbcVersion = '8.5.28'
springSecurityCryptoVersion='4.2.5.RELEASE'
}
dependencies {
compile "io.micronaut.configuration:micronaut-jdbc-tomcat"
compile "io.micronaut.configuration:micronaut-hibernate-validator"
compile "io.micronaut.configuration:micronaut-hibernate-gorm"
compile "org.grails:grails-datastore-gorm-hibernate5:$gormVersion"
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 "javax.annotation:javax.annotation-api"
compileOnly "io.micronaut:micronaut-inject-groovy"
runtime "ch.qos.logback:logback-classic:1.2.3"
runtime "com.h2database:h2"
runtime "org.apache.tomcat:tomcat-jdbc"
testCompile "io.micronaut:micronaut-inject-groovy"
testCompile("org.spockframework:spock-core") {
exclude group: "org.codehaus.groovy", module: "groovy-all"
}
runtime "org.hibernate:hibernate-ehcache:5.1.9.Final"
runtime group: 'mysql', name: 'mysql-connector-java', version: '8.0.13'
}
shadowJar {
mergeServiceFiles()
}
run.jvmArgs('-noverify', '-XX:TieredStopAtLevel=1')
mainClassName = "webapp.Application"
tasks.withType(GroovyCompile) {
groovyOptions.forkOptions.jvmArgs.add('-Dgroovy.parameters=true')
}
файл application.yaml
---
micronaut:
application:
name: webapp
server:
port: 8880
---
datasources.default: {}
---
hibernate:
hbm2ddl:
auto: update
cache:
queries: false
use_second_level_cache: true
use_query_cache: false
region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
dataSource:
url: jdbc:mysql://localhost:3306/db
dbCreate: create-update
pooled: true
jmxExport: true
driverClassName: com.mysql.jdbc.Driver
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
username:
password:
Надеюсь, что это помогает другим.
Спасибо