I'm trying out Play framework and using 2.2.0 version and Java version.
I want to use MySQL as the database, and I've followed the instruction at the site. I am able to get evolution script running, but I can't save anything to the database. The table created in the database. I got [PersistenceException: java.sql.SQLException: Connection is closed!]
when trying to call Ebean.save() method, which is in my controller.
What I've done is:
Set up build.sbt and added the plugin
libraryDependencies ++= Seq(
javaJdbc,
javaEbean,
cache,
"mysql" % "mysql-connector-java" % "5.1.18"
)
Set up conf/application.conf
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost:3306/TLC?characterEncoding=UTF-8"
db.default.user=root
db.default.pass=secret
Ebean server
ebean.default="models.*"
Created controller class package controllers;
import com.avaje.ebean.Ebean;
import play.*;
import play.data.Form;
import play.mvc.*;
import models.Bar;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result addBar() {
Bar bar = Form.form(Bar.class).bindFromRequest().get();
bar.save();
return redirect(routes.Application.index());
}
}
Created a form
<form action="@routes.Application.addBar()" method="post">
<input name="name"/>
<input type="submit"/>
</form>
Added the route
POST /bars controllers.Application.addBar()
The model itself of course. package models;
import play.db.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Bar extends Model {
@Id
public String id;
public String name;
}
And of course creating the database itself in mysql.
What did I miss? I've been on this like 4 hours and still have no idea what's wrong. If I used h2 in memory database, it works just fine. Please help me.
Thanks!
I had similar issue and I found a solution.
The culprit is id
property of your Bar
entity. You have defined the id
as String and you are not setting it while saving the Bar
. Incase of Long
, the id value is getting generated automatically, but for String you need to set it explicitly.
so,
Bar bar = Form.form(Bar.class).bindFromRequest().get();
bar.id = UUID.randomUUID().toString();
bar.save();
Should solve this issue. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With