Skip to content

Instantly share code, notes, and snippets.

CREATE TABLE `books` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(64) DEFAULT NULL,
`description` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
name := """play-rest-book-db"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava)
scalaVersion := "2.12.2"
libraryDependencies += guice
......
play.modules {
# By default, Play will load any class called Module that is defined
# in the root package (the "app" directory), or you can define them
# explicitly below.
# If there are any built-in modules that you want to disable, you can list them here.
#enabled += my.application.Module
# If there are any built-in modules that you want to disable, you can list them here.
package repositories;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.sql.*;
import java.util.*;
import play.db.*;
package books;
import com.google.inject.Inject;
import play.db.Database;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
public class BookController extends Controller {
package controllers;
import com.google.inject.Inject;
import play.db.Database;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
public class BookController extends Controller {
public List<Book> findAll() throws SQLException {
PreparedStatement preparedStatement = database.getConnection().prepareStatement("select * from books");
List<Book> books = new ArrayList<>();
preparedStatement.execute();
ResultSet rs = preparedStatement.getResultSet();
while (rs.next()) {
public Optional<Book> findById(int id) throws SQLException {
PreparedStatement preparedStatement = database.getConnection().prepareStatement("select * from books where id = ?");
preparedStatement.setInt(1, id);
preparedStatement.execute();
ResultSet rs = preparedStatement.getResultSet();
if (rs.next()) {
public void delete(int id) throws SQLException {
PreparedStatement preparedStatement = database.getConnection().prepareStatement("delete from books where id = ?");
preparedStatement.setInt(1, id);
preparedStatement.execute();
}
public void add(Book book) throws SQLException {
// Book has no id because we are adding a new one to the database
PreparedStatement preparedStatement = database.getConnection().prepareStatement("insert into books (id, title, description) values (null, ?, ?)", Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, book.getTitle());
preparedStatement.setString(2, book.getDescription());
preparedStatement.execute();
// after inserting we want to get the generated id
ResultSet rs = preparedStatement.getGeneratedKeys();