├── .github ├── mergify.yml ├── workflows │ ├── publish.yml │ ├── release-drafter.yml │ ├── dependency-graph.yml │ └── build-test.yml ├── scala-steward.conf └── dependabot.yml ├── docs ├── src │ └── main │ │ └── resources │ │ └── application.conf ├── project │ ├── build.properties │ └── plugins.sbt ├── manual │ └── working │ │ └── javaGuide │ │ └── main │ │ └── sql │ │ ├── code │ │ ├── javaguide │ │ │ └── ebean │ │ │ │ ├── MyServerConfigStartup.java │ │ │ │ ├── Task.java │ │ │ │ └── JavaEbeanTest.java │ │ └── ebean.sbt │ │ └── JavaEbean.md ├── .scalafmt.conf ├── common.sbt └── build.sbt ├── sbt-play-ebean └── src │ ├── sbt-test │ └── sbt-ebean │ │ ├── enhancement │ │ ├── test │ │ ├── conf │ │ │ └── application.conf │ │ ├── project │ │ │ └── plugins.sbt │ │ ├── build.sbt │ │ ├── app │ │ │ └── models │ │ │ │ └── Task.java │ │ └── tests │ │ │ └── models │ │ │ └── TestTask.java │ │ └── model-loading │ │ ├── test │ │ ├── project │ │ └── plugins.sbt │ │ └── build.sbt │ └── main │ └── scala │ └── play │ └── ebean │ └── sbt │ └── PlayEbean.scala ├── project ├── build.properties ├── plugins.sbt ├── Dependencies.scala └── Common.scala ├── .git-blame-ignore-revs ├── .gitignore ├── play-ebean └── src │ ├── main │ ├── java │ │ └── play │ │ │ └── db │ │ │ └── ebean │ │ │ ├── package-info.java │ │ │ ├── EbeanConfig.java │ │ │ ├── TransactionalAction.java │ │ │ ├── Transactional.java │ │ │ ├── EbeanModule.java │ │ │ ├── EBeanComponents.java │ │ │ ├── ModelsConfigLoader.java │ │ │ ├── EbeanParsedConfig.java │ │ │ ├── EbeanDynamicEvolutions.java │ │ │ └── DefaultEbeanConfig.java │ └── resources │ │ └── reference.conf │ └── test │ └── java │ └── play │ └── db │ └── ebean │ ├── EBeanComponentsTest.java │ └── EbeanParsedConfigTest.java ├── .scalafmt.conf ├── common.sbt ├── README.md └── LICENSE /.github/mergify.yml: -------------------------------------------------------------------------------- 1 | extends: .github 2 | -------------------------------------------------------------------------------- /docs/src/main/resources/application.conf: -------------------------------------------------------------------------------- 1 | play.crypto.secret = "changeme" -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/enhancement/test: -------------------------------------------------------------------------------- 1 | > test 2 | $ exists conf/evolutions/default/1.sql -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/enhancement/conf/application.conf: -------------------------------------------------------------------------------- 1 | ebean.default = [ "models.*" ] 2 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/model-loading/test: -------------------------------------------------------------------------------- 1 | # Test that loading ebean models doesn't fail when there's no application.conf 2 | -$ exists conf/application.conf 3 | > playEbeanModels 4 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | sbt.version=1.11.7 4 | -------------------------------------------------------------------------------- /docs/project/build.properties: -------------------------------------------------------------------------------- 1 | # Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | sbt.version=1.11.7 4 | -------------------------------------------------------------------------------- /.git-blame-ignore-revs: -------------------------------------------------------------------------------- 1 | # Scala Steward: Reformat with scalafmt 3.5.8 2 | 7fe92e05b8508927343db11bd4c6bbbd723253c1 3 | # Enable Java formatter 4 | 367b1e5662a20cda35df21d715bd76d1bf4d2324 5 | 6 | # Scala Steward: Reformat with scalafmt 3.9.8 7 | aa32f0df6ba6661a2f8620c10a15c66dddc23354 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | .bsp 4 | docs/conf 5 | 6 | # sbt specific 7 | dist/* 8 | target/ 9 | lib_managed/ 10 | src_managed/ 11 | project/boot/ 12 | project/plugins/project/ 13 | 14 | # Scala-IDE specific 15 | .scala_dependencies 16 | .idea 17 | .classpath 18 | .project 19 | .settings 20 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | branches: # Snapshots 6 | - main 7 | tags: ["**"] # Releases 8 | 9 | jobs: 10 | publish-artifacts: 11 | name: Publish / Artifacts 12 | uses: playframework/.github/.github/workflows/publish.yml@v4 13 | secrets: inherit 14 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/enhancement/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | resolvers ++= DefaultOptions.resolvers(snapshot = true) 4 | addSbtPlugin("org.playframework" % "sbt-play-ebean" % sys.props("project.version")) 5 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/model-loading/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | resolvers ++= DefaultOptions.resolvers(snapshot = true) 4 | addSbtPlugin("org.playframework" % "sbt-play-ebean" % sys.props("project.version")) 5 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | /** 6 | * Provides Ebean ORM integration. 7 | * 8 | *

