user2340414
user2340414

Reputation: 89

Play framework with H2 - need simple tutorial

I configured H2 in application.conf Unhashed this rows:

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:file:data/db"
db.default.user=sa
db.default.password=""

Ok, then compile my app, using play run, then play h2-browser in other window cmd prompt in my application path. What's next?! When I running play h2-browser, google chrome is started on 192.168.1.102:8082, then "Oops! Google Chrome could not connect to 192.168.1.102:8082". I have not strength on this. Online documentation on Play site is very very very poor in my opinion (as beginner)

In model class, in method called index (return Result) I have following code:

 String sql = "CREATE TABLE REGISTRATION " +
                   "(id INTEGER not NULL, " +
                   " first VARCHAR(255), " + 
                   " last VARCHAR(255), " + 
                   " age INTEGER, " + 
                   " PRIMARY KEY ( id ))"; 
        Statement statement = null;
        Connection connection = DB.getConnection();
        try {
            statement = connection.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            statement.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ok(
            index.render(form(Login.class))
        );

anyone can help me?

Upvotes: 2

Views: 3047

Answers (1)

Jaya Krishna
Jaya Krishna

Reputation: 65

You should probably have your code base follow below principles.

  1. Use controller class only to handle Request/ Response flows.
  2. Write a model class to define your entity attributes. Play model classes typically use EBean ORM (Refer http://www.avaje.org/ebean/documentation.html).
  3. Run the application using 'Play' command and then use 'H2-Browser' command to launch H2 database explorer.
  4. You might want to use below configuration -
    db.default.driver=org.h2.Driver
    db.default.url="jdbc:h2:mem:play"
    db.default.user=sa
    db.default.password=sa

Sample Controller (Application.java) -

public class Application extends Controller {

    public static Result addrecord() {
             SampleModel sm = new SampleModel();
             sm.text = "Testing";
             SampleModel.create(sm);
             return ok("Record is added");
    }
}

Sample Model class (SampleModel.java) -

@Entity
public class SampleModel extends Model {

     @Id
     public Long id;

     public String text;  // you can add annotations like @Required, @ManyToMany etc

     // other attributes (columns)

     public static void create(SampleModel sm){
          sm.save();
     }
}

Routes file -

POST    /addrecord         controllers.Application.addrecord()

Upvotes: 2

Related Questions