Play Framework2.5 (Java) Tips

I will add it in my spare time

Precautions when mapping your own class to Form

ProductForm.java


public class ProductForm {
    //Own class
    public ProductDto productDto;
}

The following error may occur.

[InvalidPropertyException: Invalid property ◯◯ of bean class [△△Form]: Illegal attempt to get property '◯◯' threw exception; nested exception is org.springframework.beans.NullValueInNestedPathException: Invalid property '◯◯' of bean class [△△Form]: Could not instantiate property type [□□] to auto-grow nested property path: org.springframework.beans.BeanInstantiationException: Failed to instantiate [□□]: Is it an abstract class?; nested exception is java.lang.InstantiationException: □□]

It seems to happen if you make a constructor with arguments without making a constructor without arguments. I made an empty constructor and it was fixed.

ProductDto.java


public ProductDto() {
  //do nothing
}

public ProductDto(Product product) {
  this.price = product.price + "Circle";
}

Get record

//All cases
List<Product> products = Product.find.all();

//Get in list
List<Product> products = Product.find.where().eq("valid_flg", 1).findList();

//Get in paging format findPagedList(page number,Number of pages per page)
PagedList<Product> products = Product.find.findPagedList(1, 20);

//Get with primary key
Product product = Product.find.byId(1L);

//Get the number
int count = Product.find.findRowCount();

//Acquire only one (* An error will occur if there are two or more applicable data)
Product product = Product.find.where().eq("product_code", "123456789").findUnique();

Deduplication

Use setDistinct (true).

List<Product> products = Product.find.select("category").setDistinct(true).findList();
// select distinct category from m_product;

Conditions like A and (B or C)

Product.find.where().eq("Condition A")
                    .disjunction()
                      .add(Expr.eq("Condition B"))
		              .add(Expr.ilike("Condition C"))
                    .findList();

How to set up a relationship

Define in model class. The following is an example of relation between m_product table and m_season table with N: 1.

※ N:1 One record for a specific season always corresponds to one record for a product. One product is not tied to multiple seasons. For a particular season 1 record, there are multiple products associated with that season. Therefore, the relationship of "product: season" is "N: 1". Explain the relationship between "one-to-one", "one-to-many", and "many-to-many" in an easy-to-understand manner

models/Product.java


@ManyToOne
@JoinColumn(name = "season_id", insertable = false, updatable = false)
public Season season;

Define @ManyToOne for the one that becomes N. Then define the foreign key to the name of @JoinColumn.

models/Season.java


@OneToMany(mappedBy = "season")
public List<Product> productList;

Define ʻOneToManyfor the one that becomes 1.mappedBy matches the variable name of the field defined by @ ManyToOne`.

JPA Reference

Join The join SQL is created by passing the variable name of the relation defined above to the fetch method.

controllers/ProductListController


List<Product> products = Product.find
                                .fetch("season")
                                .findList();
// select * from m_product t0 left outer join m_season t1 on t1.id = t0.season_id;

@OneToOne @OneToMany and @ManyToOne will be lazy load unless you explicitly write fetch, but in the case of one-to-one relation, it will be EAGER load by default.

python


Product p = Product.find.byId(1);
// select * fron m_product t0 left outer join m_product_detail t1 on t0.product_id = t1.id where t1.id = 1;

//When the following relations are attached to the Product model
// @OneToOne(mappedBy = "productDetail")
// public ProductDetail productDetail;

Joined even though fetch is not written. If you don't want to join, explicitly specify lazy loading.

models/Product.java


@OneToOne(mappedBy = "productDetail", fetch = FetchType.LAZY)
public ProductDetail productDetail;

Table name alias

The serial numbers are assigned as t0, t1, t2 ... in the order of appearance by default. You can set any alias using Query # alias. The table to join is not possible with Query # alias.

controllers/ProductListController


List<Product> products = Product.find
                                .query()
                                .alias("pro")
                                .fetch("season")
                                .findList();
// select * from m_product pro left outer join m_season t1 on t1.id = pro.season_id;

If there is a column with the same name in the relation destination, specify an alias to make it easier to understand.

controllers/ProductListController


List<Product> products = Product.find
                                .query()
                                .alias("pro")
                                .orderBy("pro.valid_flg desc, pro.updated_at desc")
                                .fetch("season")
                                .findList();
// select * from m_product pro left outer join m_season t1 on t1.id = pro.season_id order by pro.valid_flg desc, pro.updated_at desc;

session

SampleController.java


session().get("hoge");

Since session () is a method of play.mvc.Controller class, it is as follows when calling from other than controller.

Http.Context.current().session().get("hoge");

Read the value written in the configuration file

Get the value originally defined in application.conf from Java.

conf/application.conf


MAIL_ADDRESS = "[email protected]"

Sample.java


import com.typesafe.config.ConfigFactory;

String mailAddress = ConfigFactory.load().getString("MAIL_ADDRESS");

You may create another file under conf and specify the file name.

conf/sample.conf


MAIL_ADDRESS = "[email protected]"

Sample.java


import com.typesafe.config.ConfigFactory;

String mailAddress = ConfigFactory.load(ConfigFactory.parseFileAnySyntax(new File("conf/sample.conf"))).getString("MAIL_ADDRESS");

Can be called by dependency injection from Controller

SampleController.java


import Play.Configuration

@Inject Configuration configuration

String mailAddress = configuration.getString("MAIL_ADDRESS");

Switch the configuration file used for each environment

By default, ʻapplication.conf` is loaded at startup. You can change the configuration file to be read by specifying the startup option.