http://ebean-orm.github.io/ 9 | */ 10 | package play.db.ebean; 11 | -------------------------------------------------------------------------------- /play-ebean/src/main/resources/reference.conf: -------------------------------------------------------------------------------- 1 | play { 2 | modules { 3 | enabled += "play.db.ebean.EbeanModule" 4 | } 5 | 6 | ebean { 7 | # The key for ebean config 8 | config = "ebean" 9 | 10 | # The name of the default ebean datasource 11 | defaultDatasource = "default" 12 | 13 | # The key to control the generation of the Evolutions scripts 14 | generateEvolutionsScripts = true 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/model-loading/build.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | lazy val root = project 4 | .in(file(".")) 5 | .enablePlugins(PlayJava, PlayEbean) 6 | 7 | scalaVersion := sys.props("scala.version") 8 | 9 | resolvers ++= DefaultOptions.resolvers(snapshot = true) 10 | 11 | libraryDependencies += "com.h2database" % "h2" % "2.4.240" 12 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/EbeanConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import io.ebean.config.DatabaseConfig; 8 | import java.util.Map; 9 | 10 | public interface EbeanConfig { 11 | 12 | String defaultServer(); 13 | 14 | Map serverConfigs(); 15 | 16 | boolean generateEvolutionsScripts(); 17 | } 18 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | addSbtPlugin("com.github.sbt" % "sbt-header" % "5.11.0") 4 | 5 | addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.1.4") 6 | 7 | addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.6") 8 | 9 | addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.11.2") 10 | 11 | addSbtPlugin("com.lightbend.sbt" % "sbt-java-formatter" % "0.8.0") 12 | -------------------------------------------------------------------------------- /.github/scala-steward.conf: -------------------------------------------------------------------------------- 1 | commits.message = "${artifactName} ${nextVersion} (was ${currentVersion})" 2 | 3 | pullRequests.grouping = [ 4 | { name = "patches", "title" = "Patch updates", "filter" = [{"version" = "patch"}] } 5 | ] 6 | 7 | buildRoots = [ 8 | ".", 9 | "docs", 10 | ] 11 | 12 | updates.ignore = [ 13 | // these will get updated along with ebean, so no need to update them separately 14 | { groupId = "io.ebean", artifactId = "ebean-ddl-generator" } 15 | { groupId = "io.ebean", artifactId = "ebean-agent" } 16 | ] 17 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: "weekly" 11 | target-branch: "8.x" 12 | commit-message: 13 | prefix: "[8.x] " 14 | - package-ecosystem: "github-actions" 15 | directory: "/" 16 | schedule: 17 | interval: "weekly" 18 | target-branch: "7.x" 19 | commit-message: 20 | prefix: "[7.x] " 21 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | update_release_draft: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: release-drafter/release-drafter@v6 13 | with: 14 | name: "Play Ebean $RESOLVED_VERSION" 15 | config-name: release-drafts/increasing-minor-version.yml # located in .github/ in the default branch within this or the .github repo 16 | commitish: ${{ github.ref_name }} 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | align.preset = true 2 | assumeStandardLibraryStripMargin = true 3 | danglingParentheses.preset = true 4 | docstrings.style = Asterisk 5 | maxColumn = 120 6 | project.git = true 7 | rewrite.rules = [ AvoidInfix, ExpandImportSelectors, RedundantParens, SortModifiers, PreferCurlyFors ] 8 | rewrite.sortModifiers.order = [ "private", "protected", "final", "sealed", "abstract", "implicit", "override", "lazy" ] 9 | spaces.inImportCurlyBraces = true # more idiomatic to include whitepsace in import x.{ yyy } 10 | trailingCommas = preserve 11 | newlines.afterCurlyLambda = preserve 12 | runner.dialect = scala212source3 13 | version = 3.10.2 14 | -------------------------------------------------------------------------------- /docs/manual/working/javaGuide/main/sql/code/javaguide/ebean/MyServerConfigStartup.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | // #content 6 | // ###replace: package models; 7 | package javaguide.ebean; 8 | 9 | import io.ebean.config.ServerConfig; 10 | import io.ebean.event.ServerConfigStartup; 11 | 12 | public class MyServerConfigStartup implements ServerConfigStartup { 13 | public void onStart(ServerConfig serverConfig) { 14 | serverConfig.setDatabaseSequenceBatchSize(1); 15 | } 16 | } 17 | // #content 18 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/enhancement/build.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | lazy val root = project 4 | .in(file(".")) 5 | .enablePlugins(PlayJava, PlayEbean) 6 | 7 | scalaVersion := sys.props("scala.version") 8 | 9 | Test / sourceDirectory := baseDirectory.value / "tests" 10 | 11 | Test / scalaSource := baseDirectory.value / "tests" 12 | 13 | Test / javaSource := baseDirectory.value / "tests" 14 | 15 | resolvers ++= DefaultOptions.resolvers(snapshot = true) 16 | 17 | libraryDependencies += "com.h2database" % "h2" % "2.4.240" 18 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/TransactionalAction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import io.ebean.DB; 8 | import java.util.concurrent.CompletionStage; 9 | import play.mvc.Action; 10 | import play.mvc.Http.Request; 11 | import play.mvc.Result; 12 | 13 | /** Wraps an action in an Ebean/DB transaction. */ 14 | public class TransactionalAction extends Action { 15 | public CompletionStage call(final Request req) { 16 | return DB.executeCall(() -> delegate.call(req)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/Transactional.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import java.lang.annotation.ElementType; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.RetentionPolicy; 10 | import java.lang.annotation.Target; 11 | import play.mvc.With; 12 | 13 | /** Wraps the annotated action in an Ebean transaction. */ 14 | @With(TransactionalAction.class) 15 | @Target({ElementType.TYPE, ElementType.METHOD}) 16 | @Retention(RetentionPolicy.RUNTIME) 17 | public @interface Transactional {} 18 | -------------------------------------------------------------------------------- /docs/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | lazy val plugins = (project in file(".")).dependsOn(sbtPlayEbean) 4 | 5 | lazy val sbtPlayEbean = ProjectRef(Path.fileProperty("user.dir").getParentFile, "plugin") 6 | 7 | resolvers ++= DefaultOptions.resolvers(snapshot = true) 8 | 9 | addSbtPlugin("org.playframework" % "play-docs-sbt-plugin" % sys.props.getOrElse("play.version", "3.1.0-M4")) 10 | 11 | addSbtPlugin("com.lightbend.sbt" % "sbt-java-formatter" % "0.8.0") 12 | 13 | addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.6") 14 | 15 | addSbtPlugin("com.github.sbt" % "sbt-header" % "5.11.0") 16 | -------------------------------------------------------------------------------- /docs/.scalafmt.conf: -------------------------------------------------------------------------------- 1 | # ATTENTION: 2 | # This was copy and pasted from ../.scalafmt.conf, so keep both files in sync. 3 | 4 | align.preset = true 5 | assumeStandardLibraryStripMargin = true 6 | danglingParentheses.preset = true 7 | docstrings.style = Asterisk 8 | maxColumn = 120 9 | project.git = true 10 | rewrite.rules = [ AvoidInfix, ExpandImportSelectors, RedundantParens, SortModifiers, PreferCurlyFors ] 11 | rewrite.sortModifiers.order = [ "private", "protected", "final", "sealed", "abstract", "implicit", "override", "lazy" ] 12 | spaces.inImportCurlyBraces = true # more idiomatic to include whitepsace in import x.{ yyy } 13 | trailingCommas = preserve 14 | newlines.afterCurlyLambda = preserve 15 | runner.dialect = scala212source3 16 | version = 3.10.2 17 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/enhancement/app/models/Task.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package models; 6 | 7 | import java.util.*; 8 | import jakarta.persistence.*; 9 | 10 | import io.ebean.*; 11 | import play.data.format.*; 12 | import play.data.validation.*; 13 | 14 | @Entity 15 | public class Task extends Model { 16 | 17 | public static final Finder find = new Finder<>(Task.class); 18 | 19 | @Id 20 | public Long id; 21 | 22 | @Constraints.Required 23 | public String name; 24 | 25 | public boolean done; 26 | 27 | @Formats.DateTime(pattern = "dd/MM/yyyy") 28 | public Date dueDate = new Date(); 29 | } 30 | -------------------------------------------------------------------------------- /.github/workflows/dependency-graph.yml: -------------------------------------------------------------------------------- 1 | name: Dependency Graph 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | concurrency: 8 | # Only run once for latest commit per ref and cancel other (previous) runs. 9 | group: dependency-graph-${{ github.ref }} 10 | cancel-in-progress: true 11 | 12 | permissions: 13 | contents: write # this permission is needed to submit the dependency graph 14 | 15 | jobs: 16 | dependency-graph: 17 | name: Submit dependencies to GitHub 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v6 21 | with: 22 | fetch-depth: 0 23 | ref: ${{ inputs.ref }} 24 | - uses: sbt/setup-sbt@v1 25 | - uses: scalacenter/sbt-dependency-submission@v3 # for root project 26 | - uses: scalacenter/sbt-dependency-submission@v3 27 | with: 28 | working-directory: ./docs/ 29 | -------------------------------------------------------------------------------- /docs/manual/working/javaGuide/main/sql/code/ebean.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | //#add-sbt-plugin 4 | addSbtPlugin("org.playframework" % "sbt-play-ebean" % "8.2.0") 5 | //#add-sbt-plugin 6 | 7 | //#enable-plugin 8 | lazy val myProject = (project in file(".")) 9 | .enablePlugins(PlayJava, PlayEbean) 10 | 11 | //#enable-plugin 12 | 13 | //#play-ebean-models 14 | Compile / playEbeanModels := Seq("models.*") 15 | //#play-ebean-models 16 | 17 | //#play-ebean-debug 18 | playEbeanDebugLevel := 4 19 | //#play-ebean-debug 20 | 21 | //#play-ebean-agent-args 22 | playEbeanAgentArgs += ("detect" -> "false") 23 | //#play-ebean-agent-args 24 | 25 | //#play-ebean-test 26 | inConfig(Test)(PlayEbean.scopedSettings) 27 | 28 | Test / playEbeanModels := Seq("models.*") 29 | //#play-ebean-test 30 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/EbeanModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import play.api.Configuration; 8 | import play.api.Environment; 9 | import play.api.db.evolutions.DynamicEvolutions; 10 | import play.api.inject.Binding; 11 | import play.api.inject.Module; 12 | import scala.collection.Seq; 13 | 14 | /** Injection module with default Ebean components. */ 15 | public class EbeanModule extends Module { 16 | 17 | @Override 18 | public Seq> bindings(Environment environment, Configuration configuration) { 19 | return seq( 20 | bind(DynamicEvolutions.class).to(EbeanDynamicEvolutions.class).eagerly(), 21 | bind(EbeanConfig.class).toProvider(DefaultEbeanConfig.EbeanConfigParser.class).eagerly()); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/sbt-test/sbt-ebean/enhancement/tests/models/TestTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package models; 6 | 7 | import org.junit.*; 8 | 9 | import static org.junit.Assert.*; 10 | 11 | import play.test.*; 12 | import play.Application; 13 | 14 | import static play.test.Helpers.*; 15 | 16 | public class TestTask extends WithApplication { 17 | 18 | protected Application provideApplication() { 19 | return fakeApplication(inMemoryDatabase()); 20 | } 21 | 22 | @Test 23 | public void saveAndFind() { 24 | Task task = new Task(); 25 | task.id = 10L; 26 | task.name = "Hello"; 27 | task.done = false; 28 | task.save(); 29 | 30 | Task saved = Task.find.byId(10L); 31 | assertEquals("Hello", saved.name); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/EBeanComponents.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import play.api.db.evolutions.DefaultEvolutionsConfigParser; 8 | import play.api.db.evolutions.DynamicEvolutions; 9 | import play.api.db.evolutions.EvolutionsConfig; 10 | import play.components.ConfigurationComponents; 11 | import play.db.DBComponents; 12 | 13 | /** Classes for Java compile time dependency injection. */ 14 | public interface EBeanComponents extends ConfigurationComponents, DBComponents { 15 | 16 | default DynamicEvolutions dynamicEvolutions() { 17 | return new EbeanDynamicEvolutions( 18 | ebeanConfig(), environment(), applicationLifecycle(), evolutionsConfig()); 19 | } 20 | 21 | default EbeanConfig ebeanConfig() { 22 | return new DefaultEbeanConfig.EbeanConfigParser(config(), environment(), dbApi()).get(); 23 | } 24 | 25 | default EvolutionsConfig evolutionsConfig() { 26 | return new DefaultEvolutionsConfigParser(configuration()).parse(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/ModelsConfigLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import java.io.File; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.function.Function; 11 | import play.Mode; 12 | import play.api.Configuration; 13 | import play.api.Environment; 14 | 15 | /** 16 | * Given a classloader, load the models configuration. 17 | * 18 | *

