我是Play Framework的新手。我正在尝试从Play添加新视图(" Play Java Ebean Example")。我为用户添加了CRUD的新文件,但我无法编辑,更新或添加新用户。删除选项作为用户的列表视图正常工作。
玩-java的ebean-示例
这是一个使用Java的Play应用程序示例,它使用EBean与内存数据库进行通信。
该项目的Github位置是:
https://github.com/playframework/play-java-ebean-example
播放
播放文档在这里:
https://playframework.com/documentation/latest/Home
EBean
EBean是一个使用SQL的Java ORM库:
https://www.playframework.com/documentation/latest/JavaEbean
可以在这里找到文档:
package controllers;
import models.Customer;
import models.CustomerUser;
import play.data.Form;
import play.data.FormFactory;
import play.libs.concurrent.HttpExecutionContext;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results;
import repository.CompanyRepository;
import repository.CustomerRepository;
import repository.CustomerUserRepository;
import javax.inject.Inject;
import javax.persistence.PersistenceException;
import java.util.Map;
import java.util.concurrent.CompletionStage;
/**
* Manage a database of computers
*/
public class UserController extends Controller {
private final CustomerUserRepository userRepository;
private final CustomerRepository customerRepository;
//private final CompanyRepository companyRepository;
private final FormFactory formFactory;
private final HttpExecutionContext httpExecutionContext;
@Inject
public UserController(FormFactory formFactory,
CustomerUserRepository userRepository,
CustomerRepository customerRepository,
HttpExecutionContext httpExecutionContext) {
this.userRepository = userRepository;
this.formFactory = formFactory;
this.customerRepository = customerRepository;
this.httpExecutionContext = httpExecutionContext;
}
/**
* This result directly redirect to application home.
*/
private Result GO_HOME = Results.redirect(
routes.UserController.list(0, "name", "asc", "")
);
/**
* Handle default path requests, redirect to computers list
*/
public Result index() {
return GO_HOME;
}
/**
* Display the paginated list of computers.
*
* @param page Current page number (starts from 0)
* @param sortBy Column to be sorted
* @param order Sort order (either asc or desc)
* @param filter Filter applied on computer names
*/
public CompletionStage<Result> list(int page, String sortBy, String order, String filter) {
// Run a db operation in another thread (using DatabaseExecutionContext)
return userRepository.page(page, 10, sortBy, order, filter).thenApplyAsync(list -> {
// This is the HTTP rendering thread context
return ok(views.html.listuser.render(list, sortBy, order, filter));
}, httpExecutionContext.current());
}
/**
* Display the 'edit form' of a existing Computer.
*
* @param id Id of the computer to edit
*/
public CompletionStage<Result> edit(Long id) {
// Run a db operation in another thread (using DatabaseExecutionContext)
CompletionStage<Map<String, String>> customersFuture = customerRepository.options();
// Run the lookup also in another thread, then combine the results:
return userRepository.lookup(id).thenCombineAsync(customersFuture, (userCustomerOptional, customers) -> {
// This is the HTTP rendering thread context
CustomerUser c = userCustomerOptional.get();
Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).fill(c);
return ok(views.html.editFormUser.render(id, userForm, customers));
}, httpExecutionContext.current());
}
/**
* Handle the 'edit form' submission
*
* @param id Id of the user to edit
*/
public CompletionStage<Result> update(Long id) throws PersistenceException {
Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).bindFromRequest();
if (userForm.hasErrors()) {
// Run companies db operation and then render the failure case
return customerRepository.options().thenApplyAsync(customers -> {
// This is the HTTP rendering thread context
return badRequest(views.html.editFormUser.render(id, userForm, customers));
}, httpExecutionContext.current());
} else {
CustomerUser newUser = userForm.get();
// Run update operation and then flash and then redirect
return userRepository.update(id, newUser).thenApplyAsync(data -> {
// This is the HTTP rendering thread context
flash("success", "Data - " + newUser.name + " has been updated");
return GO_HOME;
}, httpExecutionContext.current());
}
}
/**
* Display the 'new computer form'.
*/
public CompletionStage<Result> create() {
Form<CustomerUser> userForm = formFactory.form(CustomerUser.class);
// Run companies db operation and then render the form
return customerRepository.options().thenApplyAsync((Map<String, String> customers) -> {
// This is the HTTP rendering thread context
return ok(views.html.createFormUser.render(userForm, customers));
}, httpExecutionContext.current());
}
/**
* Handle the 'new computer form' submission
*/
public CompletionStage<Result> save() {
Form<CustomerUser> userForm = formFactory.form(CustomerUser.class).bindFromRequest();
if (userForm.hasErrors()) {
// Run companies db operation and then render the form
return customerRepository.options().thenApplyAsync(customers -> {
// This is the HTTP rendering thread context
return badRequest(views.html.createFormUser.render(userForm, customers));
}, httpExecutionContext.current());
}
CustomerUser cust = userForm.get();
// Run insert db operation, then redirect
return userRepository.insert(cust).thenApplyAsync(data -> {
// This is the HTTP rendering thread context
flash("success", "Data - " + cust.name + " has been created");
return GO_HOME;
}, httpExecutionContext.current());
}
/**
* Handle computer deletion
*/
//it works!!!
public CompletionStage<Result> delete(Long id) {
// Run delete db operation, then redirect
return userRepository.delete(id).thenApplyAsync(v -> {
// This is the HTTP rendering thread context
flash("success", "User has been deleted");
return GO_HOME;
}, httpExecutionContext.current());
}
}
package models;
import play.data.format.Formats;
import play.data.validation.Constraints;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.util.Date;
/**
* Computer entity managed by Ebean
*/
@Entity
public class CustomerUser extends BaseModel {
private static final long serialVersionUID = 1L;
@Constraints.Required
public String name;
@Constraints.Required
public String email;
@Constraints.Required
public String password;
@Constraints.Required
public String typeid;
@ManyToOne
public Customer customer;
}
package repository;
import io.ebean.Ebean;
import io.ebean.EbeanServer;
import io.ebean.PagedList;
import io.ebean.Transaction;
import models.CustomerUser;
import play.db.ebean.EbeanConfig;
import javax.inject.Inject;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import static java.util.concurrent.CompletableFuture.supplyAsync;
/**
* A repository that executes database operations in a different
* execution context.
*/
public class CustomerUserRepository {
private final EbeanServer ebeanServer;
private final DatabaseExecutionContext executionContext;
@Inject
public CustomerUserRepository(EbeanConfig ebeanConfig, DatabaseExecutionContext executionContext) {
this.ebeanServer = Ebean.getServer(ebeanConfig.defaultServer());
this.executionContext = executionContext;
}
/**
* Return a paged list of computer
*
* @param page Page to display
* @param pageSize Number of computers per page
* @param sortBy CustomerUser property used for sorting
* @param order Sort order (either or asc or desc)
* @param filter Filter applied on the name column
*/
public CompletionStage<PagedList<CustomerUser>> page(int page, int pageSize, String sortBy, String order, String filter) {
return supplyAsync(() -> {
return ebeanServer.find(CustomerUser.class).where()
.ilike("name", "%" + filter + "%")
.orderBy(sortBy + " " + order)
.fetch("customer")
.setFirstRow(page * pageSize)
.setMaxRows(pageSize)
.findPagedList();
} , executionContext);
}
public CompletionStage<Optional<CustomerUser>> lookup(Long id) {
return supplyAsync(() -> {
return Optional.ofNullable(ebeanServer.find(CustomerUser.class).setId(id).findUnique());
}, executionContext);
}
public CompletionStage<Optional<Long>> update(Long id, CustomerUser newUserData) {
return supplyAsync(() -> {
Transaction txn = ebeanServer.beginTransaction();
Optional<Long> value = Optional.empty();
try {
CustomerUser savedUserCustomer = ebeanServer.find(CustomerUser.class).setId(id).findUnique();
if (savedUserCustomer != null) {
savedUserCustomer.customer = newUserData.customer;
savedUserCustomer.typeid = newUserData.typeid;
savedUserCustomer.password = newUserData.password;
savedUserCustomer.email = newUserData.email;
savedUserCustomer.name = newUserData.name;
savedUserCustomer.update();
txn.commit();
value = Optional.of(id);
}
} finally {
txn.end();
}
return value;
}, executionContext);
}
public CompletionStage<Optional<Long>> delete(Long id) {
return supplyAsync(() -> {
try {
final Optional<CustomerUser> userCustomerOptional = Optional.ofNullable(ebeanServer.find(CustomerUser.class).setId(id).findUnique());
userCustomerOptional.ifPresent(c -> c.delete());
return userCustomerOptional.map(c -> c.id);
} catch (Exception e) {
return Optional.empty();
}
}, executionContext);
}
public CompletionStage<Long> insert(CustomerUser customerUser) {
return supplyAsync(() -> {
customerUser.id = System.currentTimeMillis(); // not ideal, but it works
ebeanServer.insert(customerUser);
return customerUser.id;
}, executionContext);
}
}
@(id: Long, userForm: Form[CustomerUser], customers: Map[String, String])
@import helper._
@main {
<h1>Edit user</h1>
@form(routes.UserController.update(id)) {
<fieldset>
@CSRF.formField
@inputText(userForm("name"), '_label -> "User name", '_help -> "")
@inputText(userForm("email"), '_label -> "E-mail", '_help -> "")
@inputText(userForm("typeid"), '_label -> "Type Id", '_help -> "")
@select(
userForm("customer.id"),
options(customers),
'_label -> "Customer", '_default -> "-- Choose a customer --",
'_showConstraints -> false
)
</fieldset>
<div class="actions">
<input type="submit" value="Save this user" class="btn primary"> or
<a href="@routes.UserController.list()" class="btn">Cancel</a>
</div>
}
@form(routes.UserController.delete(id), 'class -> "topRight") {
@CSRF.formField
<input type="submit" value="Delete this user" class="btn danger">
}
}
答案 0 :(得分:0)
我发现了这个问题。这是必需的密码,我没有填写我的表格。现在它完美无缺。 IntelliJ的调试帮了我很多忙。见到你们。