activator -Dconfig.file=conf/application_local.conf run

Attention ①

If the file specified in the option is not found, ʻapplication.conf` is read without an error.

Attention ②

In the production environment, ʻactivator start is used instead of ʻactivator run, so it is necessary to add a habit to the writing style.

activator "start 9000 -Dconfig.file=conf/application_prod.conf" -Dapplication.secret="xxxxxxxx"

Start in debug mode

activator -jvm-debug 9999 run 

When the server starts, right click on the project folder in Eclipse Select DebugDebug Configuration. Select Remote Java Application from the left side menu and select Enter localhost for the host and 9999 for the port and press Debug.

This will stop at the breakpoint.

Prefix the URL

If you want to add a common prefix to all routes, set it in application.conf.

conf/application.conf


application.context = "/admin"

localhost: 9000 / admin is the root.



If you have any questions or comments, please feel free to contact us. I put it together while fluttering, so there may be typos ...

Recommended Posts

Play Framework2.5 (Java) Tips
Java tips, tips
java framework
Java Tips
Play Framework 2.6 (Java) development environment creation
Java code TIPS
Play Framework study
Java framework comparison
[Java] Collection framework
Play Framework 2.6 (Java) environment construction in Eclipse
Post to Slack from Play Framework 2.8 (Java)
Play Framework studying test
play framework personal notes
[Development] Java framework comparison
Learning Java framework # 1 (Mac version)
Play Framework Study Memo Database ①
Java tips --StaticUtility class modifier
Java to play with Function
Java Collections Framework Review Notes
First Play Framework personal notes
Java tips --Spring execution Summary
Introduced Dozer to Play Framework
[Java] Tips for writing source
Validation function in Play Framework
[Java] [Play Framework] Until the project is started with Gradle
Consideration on Java Persistence Framework 2017 (Summary) -1
Play Framework Study Memo Database ②Read
Consideration on Java Persistence Framework 2017 (6) Ebean
Root cause of java framework bugs
Consideration on Java Persistence Framework 2017 (5) Iciql
Play Framework Study Momo DB Update
Java High Level REST Client Tips
Double submit measures with Play Framework
Consideration on Java Persistence Framework 2017 (7) EclipseLink
Java --Jersey Framework vs Spring Boot
Consideration on the 2017 Java Persistence Framework (1)
Spring Framework tools for Java developer
I tried the Java framework "Quarkus"
Consideration on Java Persistence Framework 2017 (8) Hibernate5
Java
Introducing Java tips GreenMail to Junit5
Consideration on Java Persistence Framework 2017 (2) Doma2
Java
Play with Markdown in Java flexmark-java
Differences between Java and .NET Framework
Play framework scheduled jobs and crontab
Try using Java framework Nablarch [Web application]
Guess about the 2017 Java Persistence Framework (3) Reladomo
How to install Play Framework 2.6 for Mac
Authentication function in Play Framework [Access restrictions]
How to use BootStrap with Play Framework
Authentication function with Play Framework [Registration and authentication]
Play RAW, WAV, MP3 files in Java
Features of spring framework for java developers
Interoperability tips with Kotlin for Java developers
Play Framework studying value passing, form helper
Element operation method in appium TIPS (Java)