This is used by the ebean sbt plugin to get the same models configuration that will be loaded 19 | * by the app. 20 | */ 21 | public class ModelsConfigLoader implements Function>> { 22 | 23 | @Override 24 | public Map> apply(ClassLoader classLoader) { 25 | // Using TEST mode is the only way to load configuration without failing if application.conf 26 | // doesn't exist 27 | Environment env = new Environment(new File("."), classLoader, Mode.TEST.asScala()); 28 | Configuration config = Configuration.load(env); 29 | return EbeanParsedConfig.parseFromConfig(config.underlying()).getDatasourceModels(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /docs/manual/working/javaGuide/main/sql/code/javaguide/ebean/Task.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | // #content 6 | // ###replace: package models; 7 | package javaguide.ebean; 8 | 9 | import io.ebean.*; 10 | import jakarta.persistence.*; 11 | import java.util.*; 12 | import play.data.format.*; 13 | import play.data.validation.*; 14 | 15 | @Entity 16 | public class Task extends Model { 17 | 18 | @Id 19 | @Constraints.Min(10) 20 | private Long id; 21 | 22 | @Constraints.Required private String name; 23 | 24 | private boolean done; 25 | 26 | @Formats.DateTime(pattern = "dd/MM/yyyy") 27 | private Date dueDate = new Date(); 28 | 29 | public Long getId() { 30 | return id; 31 | } 32 | 33 | public void setId(Long id) { 34 | this.id = id; 35 | } 36 | 37 | public String getName() { 38 | return name; 39 | } 40 | 41 | public void setName(String name) { 42 | this.name = name; 43 | } 44 | 45 | public boolean isDone() { 46 | return done; 47 | } 48 | 49 | public void setDone(boolean done) { 50 | this.done = done; 51 | } 52 | 53 | public Date getDueDate() { 54 | return dueDate; 55 | } 56 | 57 | public void setDueDate(Date dueDate) { 58 | this.dueDate = dueDate; 59 | } 60 | 61 | public static final Finder find = new Finder<>(Task.class); 62 | } 63 | // #content 64 | -------------------------------------------------------------------------------- /common.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// 4 | // NOTE: !!! THIS IS A COPY !!! // 5 | // To edit this file use the main version in https://github.com/playframework/.github/blob/main/sbt/common.sbt // 6 | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// 7 | 8 | /** 9 | * If you need extra commands to format source code or other documents, add following line to your `build.sbt` 10 | * {{{ 11 | * val _ = sys.props += ("sbt_formatCode" -> List("", "",...).mkString(";")) 12 | * }}} 13 | */ 14 | addCommandAlias( 15 | "formatCode", 16 | List( 17 | "headerCreateAll", 18 | "scalafmtSbt", 19 | "scalafmtAll", 20 | "javafmtAll" 21 | ).mkString(";") + sys.props.get("sbt_formatCode").map(";" + _).getOrElse("") 22 | ) 23 | 24 | /** 25 | * If you need extra commands to validate source code or other documents, add following line to your `build.sbt` 26 | * {{{ 27 | * val _ = sys.props += ("sbt_validateCode" -> List("", "",...).mkString(";")) 28 | * }}} 29 | */ 30 | addCommandAlias( 31 | "validateCode", 32 | List( 33 | "headerCheckAll", 34 | "scalafmtSbtCheck", 35 | "scalafmtCheckAll", 36 | "javafmtCheckAll" 37 | ).mkString(";") + sys.props.get("sbt_validateCode").map(";" + _).getOrElse("") 38 | ) 39 | -------------------------------------------------------------------------------- /docs/common.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// 4 | // NOTE: !!! THIS IS A COPY !!! // 5 | // To edit this file use the main version in https://github.com/playframework/.github/blob/main/sbt/common.sbt // 6 | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// 7 | 8 | /** 9 | * If you need extra commands to format source code or other documents, add following line to your `build.sbt` 10 | * {{{ 11 | * val _ = sys.props += ("sbt_formatCode" -> List("", "",...).mkString(";")) 12 | * }}} 13 | */ 14 | addCommandAlias( 15 | "formatCode", 16 | List( 17 | "headerCreateAll", 18 | "scalafmtSbt", 19 | "scalafmtAll", 20 | "javafmtAll" 21 | ).mkString(";") + sys.props.get("sbt_formatCode").map(";" + _).getOrElse("") 22 | ) 23 | 24 | /** 25 | * If you need extra commands to validate source code or other documents, add following line to your `build.sbt` 26 | * {{{ 27 | * val _ = sys.props += ("sbt_validateCode" -> List("", "",...).mkString(";")) 28 | * }}} 29 | */ 30 | addCommandAlias( 31 | "validateCode", 32 | List( 33 | "headerCheckAll", 34 | "scalafmtSbtCheck", 35 | "scalafmtCheckAll", 36 | "javafmtCheckAll" 37 | ).mkString(";") + sys.props.get("sbt_validateCode").map(";" + _).getOrElse("") 38 | ) 39 | -------------------------------------------------------------------------------- /project/Dependencies.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | import sbt.Keys.libraryDependencies 6 | 7 | import sbt._ 8 | 9 | object Dependencies { 10 | 11 | object ScalaVersions { 12 | val scala212 = "2.12.21" 13 | val scala213 = "2.13.18" 14 | val scala3 = "3.3.7" 15 | } 16 | 17 | object Versions { 18 | val play: String = "3.1.0-M4" 19 | val ebean = "17.2.0" 20 | val typesafeConfig = "1.4.5" 21 | } 22 | 23 | val ebean = libraryDependencies ++= Seq( 24 | ("io.ebean" % "ebean" % Versions.ebean).excludeAll(ExclusionRule("com.fasterxml.jackson.core")), 25 | "io.ebean" % "ebean-ddl-generator" % Versions.ebean, 26 | "io.ebean" % "ebean-agent" % Versions.ebean, 27 | "org.playframework" %% "play-java-jdbc" % Versions.play, 28 | "org.playframework" %% "play-jdbc-evolutions" % Versions.play, 29 | "org.playframework" %% "play-guice" % Versions.play % Test, 30 | "org.playframework" %% "play-filters-helpers" % Versions.play % Test, 31 | "org.playframework" %% "play-test" % Versions.play % Test, 32 | ("org.reflections" % "reflections" % "0.10.2") 33 | .exclude("com.google.code.findbugs", "annotations") 34 | .classifier("") 35 | ) 36 | 37 | val plugin = libraryDependencies ++= Seq( 38 | "io.ebean" % "ebean" % Versions.ebean, 39 | "io.ebean" % "ebean-agent" % Versions.ebean, 40 | "com.typesafe" % "config" % Versions.typesafeConfig, 41 | ) 42 | } 43 | -------------------------------------------------------------------------------- /.github/workflows/build-test.yml: -------------------------------------------------------------------------------- 1 | name: Check 2 | 3 | on: 4 | pull_request: 5 | 6 | push: 7 | branches: 8 | - main # Check branch after merge 9 | 10 | concurrency: 11 | # Only run once for latest commit per ref and cancel other (previous) runs. 12 | group: ci-${{ github.ref }} 13 | cancel-in-progress: true 14 | 15 | jobs: 16 | check-code-style: 17 | name: Code Style 18 | uses: playframework/.github/.github/workflows/cmd.yml@v4 19 | with: 20 | cmd: sbt validateCode 21 | 22 | check-binary-compatibility: 23 | name: Binary Compatibility 24 | uses: playframework/.github/.github/workflows/binary-check.yml@v4 25 | 26 | check-docs: 27 | name: Docs 28 | uses: playframework/.github/.github/workflows/cmd.yml@v4 29 | with: 30 | java: 21, 17 31 | scala: 2.13.x, 3.x 32 | cmd: cd docs && sbt ++$MATRIX_SCALA validateCode 33 | 34 | tests: 35 | name: Tests 36 | needs: 37 | - "check-code-style" 38 | - "check-binary-compatibility" 39 | - "check-docs" 40 | uses: playframework/.github/.github/workflows/cmd.yml@v4 41 | with: 42 | java: 21, 17 43 | scala: 2.13.x, 3.x 44 | cmd: >- 45 | sbt ++$MATRIX_SCALA test 46 | 47 | scripted-tests: 48 | name: Scripted tests 49 | needs: 50 | - "check-code-style" 51 | - "check-binary-compatibility" 52 | - "check-docs" 53 | uses: playframework/.github/.github/workflows/cmd.yml@v4 54 | with: 55 | java: 21, 17 56 | scala: 2.13.18, 3.3.6 57 | cmd: >- 58 | sbt " 59 | +publishLocal; 60 | set plugin/scriptedLaunchOpts += \"-Dscala.version=$MATRIX_SCALA\"; 61 | show scriptedSbt; 62 | show scriptedLaunchOpts; 63 | plugin/scripted; 64 | " 65 | 66 | finish: 67 | name: Finish 68 | if: github.event_name == 'pull_request' 69 | needs: # Should be last 70 | - "tests" 71 | - "scripted-tests" 72 | uses: playframework/.github/.github/workflows/rtm.yml@v4 73 | -------------------------------------------------------------------------------- /play-ebean/src/test/java/play/db/ebean/EBeanComponentsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import java.util.Collections; 8 | import org.junit.Test; 9 | import play.Application; 10 | import play.ApplicationLoader; 11 | import play.Environment; 12 | import play.LoggerConfigurator; 13 | import play.api.Play; 14 | import play.components.BodyParserComponents; 15 | import play.db.HikariCPComponents; 16 | import play.filters.components.NoHttpFiltersComponents; 17 | import play.mvc.Results; 18 | import play.routing.RoutingDslComponentsFromContext; 19 | 20 | public class EBeanComponentsTest { 21 | 22 | static class MyComponents extends RoutingDslComponentsFromContext 23 | implements NoHttpFiltersComponents, 24 | BodyParserComponents, 25 | EBeanComponents, 26 | HikariCPComponents { 27 | 28 | public MyComponents(ApplicationLoader.Context context) { 29 | super(context); 30 | } 31 | 32 | @Override 33 | public play.routing.Router router() { 34 | return routingDsl().GET("/").routingTo((req) -> Results.ok("Hello")).build(); 35 | } 36 | } 37 | 38 | static class MyApplicationLoader implements ApplicationLoader { 39 | @Override 40 | public Application load(Context context) { 41 | LoggerConfigurator.apply(context.environment().classLoader()) 42 | .ifPresent( 43 | lc -> { 44 | lc.configure( 45 | context.environment(), context.initialConfig(), Collections.emptyMap()); 46 | }); 47 | 48 | return new MyComponents(context).application(); 49 | } 50 | } 51 | 52 | @Test 53 | public void createComponents() { 54 | MyApplicationLoader loader = new MyApplicationLoader(); 55 | Application application = loader.load(new ApplicationLoader.Context(Environment.simple())); 56 | 57 | Play.start(application.asScala()); 58 | Play.stop(application.asScala()); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /project/Common.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | import sbtheader.HeaderPlugin.autoImport.HeaderPattern.commentBetween 6 | import sbt.Keys.* 7 | import sbt.* 8 | import sbt.plugins.JvmPlugin 9 | import sbtheader.CommentStyle 10 | import sbtheader.FileType 11 | import sbtheader.HeaderPlugin 12 | import sbtheader.LineCommentCreator 13 | 14 | object Common extends AutoPlugin { 15 | 16 | import HeaderPlugin.autoImport._ 17 | 18 | override def trigger = allRequirements 19 | 20 | override def requires = JvmPlugin && HeaderPlugin 21 | 22 | val repoName = "play-ebean" 23 | 24 | override def globalSettings: Seq[Setting[_]] = 25 | Seq( 26 | // organization 27 | organization := "org.playframework", 28 | organizationName := "The Play Framework Project", 29 | organizationHomepage := Some(url("https://playframework.com/")), 30 | scalacOptions ++= Seq("-deprecation", "-feature", "-unchecked", "-encoding", "utf8"), 31 | javacOptions ++= Seq("-encoding", "UTF-8"), 32 | // legal 33 | licenses := Seq("Apache-2.0" -> url("https://www.apache.org/licenses/LICENSE-2.0.html")), 34 | // on the web 35 | homepage := Some(url(s"https://github.com/playframework/$repoName")), 36 | scmInfo := Some( 37 | ScmInfo( 38 | url(s"https://github.com/playframework/$repoName"), 39 | s"scm:git:git@github.com:playframework/$repoName.git" 40 | ) 41 | ), 42 | developers += Developer( 43 | "playframework", 44 | "The Play Framework Contributors", 45 | "contact@playframework.com", 46 | url("https://github.com/playframework") 47 | ) 48 | ) 49 | 50 | override def projectSettings: Seq[Def.Setting[_]] = 51 | Seq( 52 | headerLicense := Some( 53 | HeaderLicense.Custom( 54 | "Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. " 55 | ) 56 | ), 57 | headerMappings ++= Map( 58 | FileType("sbt") -> HeaderCommentStyle.cppStyleLineComment, 59 | FileType("properties") -> HeaderCommentStyle.hashLineComment, 60 | FileType("md") -> CommentStyle(new LineCommentCreator(""), commentBetween("")) 61 | ) 62 | ) 63 | } 64 | -------------------------------------------------------------------------------- /docs/build.sbt: -------------------------------------------------------------------------------- 1 | // Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 2 | 3 | import sbtheader.CommentStyle 4 | import sbtheader.FileType 5 | import sbtheader.HeaderPlugin 6 | import sbtheader.HeaderPlugin.autoImport.HeaderPattern.commentBetween 7 | import sbtheader.LineCommentCreator 8 | 9 | SettingKey[Seq[File]]("migrationManualSources") := Nil 10 | 11 | lazy val docs = project 12 | .in(file(".")) 13 | .enablePlugins(PlayDocsPlugin, PlayEbean) 14 | .settings( 15 | // use special snapshot play version for now 16 | resolvers ++= DefaultOptions.resolvers(snapshot = true), 17 | libraryDependencies += component("play-java-forms"), 18 | libraryDependencies += component("play-test") % Test, 19 | libraryDependencies += "com.h2database" % "h2" % "2.4.240" % Test, 20 | PlayDocsKeys.javaManualSourceDirectories := (baseDirectory.value / "manual" / "working" / "javaGuide" ** "code").get, 21 | // No resource directories shuts the ebean agent up about java sources in the classes directory 22 | Test / unmanagedResourceDirectories := Nil, 23 | Test / parallelExecution := false, 24 | scalaVersion := "2.13.18", 25 | crossScalaVersions := Seq("2.13.18", "3.3.6"), 26 | ) 27 | .settings( 28 | Test / javafmt / sourceDirectories ++= (Test / unmanagedSourceDirectories).value, 29 | ) 30 | .settings( 31 | headerLicense := Some( 32 | HeaderLicense.Custom( 33 | "Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. " 34 | ) 35 | ), 36 | headerMappings ++= Map( 37 | FileType("sbt") -> HeaderCommentStyle.cppStyleLineComment, 38 | FileType("properties") -> HeaderCommentStyle.hashLineComment, 39 | FileType("md") -> CommentStyle(new LineCommentCreator(""), commentBetween("")) 40 | ), 41 | Compile / headerSources ++= 42 | ((baseDirectory.value ** ("*.properties" || "*.md" || "*.sbt")) 43 | --- (baseDirectory.value ** "target" ** "*")).get, 44 | ) 45 | .settings(PlayEbean.unscopedSettings: _*) 46 | .settings( 47 | inConfig(Test)( 48 | Seq( 49 | playEbeanModels := Seq("javaguide.ebean.*") 50 | ) 51 | ): _* 52 | ) 53 | .dependsOn(playEbean) 54 | 55 | lazy val playEbean = ProjectRef(Path.fileProperty("user.dir").getParentFile, "core") 56 | 57 | val _ = sys.props += ("sbt_validateCode" -> List( 58 | "evaluateSbtFiles", 59 | "validateDocs", 60 | ).mkString(";")) 61 | -------------------------------------------------------------------------------- /play-ebean/src/test/java/play/db/ebean/EbeanParsedConfigTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import static org.hamcrest.CoreMatchers.*; 8 | import static org.hamcrest.MatcherAssert.*; 9 | 10 | import com.google.common.collect.ImmutableMap; 11 | import com.typesafe.config.ConfigFactory; 12 | import java.util.Arrays; 13 | import java.util.Collections; 14 | import java.util.Map; 15 | import org.junit.*; 16 | 17 | public class EbeanParsedConfigTest { 18 | 19 | private EbeanParsedConfig parse(Map config) { 20 | return EbeanParsedConfig.parseFromConfig( 21 | ConfigFactory.parseMap(config).withFallback(ConfigFactory.defaultReference())); 22 | } 23 | 24 | @Test 25 | public void defaultConfig() { 26 | EbeanParsedConfig config = parse(Collections.emptyMap()); 27 | assertThat(config.getDefaultDatasource(), equalTo("default")); 28 | assertThat(config.getDatasourceModels().size(), equalTo(0)); 29 | assertThat(config.generateEvolutionsScripts(), equalTo(Boolean.TRUE)); 30 | } 31 | 32 | @Test 33 | public void withDataSources() { 34 | EbeanParsedConfig config = 35 | parse( 36 | ImmutableMap.of( 37 | "ebean.default", Arrays.asList("a", "b"), 38 | "ebean.other", Collections.singletonList("c"))); 39 | assertThat(config.getDatasourceModels().size(), equalTo(2)); 40 | assertThat(config.getDatasourceModels().get("default"), hasItems("a", "b")); 41 | assertThat(config.getDatasourceModels().get("other"), hasItems("c")); 42 | } 43 | 44 | @Test 45 | public void commaSeparatedModels() { 46 | EbeanParsedConfig config = parse(ImmutableMap.of("ebean.default", "a,b")); 47 | assertThat(config.getDatasourceModels().get("default"), hasItems("a", "b")); 48 | } 49 | 50 | @Test 51 | public void customDefault() { 52 | EbeanParsedConfig config = parse(ImmutableMap.of("play.ebean.defaultDatasource", "custom")); 53 | assertThat(config.getDefaultDatasource(), equalTo("custom")); 54 | } 55 | 56 | @Test 57 | public void disableGenerateEvolutionsScripts() { 58 | EbeanParsedConfig config = 59 | parse(ImmutableMap.of("play.ebean.generateEvolutionsScripts", false)); 60 | assertThat(config.generateEvolutionsScripts(), equalTo(Boolean.FALSE)); 61 | } 62 | 63 | @Test 64 | public void customConfig() { 65 | EbeanParsedConfig config = 66 | parse( 67 | ImmutableMap.of( 68 | "play.ebean.config", 69 | "my.custom", 70 | "my.custom.default", 71 | Collections.singletonList("a"))); 72 | assertThat(config.getDatasourceModels().size(), equalTo(1)); 73 | assertThat(config.getDatasourceModels().get("default"), hasItems("a")); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/EbeanParsedConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import com.typesafe.config.Config; 8 | import com.typesafe.config.ConfigValueType; 9 | import java.util.Arrays; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | /** 15 | * The raw parsed config from Ebean, as opposed to the EbeanConfig which actually requires starting 16 | * database connection pools to create. 17 | */ 18 | public class EbeanParsedConfig { 19 | 20 | private final String defaultDatasource; 21 | 22 | private final Map> datasourceModels; 23 | 24 | private final boolean generateEvolutionsScripts; 25 | 26 | public EbeanParsedConfig( 27 | String defaultDatasource, 28 | Map> datasourceModels, 29 | boolean generateEvolutionsScripts) { 30 | this.defaultDatasource = defaultDatasource; 31 | this.datasourceModels = datasourceModels; 32 | this.generateEvolutionsScripts = generateEvolutionsScripts; 33 | } 34 | 35 | public EbeanParsedConfig(String defaultDatasource, Map> datasourceModels) { 36 | this(defaultDatasource, datasourceModels, true); 37 | } 38 | 39 | public String getDefaultDatasource() { 40 | return defaultDatasource; 41 | } 42 | 43 | public Map> getDatasourceModels() { 44 | return datasourceModels; 45 | } 46 | 47 | public boolean generateEvolutionsScripts() { 48 | return generateEvolutionsScripts; 49 | } 50 | 51 | /** 52 | * Parse a play configuration. 53 | * 54 | * @param config play configuration 55 | * @return ebean parsed configuration 56 | * @see com.typesafe.config.Config 57 | */ 58 | public static EbeanParsedConfig parseFromConfig(Config config) { 59 | Config playEbeanConfig = config.getConfig("play.ebean"); 60 | String defaultDatasource = playEbeanConfig.getString("defaultDatasource"); 61 | String ebeanConfigKey = playEbeanConfig.getString("config"); 62 | boolean generateEvolutionsScripts = playEbeanConfig.getBoolean("generateEvolutionsScripts"); 63 | 64 | Map> datasourceModels = new HashMap<>(); 65 | 66 | if (config.hasPath(ebeanConfigKey)) { 67 | Config ebeanConfig = config.getConfig(ebeanConfigKey); 68 | ebeanConfig 69 | .root() 70 | .forEach( 71 | (key, raw) -> { 72 | List models; 73 | if (raw.valueType() == ConfigValueType.STRING) { 74 | // Support legacy comma separated string 75 | models = Arrays.asList(((String) raw.unwrapped()).split(",")); 76 | } else { 77 | models = ebeanConfig.getStringList(key); 78 | } 79 | 80 | datasourceModels.put(key, models); 81 | }); 82 | } 83 | return new EbeanParsedConfig(defaultDatasource, datasourceModels, generateEvolutionsScripts); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /docs/manual/working/javaGuide/main/sql/code/javaguide/ebean/JavaEbeanTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package javaguide.ebean; 6 | 7 | import static org.hamcrest.CoreMatchers.*; 8 | import static org.junit.Assert.*; 9 | import static play.test.Helpers.*; 10 | 11 | import io.ebean.Ebean; 12 | import java.util.HashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | import org.junit.*; 16 | import play.Application; 17 | import play.db.ebean.Transactional; 18 | import play.mvc.Controller; 19 | import play.mvc.Result; 20 | import play.test.*; 21 | 22 | public class JavaEbeanTest extends WithApplication { 23 | 24 | @Override 25 | protected Application provideApplication() { 26 | Map config = new HashMap<>(); 27 | config.putAll(inMemoryDatabase()); 28 | config.put("ebean.default", "javaguide.ebean.Task"); 29 | return fakeApplication(config); 30 | } 31 | 32 | @Test 33 | public void taskOperations() { 34 | createTask(); 35 | 36 | // #operations 37 | // Find all tasks 38 | List tasks = Task.find.all(); 39 | 40 | // Find a task by ID 41 | Task anyTask = Task.find.byId(34L); 42 | 43 | // Delete a task by ID 44 | Task.find.ref(34L).delete(); 45 | 46 | // More complex task query 47 | List cocoTasks = 48 | Task.find 49 | .query() 50 | .where() 51 | .ilike("name", "%coco%") 52 | .orderBy("dueDate asc") 53 | .setFirstRow(0) 54 | .setMaxRows(25) 55 | .findPagedList() 56 | .getList(); 57 | // #operations 58 | 59 | assertThat(tasks.size(), equalTo(1)); 60 | assertThat(tasks.get(0).getName(), equalTo("coco")); 61 | assertThat(anyTask.getName(), equalTo("coco")); 62 | assertThat(cocoTasks.size(), equalTo(0)); 63 | assertThat(Task.find.all().size(), equalTo(0)); 64 | } 65 | 66 | @Test 67 | public void transactionExplanation() { 68 | createTask(); 69 | 70 | // #transaction 71 | // Created implicit transaction 72 | Task task = Task.find.byId(34L); 73 | // Transaction committed or rolled back 74 | 75 | task.setDone(true); 76 | 77 | // Created implicit transaction 78 | task.save(); 79 | // Transaction committed or rolled back 80 | // #transaction 81 | 82 | assertThat(Task.find.byId(34L).isDone(), is(true)); 83 | } 84 | 85 | @Test 86 | public void txRunnable() { 87 | createTask(); 88 | 89 | // #txrunnable 90 | // ###insert: import io.ebean.*; 91 | 92 | // ###insert: ... 93 | 94 | Ebean.execute( 95 | () -> { 96 | // code running in "REQUIRED" transactional scope 97 | // ... as "REQUIRED" is the default TxType 98 | System.out.println(Ebean.currentTransaction()); 99 | 100 | Task task = Task.find.byId(34L); 101 | task.setDone(true); 102 | 103 | task.save(); 104 | }); 105 | // #txrunnable 106 | 107 | assertThat(Task.find.byId(34L).isDone(), is(true)); 108 | } 109 | 110 | public class TransactionController extends Controller { 111 | 112 | // #annotation 113 | // ###insert: import play.db.ebean.Transactional; 114 | 115 | // ###insert: ... 116 | 117 | @Transactional 118 | public Result done(long id) { 119 | Task task = Task.find.byId(34L); 120 | task.setDone(true); 121 | 122 | task.save(); 123 | return ok(); 124 | } 125 | // #annotation 126 | 127 | } 128 | 129 | @Test 130 | public void traditional() { 131 | createTask(); 132 | 133 | // #traditional 134 | Ebean.beginTransaction(); 135 | try { 136 | Task task = Task.find.byId(34L); 137 | task.setDone(true); 138 | 139 | task.save(); 140 | 141 | Ebean.commitTransaction(); 142 | } finally { 143 | Ebean.endTransaction(); 144 | } 145 | // #traditional 146 | 147 | assertThat(Task.find.byId(34L).isDone(), is(true)); 148 | } 149 | 150 | private void createTask() { 151 | Task task = new Task(); 152 | task.setId(34L); 153 | task.setName("coco"); 154 | task.save(); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/EbeanDynamicEvolutions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import io.ebean.Database; 8 | import io.ebean.DatabaseFactory; 9 | import io.ebeaninternal.api.SpiEbeanServer; 10 | import io.ebeaninternal.dbmigration.model.CurrentModel; 11 | import jakarta.inject.Inject; 12 | import jakarta.inject.Singleton; 13 | import java.io.File; 14 | import java.io.IOException; 15 | import java.nio.charset.StandardCharsets; 16 | import java.nio.file.Files; 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | import java.util.concurrent.CompletableFuture; 20 | import play.Environment; 21 | import play.api.db.evolutions.DynamicEvolutions; 22 | import play.api.db.evolutions.Evolutions$; 23 | import play.api.db.evolutions.EvolutionsConfig; 24 | import play.inject.ApplicationLifecycle; 25 | 26 | /** A Play module that automatically manages Ebean configuration. */ 27 | @Singleton 28 | public class EbeanDynamicEvolutions extends DynamicEvolutions { 29 | 30 | private final EbeanConfig config; 31 | private final Environment environment; 32 | 33 | private final EvolutionsConfig evolutionsConfig; 34 | 35 | private final Map databases = new HashMap<>(); 36 | 37 | @Inject 38 | public EbeanDynamicEvolutions( 39 | EbeanConfig config, 40 | Environment environment, 41 | ApplicationLifecycle lifecycle, 42 | EvolutionsConfig evolutionsConfig) { 43 | this.config = config; 44 | this.environment = environment; 45 | this.evolutionsConfig = evolutionsConfig; 46 | start(); 47 | lifecycle.addStopHook( 48 | () -> { 49 | databases.forEach((key, database) -> database.shutdown(false, false)); 50 | return CompletableFuture.completedFuture(null); 51 | }); 52 | } 53 | 54 | /** Initialise the Ebean servers/databases. */ 55 | public void start() { 56 | config 57 | .serverConfigs() 58 | .forEach((key, serverConfig) -> databases.put(key, DatabaseFactory.create(serverConfig))); 59 | } 60 | 61 | /** Generate evolutions. */ 62 | @Override 63 | public void create() { 64 | if (environment.isProd()) { 65 | return; 66 | } 67 | if (!config.generateEvolutionsScripts()) { 68 | return; 69 | } 70 | config 71 | .serverConfigs() 72 | .forEach( 73 | (key, serverConfig) -> { 74 | String evolutionScript = generateEvolutionScript(databases.get(key)); 75 | if (evolutionScript == null) { 76 | return; 77 | } 78 | File evolutions = 79 | environment.getFile( 80 | Evolutions$.MODULE$.fileName( 81 | key, 1, evolutionsConfig.forDatasource(key).path())); 82 | try { 83 | String content = ""; 84 | if (evolutions.exists()) { 85 | content = 86 | new String(Files.readAllBytes(evolutions.toPath()), StandardCharsets.UTF_8); 87 | } 88 | if (content.isEmpty() 89 | || content.startsWith("# --- Created by Ebean DDL") 90 | || content.startsWith("-- Created by Ebean DDL")) { 91 | environment 92 | .getFile( 93 | Evolutions$.MODULE$.directoryName( 94 | key, evolutionsConfig.forDatasource(key).path())) 95 | .mkdirs(); 96 | if (!content.equals(evolutionScript)) { 97 | Files.write( 98 | evolutions.toPath(), evolutionScript.getBytes(StandardCharsets.UTF_8)); 99 | } 100 | } 101 | } catch (IOException e) { 102 | throw new RuntimeException(e); 103 | } 104 | }); 105 | } 106 | 107 | /** 108 | * Helper method that generates the required evolution to properly run Ebean/DB. 109 | * 110 | * @param database the Database. 111 | * @return the complete migration generated by Ebean/DB. 112 | */ 113 | public static String generateEvolutionScript(Database database) { 114 | return generateScript((SpiEbeanServer) database); 115 | } 116 | 117 | private static String generateScript(SpiEbeanServer spiServer) { 118 | CurrentModel ddl = new CurrentModel(spiServer); 119 | 120 | String ups = ddl.getCreateDdl(); 121 | String downs = ddl.getDropAllDdl(); 122 | 123 | if (ups == null || ups.trim().isEmpty()) { 124 | return null; 125 | } 126 | 127 | return "-- Created by Ebean DDL\r\n" 128 | + "-- To stop Ebean DDL generation, remove this comment (both lines) and start using Evolutions\r\n" 129 | + "\r\n" 130 | + "-- !Ups\r\n" 131 | + "\r\n" 132 | + ups 133 | + "\r\n" 134 | + "-- !Downs\r\n" 135 | + "\r\n" 136 | + downs; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /docs/manual/working/javaGuide/main/sql/JavaEbean.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Using the Ebean ORM 4 | 5 | ## Configuring Ebean 6 | 7 | Play comes with the [Ebean](https://ebean-orm.github.io/) ORM. To enable it, add the Play Ebean plugin to your SBT plugins in `project/plugins.sbt`: 8 | 9 | @[add-sbt-plugin](code/ebean.sbt) 10 | 11 | > **Note**: see all available version [here](https://github.com/playframework/play-ebean#releases). 12 | 13 | And then modify your `build.sbt` to enable the Play Ebean plugin: 14 | 15 | @[enable-plugin](code/ebean.sbt) 16 | 17 | ### Configuring models 18 | 19 | Play Ebean comes with two components, a runtime library that actually talks to the database, and an sbt plugin that enhances the compiled Java bytecode of your models for use with Ebean. Both of these components need to be configured so that Ebean knows where your models are. 20 | 21 | #### Configuring the runtime library 22 | 23 | The runtime library can be configured by putting the list of packages and/or classes that your Ebean models live in your application configuration file. For example, if all your models are in the `models` package, add the following to `conf/application.conf`: 24 | 25 | ```properties 26 | ebean.default = ["models.*"] 27 | ``` 28 | 29 | This defines a `default` Ebean server, using the `default` data source, which must be properly configured. You can also override the name of the default Ebean server by configuring `ebeanconfig.datasource.default` property. This might be useful if you want to use separate databases for testing and development. You can actually create as many Ebean servers you need, and explicitly define the mapped class for each server: 30 | 31 | ```properties 32 | ebean.orders = ["models.Order", "models.OrderItem"] 33 | ebean.customers = ["models.Customer", "models.Address"] 34 | ``` 35 | 36 | In this example, we have access to two Ebean servers - each using its own database. 37 | 38 | Each `ebean.` config line (as above) can map *any* classes that Ebean may be interested in registering (eg. `@Entity`/`Model` classes, `@Embeddable`s, custom `ScalarType`s and `CompoundType`s, `BeanPersistController`s, `BeanPersistListener`s, `BeanFinder`s, `ServerConfigStartup`s, etc). These can be individually listed separated by commas, and/or you can use the wildcard `.*`. For example, `models.*` registers with Ebean all classes within the models package that Ebean can make use of. 39 | 40 | To customise the underlying Ebean Server configuration, you can either add a [`conf/application.yaml`](https://ebean.io/docs/intro/configuration/) file, or create an instance of the `ServerConfigStartup` interface to programmatically manipulate the Ebean `ServerConfig` before the server is initialised. 41 | 42 | As an example, the fairly common problem of reducing the sequence batch size in order to minimise sequence gaps, could be solved quite simply with a class like this: 43 | 44 | @[content](code/javaguide/ebean/MyServerConfigStartup.java) 45 | 46 | Note that Ebean will also make use of a `conf/orm.xml` file (if present), to configure ``. 47 | 48 | > For more information about Ebean, see the [Ebean documentation](https://ebean-orm.github.io/docs). 49 | 50 | #### Configuring the sbt plugin 51 | 52 | By default, the sbt plugin will attempt to load your `application.conf` file to discover what your models configuration is. This will work in a simple project setup, however, for projects that have multiple sub projects, where the `application.conf` file lives in a different project to where the ebean model classes live, this may not work. In this case you will need to manually specify the ebean models for each sub project that contains ebean models, using the `playEbeanModels` configuration item: 53 | 54 | @[play-ebean-models](code/ebean.sbt) 55 | 56 | In addition to configuring the models, you may wish to enable debug of the configuration. This can be done using `playEbeanDebugLevel`, with -1 being off, and 9 showing the most amount of debug: 57 | 58 | @[play-ebean-debug](code/ebean.sbt) 59 | 60 | You may also configure custom arguments for the ebean agent, this can be done using the `playEbeanAgentArgs` setting: 61 | 62 | @[play-ebean-agent-args](code/ebean.sbt) 63 | 64 | Finally, if you want to also enhance models in your tests, you can do this by configuring the ebean test configuration: 65 | 66 | @[play-ebean-test](code/ebean.sbt) 67 | 68 | ## Using Model superclass 69 | 70 | Ebean defines a convenient superclass for your Ebean model classes, `io.ebean.Model`. Here is a typical Ebean class, mapped in Play: 71 | 72 | @[content](code/javaguide/ebean/Task.java) 73 | 74 | > Play has been designed to generate getter/setter automatically, to ensure compatibility with libraries that expect them to be available at **runtime** (ORM, DataBinder, JSON Binder, etc). **If Play detects any user-written getter/setter in the Model, it will not generate getter/setter in order to avoid any conflict.** 75 | 76 | > **Caveats:** 77 | 78 | > (1) Because Ebean class enhancement occurs *after* compilation, **do not expect Ebean-generated getter/setters to be available at compilation time.** If you'd prefer to code with them directly, either add the getter/setters explicitly yourself, or ensure that your model classes are compiled before the remainder of your project, eg. by putting them in a separate subproject. 79 | 80 | > (2) Enhancement of direct Ebean field access (enabling lazy loading) is only applied to Java classes, not to Scala. Thus, direct field access from Scala source files (including standard Play templates) does not invoke lazy loading, often resulting in empty (unpopulated) entity fields. To ensure the fields get populated, either (a) manually create getter/setters and call them instead, or (b) ensure the entity is fully populated *before* accessing the fields. 81 | 82 | As you can see, we've added a `find` static field, defining a `Finder` for an entity of type `Task` with a `Long` identifier. This helper field is then used to simplify querying our model: 83 | 84 | @[operations](code/javaguide/ebean/JavaEbeanTest.java) 85 | 86 | ## Transactional actions 87 | 88 | By default Ebean will use transactions. However these transactions will be created before and committed or rollbacked after every single query, update, create or delete, as you can see here: 89 | 90 | @[transaction](code/javaguide/ebean/JavaEbeanTest.java) 91 | 92 | So, if you want to do more than one action in the same transaction you can use TxRunnable and TxCallable: 93 | 94 | @[txrunnable](code/javaguide/ebean/JavaEbeanTest.java) 95 | 96 | If your class is an action, you can annotate your action method with `@play.db.ebean.Transactional` to compose your action method with an `Action` that will automatically manage a transaction: 97 | 98 | @[annotation](code/javaguide/ebean/JavaEbeanTest.java) 99 | 100 | Or if you want a more traditional approach you can begin, commit and rollback transactions explicitly: 101 | 102 | @[traditional](code/javaguide/ebean/JavaEbeanTest.java) 103 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Play Ebean 4 | 5 | [![X (formerly Twitter) Follow](https://img.shields.io/twitter/follow/playframework?label=follow&style=flat&logo=x&color=brightgreen)](https://x.com/playframework) 6 | [![Discord](https://img.shields.io/discord/931647755942776882?logo=discord&logoColor=white)](https://discord.gg/g5s2vtZ4Fa) 7 | [![GitHub Discussions](https://img.shields.io/github/discussions/playframework/playframework?&logo=github&color=brightgreen)](https://github.com/playframework/playframework/discussions) 8 | [![StackOverflow](https://img.shields.io/static/v1?label=stackoverflow&logo=stackoverflow&logoColor=fe7a16&color=brightgreen&message=playframework)](https://stackoverflow.com/tags/playframework) 9 | [![YouTube](https://img.shields.io/youtube/channel/views/UCRp6QDm5SDjbIuisUpxV9cg?label=watch&logo=youtube&style=flat&color=brightgreen&logoColor=ff0000)](https://www.youtube.com/channel/UCRp6QDm5SDjbIuisUpxV9cg) 10 | [![Twitch Status](https://img.shields.io/twitch/status/playframework?logo=twitch&logoColor=white&color=brightgreen&label=live%20stream)](https://www.twitch.tv/playframework) 11 | [![OpenCollective](https://img.shields.io/opencollective/all/playframework?label=financial%20contributors&logo=open-collective)](https://opencollective.com/playframework) 12 | 13 | [![Build Status](https://github.com/playframework/play-ebean/actions/workflows/build-test.yml/badge.svg)](https://github.com/playframework/play-ebean/actions/workflows/build-test.yml) 14 | [![Maven](https://img.shields.io/maven-central/v/org.playframework/play-ebean_2.13.svg?logo=apache-maven)](https://mvnrepository.com/artifact/org.playframework/play-ebean_2.13) 15 | [![Repository size](https://img.shields.io/github/repo-size/playframework/play-ebean.svg?logo=git)](https://github.com/playframework/play-ebean) 16 | [![Scala Steward badge](https://img.shields.io/badge/Scala_Steward-helping-blue.svg?style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAMAAAARSr4IAAAAVFBMVEUAAACHjojlOy5NWlrKzcYRKjGFjIbp293YycuLa3pYY2LSqql4f3pCUFTgSjNodYRmcXUsPD/NTTbjRS+2jomhgnzNc223cGvZS0HaSD0XLjbaSjElhIr+AAAAAXRSTlMAQObYZgAAAHlJREFUCNdNyosOwyAIhWHAQS1Vt7a77/3fcxxdmv0xwmckutAR1nkm4ggbyEcg/wWmlGLDAA3oL50xi6fk5ffZ3E2E3QfZDCcCN2YtbEWZt+Drc6u6rlqv7Uk0LdKqqr5rk2UCRXOk0vmQKGfc94nOJyQjouF9H/wCc9gECEYfONoAAAAASUVORK5CYII=)](https://scala-steward.org) 17 | [![Mergify Status](https://img.shields.io/endpoint.svg?url=https://api.mergify.com/v1/badges/playframework/play-ebean&style=flat)](https://mergify.com) 18 | 19 | This module provides Ebean support for Play Framework. 20 | 21 | ## Releases 22 | 23 | The Play Ebean plugin supports several different versions of Play and Ebean. 24 | 25 | | Plugin version | Play version | Ebean version | 26 | |--------------------------------------------------------------------------------------------------------|--------------|----------------| 27 | | 8.5.0 | 3.0.9+ | 17.1.0 | 28 | | 8.4.0 | 3.0.9+ | 15.11.0 | 29 | | 8.3.0 | 3.0.2+ | 15.1.0 | 30 | | 8.2.0 | 3.0.2+ | 15.0.1 | 31 | | 8.1.0 | 3.0.1+ | 13.23.0 | 32 | | 8.0.0 | 3.0.0+ | 13.17.3 | 33 | | 7.5.0 | 2.9.9+ | 17.1.0 | 34 | | 7.4.0 | 2.9.9+ | 15.11.0 | 35 | | 7.3.0 | 2.9.2+ | 15.1.0 | 36 | | 7.2.0 | 2.9.2+ | 15.0.1 | 37 | | 7.1.0 | 2.9.1+ | 13.23.0 | 38 | | 7.0.0 | 2.9.0+ | 13.17.3 | 39 | | 6.2.0
**! [Important notes](https://github.com/playframework/play-ebean/releases/tag/6.2.0-RC4) !** | 2.8.18+ | 12.16.1 | 40 | | 6.0.0 | 2.8.1 | 11.45.1 | 41 | | 5.0.2 | 2.7.0 | 11.39.x | 42 | | 5.0.1    | 2.7.0   | 11.32.x       | 43 | | 5.0.0    | 2.7.0   | 11.22.x       | 44 | | 4.1.4 | 2.6.x | 11.32.x | 45 | | 4.1.3         | 2.6.x       | 11.15.x       | 46 | | 4.1.0         | 2.6.x       | 11.7.x       | 47 | | 4.0.6         | 2.6.x       | 10.4.x       | 48 | | 4.0.2 | 2.6.x | 10.3.x | 49 | | 3.2.0 | 2.5.x | 10.4.x | 50 | | 3.1.0 | 2.5.x | 8.2.x | 51 | | 3.0.2 | 2.5.x | 7.6.x | 52 | | 3.0.1         | 2.5.x       | 6.18.x         | 53 | | 2.0.0         | 2.4.x       | 6.8.x         | 54 | | 1.0.0 | 2.4.x | 4.6.x | 55 | 56 | > * Release Candidate: these releases are not stable and should not be used in production. 57 | 58 | We also recommend using the payintech fork: https://github.com/payintech/play-ebean 59 | 60 | ## Releasing a new version 61 | 62 | See https://github.com/playframework/.github/blob/main/RELEASING.md 63 | -------------------------------------------------------------------------------- /sbt-play-ebean/src/main/scala/play/ebean/sbt/PlayEbean.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.ebean.sbt 6 | 7 | import java.net.URLClassLoader 8 | import io.ebean.enhance.Transformer 9 | import io.ebean.enhance.ant.OfflineFileTransform 10 | import sbt.Keys._ 11 | import sbt.internal.inc.FarmHash 12 | import sbt.internal.inc.LastModified 13 | import sbt.internal.inc.PlainVirtualFileConverter 14 | import sbt.internal.inc.Stamper 15 | import sbt.AutoPlugin 16 | import sbt.Compile 17 | import sbt.Def 18 | import sbt.Task 19 | import sbt.inConfig 20 | import sbt.settingKey 21 | import sbt.taskKey 22 | import xsbti.compile.CompileResult 23 | import xsbti.compile.analysis.Stamp 24 | import sbt._ 25 | import xsbti.VirtualFileRef 26 | import scala.util.control.NonFatal 27 | 28 | object PlayEbean extends AutoPlugin { 29 | 30 | object autoImport { 31 | val playEbeanModels = taskKey[Seq[String]]("The packages that should be searched for ebean models to enhance.") 32 | val playEbeanVersion = 33 | settingKey[String]("The version of Play ebean that should be added to the library dependencies.") 34 | val playEbeanDebugLevel = settingKey[Int]( 35 | "The debug level to use for the ebean agent. The higher, the more debug is output, with 9 being the most. -1 turns debugging off." 36 | ) 37 | val playEbeanAgentArgs = taskKey[Map[String, String]]("The arguments to pass to the agent.") 38 | } 39 | 40 | import autoImport._ 41 | 42 | override def trigger = noTrigger 43 | 44 | override def projectSettings: Seq[Def.Setting[_]] = inConfig(Compile)(scopedSettings) ++ unscopedSettings 45 | 46 | def scopedSettings: Seq[Def.Setting[_]] = 47 | Seq( 48 | playEbeanModels := configuredEbeanModels.value, 49 | manipulateBytecode := ebeanEnhance.value 50 | ) 51 | 52 | def unscopedSettings: Seq[Def.Setting[_]] = 53 | Seq( 54 | playEbeanDebugLevel := -1, 55 | playEbeanAgentArgs := Map("debug" -> playEbeanDebugLevel.value.toString), 56 | playEbeanVersion := readResourceProperty("play-ebean.version.properties", "play-ebean.version"), 57 | libraryDependencies ++= 58 | Seq( 59 | "org.playframework" %% "play-ebean" % playEbeanVersion.value, 60 | "org.glassfish.jaxb" % "jaxb-runtime" % "4.0.6" 61 | ) 62 | ) 63 | 64 | // This is replacement of old Stamp `Exists` representation 65 | private final val notPresent = "absent" 66 | 67 | def ebeanEnhance: Def.Initialize[Task[CompileResult]] = 68 | Def.task { 69 | 70 | val deps = dependencyClasspath.value 71 | val classes = classDirectory.value 72 | val result = manipulateBytecode.value 73 | val agentArgs = playEbeanAgentArgs.value 74 | val analysis = result.analysis.asInstanceOf[sbt.internal.inc.Analysis] 75 | val agentArgsString = agentArgs.map { case (key, value) => s"$key=$value" }.mkString(";") 76 | 77 | val originalContextClassLoader = Thread.currentThread.getContextClassLoader 78 | 79 | try { 80 | val classpath = deps.map(_.data.toURI.toURL).toArray :+ classes.toURI.toURL 81 | val classLoader = new URLClassLoader(classpath, null) 82 | 83 | Thread.currentThread.setContextClassLoader(classLoader) 84 | 85 | val transformer = new Transformer(classLoader, agentArgsString) 86 | val fileTransform = new OfflineFileTransform(transformer, classLoader, classes.getAbsolutePath) 87 | 88 | try { 89 | fileTransform.process(playEbeanModels.value.mkString(",")) 90 | } catch { 91 | case NonFatal(_) => 92 | } 93 | 94 | } finally { 95 | Thread.currentThread.setContextClassLoader(originalContextClassLoader) 96 | } 97 | 98 | val allProducts = analysis.relations.allProducts 99 | val converter = new PlainVirtualFileConverter() 100 | 101 | /** 102 | * Updates stamp of product (class file) by preserving the type of a passed stamp. This way any stamp incremental 103 | * compiler chooses to use to mark class files will be supported. 104 | */ 105 | def updateStampForClassFile(fileRef: VirtualFileRef, stamp: Stamp): Stamp = 106 | stamp match { 107 | case _: LastModified => Stamper.forLastModifiedP(converter.toPath(fileRef)) 108 | case _: FarmHash => Stamper.forFarmHashP(converter.toPath(fileRef)) 109 | } 110 | 111 | // Since we may have modified some of the products of the incremental compiler, that is, the compiled template 112 | // classes and compiled Java sources, we need to update their timestamps in the incremental compiler, otherwise 113 | // the incremental compiler will see that they've changed since it last compiled them, and recompile them. 114 | val updatedAnalysis = analysis.copy(stamps = allProducts.foldLeft(analysis.stamps) { (stamps, classFile) => 115 | val existingStamp = stamps.product(classFile) 116 | if (existingStamp.writeStamp == notPresent) { 117 | throw new java.io.IOException( 118 | "Tried to update a stamp for class file that is not recorded as " 119 | + s"product of incremental compiler: $classFile" 120 | ) 121 | } 122 | 123 | stamps.markProduct(classFile, updateStampForClassFile(classFile, existingStamp)) 124 | }) 125 | 126 | result.withAnalysis(updatedAnalysis) 127 | } 128 | 129 | private def configuredEbeanModels = 130 | Def.task { 131 | import java.util.{ List => JList } 132 | import java.util.{ Map => JMap } 133 | 134 | import collection.JavaConverters._ 135 | 136 | // Creates a classloader with all the dependencies and all the resources, from there we can use the play ebean 137 | // code to load the config as it would be loaded in production 138 | def withClassLoader[T](block: ClassLoader => T): T = { 139 | val classpath = 140 | unmanagedResourceDirectories.value.map(_.toURI.toURL) ++ dependencyClasspath.value.map(_.data.toURI.toURL) 141 | val classLoader = new URLClassLoader(classpath.toArray, null) 142 | try { 143 | block(classLoader) 144 | } catch { 145 | case e: Exception => 146 | // Since we're about to close the classloader, we can't risk any classloading that the thrown exception may 147 | // do when we later interrogate it, so instead we create a new exception here, with the old exceptions message 148 | // and stack trace 149 | def clone(t: Throwable): RuntimeException = { 150 | val cloned = new RuntimeException(s"${t.getClass.getName}: ${t.getMessage}") 151 | cloned.setStackTrace(t.getStackTrace) 152 | if (t.getCause != null) { 153 | cloned.initCause(clone(t.getCause)) 154 | } 155 | cloned 156 | } 157 | 158 | throw clone(e) 159 | } finally { 160 | classLoader.close() 161 | } 162 | } 163 | 164 | withClassLoader { classLoader => 165 | val configLoader = classLoader 166 | .loadClass("play.db.ebean.ModelsConfigLoader") 167 | .asSubclass(classOf[java.util.function.Function[ClassLoader, JMap[String, JList[String]]]]) 168 | val config = configLoader.getDeclaredConstructor().newInstance().apply(classLoader) 169 | 170 | if (config.isEmpty) { 171 | Seq("models.*") 172 | } else { 173 | config.asScala.flatMap(_._2.asScala).toSeq.distinct 174 | } 175 | } 176 | } 177 | 178 | private def readResourceProperty(resource: String, property: String): String = { 179 | val props = new java.util.Properties 180 | val stream = getClass.getClassLoader.getResourceAsStream(resource) 181 | try { 182 | props.load(stream) 183 | } catch { 184 | case _: Exception => 185 | } finally { 186 | if (stream ne null) stream.close() 187 | } 188 | props.getProperty(property) 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /play-ebean/src/main/java/play/db/ebean/DefaultEbeanConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) from 2022 The Play Framework Contributors , 2011-2021 Lightbend Inc. 3 | */ 4 | 5 | package play.db.ebean; 6 | 7 | import com.typesafe.config.Config; 8 | import com.typesafe.config.ConfigException; 9 | import io.ebean.config.DatabaseConfig; 10 | import jakarta.inject.Inject; 11 | import jakarta.inject.Provider; 12 | import jakarta.inject.Singleton; 13 | import java.util.*; 14 | import org.reflections.Reflections; 15 | import org.reflections.scanners.Scanners; 16 | import org.reflections.scanners.TypeElementsScanner; 17 | import org.reflections.util.ClasspathHelper; 18 | import org.reflections.util.ConfigurationBuilder; 19 | import org.reflections.util.FilterBuilder; 20 | import play.Environment; 21 | import play.Logger; 22 | import play.db.DBApi; 23 | 24 | /** Ebean server configuration. */ 25 | @Singleton 26 | public class DefaultEbeanConfig implements EbeanConfig { 27 | 28 | private final String defaultServer; 29 | 30 | private final Map serverConfigs; 31 | 32 | private final boolean generateEvolutionsScripts; 33 | 34 | public DefaultEbeanConfig( 35 | String defaultServer, 36 | Map serverConfigs, 37 | boolean generateEvolutionsScripts) { 38 | this.defaultServer = defaultServer; 39 | this.serverConfigs = serverConfigs; 40 | this.generateEvolutionsScripts = generateEvolutionsScripts; 41 | } 42 | 43 | public DefaultEbeanConfig(String defaultServer, Map serverConfigs) { 44 | this(defaultServer, serverConfigs, true); 45 | } 46 | 47 | @Override 48 | public String defaultServer() { 49 | return defaultServer; 50 | } 51 | 52 | @Override 53 | public Map serverConfigs() { 54 | return serverConfigs; 55 | } 56 | 57 | @Override 58 | public boolean generateEvolutionsScripts() { 59 | return generateEvolutionsScripts; 60 | } 61 | 62 | @Singleton 63 | public static class EbeanConfigParser implements Provider { 64 | 65 | private final Config config; 66 | 67 | private final Environment environment; 68 | 69 | private final DBApi dbApi; 70 | 71 | private static final Logger.ALogger LOGGER = Logger.of(DefaultEbeanConfig.class); 72 | 73 | @Inject 74 | public EbeanConfigParser(Config config, Environment environment, DBApi dbApi) { 75 | this.config = config; 76 | this.environment = environment; 77 | this.dbApi = dbApi; 78 | } 79 | 80 | @Override 81 | public EbeanConfig get() { 82 | return parse(); 83 | } 84 | 85 | /** 86 | * Reads the configuration and creates config for Ebean servers. 87 | * 88 | * @return a config for Ebean servers. 89 | */ 90 | public EbeanConfig parse() { 91 | 92 | EbeanParsedConfig ebeanConfig = EbeanParsedConfig.parseFromConfig(config); 93 | 94 | Map serverConfigs = new HashMap<>(); 95 | 96 | for (Map.Entry> entry : ebeanConfig.getDatasourceModels().entrySet()) { 97 | String key = entry.getKey(); 98 | 99 | if (dbApi.getDatabase(key) == null) { 100 | LOGGER.debug("There is an 'ebean.{}' but no 'db.{}' configuration", key, key); 101 | LOGGER.info("Skipping connection for datasource '{}'", key); 102 | continue; 103 | } 104 | 105 | DatabaseConfig serverConfig = new DatabaseConfig(); 106 | serverConfig.setName(key); 107 | serverConfig.loadFromProperties(); 108 | 109 | setServerConfigDataSource(key, serverConfig); 110 | 111 | if (!ebeanConfig.getDefaultDatasource().equals(key)) { 112 | serverConfig.setDefaultServer(false); 113 | } 114 | 115 | Set classes = getModelClasses(entry); 116 | addModelClassesToServerConfig(key, serverConfig, classes); 117 | 118 | serverConfigs.put(key, serverConfig); 119 | } 120 | 121 | return new DefaultEbeanConfig( 122 | ebeanConfig.getDefaultDatasource(), 123 | serverConfigs, 124 | ebeanConfig.generateEvolutionsScripts()); 125 | } 126 | 127 | private void setServerConfigDataSource(String key, DatabaseConfig serverConfig) { 128 | try { 129 | serverConfig.setDataSource(new WrappingDatasource(dbApi.getDatabase(key).getDataSource())); 130 | } catch (Exception e) { 131 | throw new ConfigException.BadValue("ebean." + key, e.getMessage(), e); 132 | } 133 | } 134 | 135 | private void addModelClassesToServerConfig( 136 | String key, DatabaseConfig serverConfig, Set classes) { 137 | for (String clazz : classes) { 138 | try { 139 | serverConfig.addClass(Class.forName(clazz, true, environment.classLoader())); 140 | } catch (Exception e) { 141 | throw new ConfigException.BadValue( 142 | "ebean." + key, "Cannot register class [" + clazz + "] in Ebean server", e); 143 | } 144 | } 145 | } 146 | 147 | private Set getModelClasses(Map.Entry> entry) { 148 | Set classes = new HashSet<>(); 149 | entry 150 | .getValue() 151 | .forEach( 152 | load -> { 153 | load = load.trim(); 154 | if (load.endsWith(".*")) { 155 | classes.addAll( 156 | Classpath.getTypes(environment, load.substring(0, load.length() - 2))); 157 | } else { 158 | classes.add(load); 159 | } 160 | }); 161 | 162 | return classes; 163 | } 164 | 165 | /** 166 | * DataSource wrapper to ensure that every retrieved connection has auto-commit 167 | * disabled. 168 | */ 169 | static class WrappingDatasource implements javax.sql.DataSource { 170 | 171 | public java.sql.Connection wrap(java.sql.Connection connection) throws java.sql.SQLException { 172 | connection.setAutoCommit(false); 173 | return connection; 174 | } 175 | 176 | // -- 177 | 178 | final javax.sql.DataSource wrapped; 179 | 180 | public WrappingDatasource(javax.sql.DataSource wrapped) { 181 | this.wrapped = wrapped; 182 | } 183 | 184 | public java.sql.Connection getConnection() throws java.sql.SQLException { 185 | return wrap(wrapped.getConnection()); 186 | } 187 | 188 | public java.sql.Connection getConnection(String username, String password) 189 | throws java.sql.SQLException { 190 | return wrap(wrapped.getConnection(username, password)); 191 | } 192 | 193 | public int getLoginTimeout() throws java.sql.SQLException { 194 | return wrapped.getLoginTimeout(); 195 | } 196 | 197 | public java.io.PrintWriter getLogWriter() throws java.sql.SQLException { 198 | return wrapped.getLogWriter(); 199 | } 200 | 201 | public void setLoginTimeout(int seconds) throws java.sql.SQLException { 202 | wrapped.setLoginTimeout(seconds); 203 | } 204 | 205 | public void setLogWriter(java.io.PrintWriter out) throws java.sql.SQLException { 206 | wrapped.setLogWriter(out); 207 | } 208 | 209 | public boolean isWrapperFor(Class iface) throws java.sql.SQLException { 210 | return wrapped.isWrapperFor(iface); 211 | } 212 | 213 | public T unwrap(Class iface) throws java.sql.SQLException { 214 | return wrapped.unwrap(iface); 215 | } 216 | 217 | public java.util.logging.Logger getParentLogger() { 218 | return null; 219 | } 220 | } 221 | } 222 | 223 | /** 224 | * Set of utilities for classpath manipulation. This class should not be used, as it was part of 225 | * the Plugin API system which no longer exists in Play. 226 | */ 227 | private static class Classpath { 228 | 229 | /** 230 | * Scans the environment classloader to retrieve all types within a specific package. 231 | * 232 | *

This method is useful for some plug-ins, for example the EBean plugin will automatically 233 | * detect all types within the models package. 234 | * 235 | *

Note that it is better to specify a very specific package to avoid expensive searches. 236 | * 237 | * @param env the Play environment. 238 | * @param packageName the root package to scan 239 | * @return a set of types names satisfying the condition 240 | */ 241 | static Set getTypes(Environment env, String packageName) { 242 | return getReflections(env, packageName) 243 | .getStore() 244 | .getOrDefault(TypeElementsScanner.class.getSimpleName(), Collections.emptyMap()) 245 | .keySet(); 246 | } 247 | 248 | private static Reflections getReflections(Environment env, String packageName) { 249 | // This is not supposed to happen very often, but just when starting the application. 250 | // So it should be okay to not have a cache. 251 | return new Reflections(getReflectionsConfiguration(packageName, env.classLoader())); 252 | } 253 | 254 | /** 255 | * Create {@link org.reflections.Configuration} object for given package name and class loader. 256 | * 257 | * @param packageName the root package to scan 258 | * @param classLoader class loader to be used in reflections 259 | * @return the configuration builder 260 | */ 261 | private static ConfigurationBuilder getReflectionsConfiguration( 262 | String packageName, ClassLoader classLoader) { 263 | return new ConfigurationBuilder() 264 | .addUrls(ClasspathHelper.forPackage(packageName, classLoader)) 265 | .filterInputsBy(new FilterBuilder().includePackage(packageName)) 266 | .setScanners(new TypeElementsScanner(), Scanners.TypesAnnotated, Scanners.SubTypes); 267 | } 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------