使用 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"
}
}
我可以知道我在这里做错了什么吗?
谢谢
更新了 Code 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)
}