Java Code Examples for io.ebean.EbeanServer

The following examples show how to use io.ebean.EbeanServer. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-data-ebean   Source File: NativeEbeanQuery.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link NativeEbeanQuery} encapsulating the query annotated on the given {@link EbeanQueryMethod}.
 *
 * @param method                    must not be {@literal null}.
 * @param ebeanServer               must not be {@literal null}.
 * @param queryString               must not be {@literal null} or empty.
 * @param evaluationContextProvider
 */
public NativeEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
                        QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

    super(method, ebeanServer, queryString, evaluationContextProvider, parser);

    Parameters<?, ?> parameters = method.getParameters();
    boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
    boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable")
            || queryString.contains("#sort");

    if (hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
        throw new InvalidEbeanQueryMethodException(
                "Cannot use native queries with dynamic sorting and/or pagination in method " + method);
    }
}
 
Example 2
/**
 * Creates a {@link QueryLookupStrategy} for the given {@link EbeanServer} and {@link Key}.
 *
 * @param ebeanServer               must not be {@literal null}.
 * @param key                       may be {@literal null}.
 * @param evaluationContextProvider must not be {@literal null}.
 * @return
 */
public static QueryLookupStrategy create(EbeanServer ebeanServer, Key key,
                                         QueryMethodEvaluationContextProvider evaluationContextProvider) {

    Assert.notNull(ebeanServer, "EbeanServer must not be null!");
    Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");

    switch (key != null ? key : Key.CREATE_IF_NOT_FOUND) {
        case CREATE:
            return new CreateQueryLookupStrategy(ebeanServer);
        case USE_DECLARED_QUERY:
            return new DeclaredQueryLookupStrategy(ebeanServer, evaluationContextProvider);
        case CREATE_IF_NOT_FOUND:
            return new CreateIfNotFoundQueryLookupStrategy(ebeanServer, new CreateQueryLookupStrategy(ebeanServer),
                    new DeclaredQueryLookupStrategy(ebeanServer, evaluationContextProvider));
        default:
            throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key));
    }
}
 
Example 3
@Override
protected RepositoryQuery resolveQuery(EbeanQueryMethod method, EbeanServer ebeanServer, NamedQueries namedQueries) {
    RepositoryQuery query = EbeanQueryFactory.INSTANCE.fromQueryAnnotation(method, ebeanServer, evaluationContextProvider);

    if (null != query) {
        return query;
    }

    String name = method.getNamedQueryName();
    if (namedQueries.hasQuery(name)) {
        return EbeanQueryFactory.INSTANCE.fromMethodWithQueryString(method, ebeanServer, namedQueries.getQuery(name),
                evaluationContextProvider);
    }

    query = NamedEbeanQuery.lookupFrom(method, ebeanServer);

    if (null != query) {
        return query;
    }

    throw new IllegalStateException(
            String.format("Did neither find a NamedQuery nor an annotated query for method %s!", method));
}
 
Example 4
Source Project: spring-data-ebean   Source File: NativeEbeanUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link NativeEbeanUpdate} encapsulating the query annotated on the given {@link EbeanQueryMethod}.
 *
 * @param method                    must not be {@literal null}.
 * @param ebeanServer               must not be {@literal null}.
 * @param queryString               must not be {@literal null} or empty.
 * @param evaluationContextProvider
 */
public NativeEbeanUpdate(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
                         QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

    super(method, ebeanServer, queryString, evaluationContextProvider, parser);

    Parameters<?, ?> parameters = method.getParameters();
    boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
    boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable")
            || queryString.contains("#sort");

    if (hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
        throw new InvalidEbeanQueryMethodException(
                "Cannot use native queries with dynamic sorting and/or pagination in method " + method);
    }
}
 
Example 5
/**
 * Return a ExampleExpression from Spring data Example
 *
 * @param ebeanServer
 * @param example
 * @param <T>
 * @return
 */
public static <T> ExampleExpression exampleExpression(EbeanServer ebeanServer, Example<T> example) {
    LikeType likeType;
    switch (example.getMatcher().getDefaultStringMatcher()) {
        case EXACT:
            likeType = LikeType.EQUAL_TO;
            break;
        case CONTAINING:
            likeType = LikeType.CONTAINS;
            break;
        case STARTING:
            likeType = LikeType.STARTS_WITH;
            break;
        case ENDING:
            likeType = LikeType.ENDS_WITH;
            break;
        default:
            likeType = LikeType.RAW;
            break;
    }
    return ebeanServer.getExpressionFactory().exampleLike(example.getProbe(),
            example.getMatcher().isIgnoreCaseEnabled(),
            likeType);
}
 
Example 6
Source Project: example-springboot   Source File: EbeanFactoryBean.java    License: Apache License 2.0 6 votes vote down vote up
@Override
  public EbeanServer getObject() throws Exception {

    ServerConfig config = new ServerConfig();
    config.setName("db");
    config.setCurrentUserProvider(currentUser);

//    // set the spring's datasource and transaction manager.
//    config.setDataSource(dataSource);
//    config.setExternalTransactionManager(new SpringAwareJdbcTransactionManager());

    config.loadFromProperties();
    config.loadTestProperties();

    return EbeanServerFactory.create(config);
  }
 
Example 7
Source Project: kyoko   Source File: MainModule.java    License: MIT License 5 votes vote down vote up
@Singleton
@Provides
EbeanServer ebeanServer(EbeanClassRegistry registry, ModuleManager moduleManager) {
    var settings = Settings.instance();
    var config = new ServerConfig();
    config.setName("pg");

    var dataSource = new DataSourceConfig()
            .setDriver(settings.jdbcDriverClass())
            .setUrl(settings.databaseUrl())
            .setUsername(settings.jdbcUser())
            .setPassword(settings.jdbcPassword());

    config.setDataSourceConfig(dataSource);
    config.setDefaultServer(true);
    config.setDdlCreateOnly(true);

    registry.get().forEach(className -> {
        try {
            config.addClass(moduleManager.findClass(className.replace("/", ".")).asSubclass(DatabaseEntity.class));
        } catch (Exception e) {
            logger.error("Error registering database entity class: {}", className, e);
        }
    });

    return EbeanServerFactory.create(config);
}
 
Example 8
/**
 * Creates a new {@link AbstractStringBasedEbeanQuery} from the given {@link EbeanQueryMethod}, {@link io.ebean.EbeanServer} and
 * query {@link String}.
 *
 * @param method                    must not be {@literal null}.
 * @param ebeanServer               must not be {@literal null}.
 * @param queryString               must not be {@literal null}.
 * @param evaluationContextProvider must not be {@literal null}.
 * @param parser                    must not be {@literal null}.
 */
public AbstractStringBasedEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
                                     QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

    super(method, ebeanServer);

    Assert.hasText(queryString, "EbeanQueryWrapper string must not be null or empty!");
    Assert.notNull(evaluationContextProvider, "ExpressionEvaluationContextProvider must not be null!");
    Assert.notNull(parser, "Parser must not be null or empty!");

    this.evaluationContextProvider = evaluationContextProvider;
    this.query = new ExpressionBasedStringQuery(queryString, method.getEntityInformation(), parser);
    this.parser = parser;
}
 
Example 9
/**
 * Creates an appropriate Ebean query from an {@link EbeanServer} according to the current {@link AbstractEbeanQuery}
 * type.
 *
 * @param queryString
 * @return
 */
protected EbeanQueryWrapper createEbeanQuery(String queryString) {
    EbeanServer ebeanServer = getEbeanServer();

    ResultProcessor resultFactory = getQueryMethod().getResultProcessor();
    ReturnedType returnedType = resultFactory.getReturnedType();

    return EbeanQueryWrapper.ofEbeanQuery(ebeanServer.createQuery(returnedType.getReturnedType(), queryString));
}
 
Example 10
Source Project: spring-data-ebean   Source File: PartTreeEbeanQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link PartTreeEbeanQuery}.
 *
 * @param method      must not be {@literal null}.
 * @param ebeanServer must not be {@literal null}.
 */
public PartTreeEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer) {
    super(method, ebeanServer);

    this.domainClass = method.getEntityInformation().getJavaType();
    this.tree = new PartTree(method.getName(), domainClass);
    this.parameters = (DefaultParameters) method.getParameters();
    this.queryPreparer = new QueryPreparer(ebeanServer);
}
 
Example 11
Source Project: spring-data-ebean   Source File: PartTreeEbeanQuery.java    License: Apache License 2.0 5 votes vote down vote up
protected EbeanQueryCreator createCreator(ParametersParameterAccessor accessor) {
    EbeanServer ebeanServer = getEbeanServer();
    Query ebeanQuery = ebeanServer.createQuery(domainClass);
    ExpressionList expressionList = ebeanQuery.where();

    ParameterMetadataProvider provider = new ParameterMetadataProvider(accessor);

    ResultProcessor processor = getQueryMethod().getResultProcessor();

    return new EbeanQueryCreator(tree, processor.getReturnedType(), expressionList, provider);
}
 
Example 12
Source Project: spring-data-ebean   Source File: AbstractEbeanQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link AbstractEbeanQuery} from the given {@link EbeanQueryMethod}.
 *
 * @param method
 * @param ebeanServer
 */
public AbstractEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer) {

    Assert.notNull(method, "EbeanQueryMethod must not be null!");
    Assert.notNull(ebeanServer, "EbeanServer must not be null!");

    this.method = method;
    this.ebeanServer = ebeanServer;
}
 
Example 13
Source Project: spring-data-ebean   Source File: NamedEbeanQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link NamedEbeanQuery}.
 */
private NamedEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer, Query query) {
    super(method, ebeanServer);

    this.queryName = method.getNamedQueryName();
    this.query = query;
}
 
Example 14
Source Project: spring-data-ebean   Source File: NamedEbeanQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Looks up a named query for the given {@link org.springframework.data.repository.query.QueryMethod}.
 *
 * @param method
 * @return
 */
public static RepositoryQuery lookupFrom(EbeanQueryMethod method, EbeanServer ebeanServer) {
    final String queryName = method.getNamedQueryName();

    LOG.debug("Looking up named query {}", queryName);

    try {
        Query query = ebeanServer.createNamedQuery(method.getEntityInformation().getJavaType(), queryName);
        return new NamedEbeanQuery(method, ebeanServer, query);
    } catch (PersistenceException e) {
        LOG.debug("Did not find named query {}", queryName);
        return null;
    }
}
 
Example 15
@Override
protected RepositoryQuery resolveQuery(EbeanQueryMethod method, EbeanServer ebeanServer, NamedQueries namedQueries) {

    try {
        return new PartTreeEbeanQuery(method, ebeanServer);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(
                String.format("Could not create query metamodel for method %s!", method.toString()), e);
    }
}
 
Example 16
/**
 * Creates a new {@link CreateIfNotFoundQueryLookupStrategy}.
 *
 * @param ebeanServer
 * @param createStrategy
 * @param lookupStrategy
 */
public CreateIfNotFoundQueryLookupStrategy(EbeanServer ebeanServer,
                                           CreateQueryLookupStrategy createStrategy, DeclaredQueryLookupStrategy lookupStrategy) {
    super(ebeanServer);

    this.createStrategy = createStrategy;
    this.lookupStrategy = lookupStrategy;
}
 
Example 17
@Override
protected RepositoryQuery resolveQuery(EbeanQueryMethod method, EbeanServer ebeanServer, NamedQueries namedQueries) {
    try {
        return lookupStrategy.resolveQuery(method, ebeanServer, namedQueries);
    } catch (IllegalStateException e) {
        return createStrategy.resolveQuery(method, ebeanServer, namedQueries);
    }
}
 
Example 18
Source Project: spring-data-ebean   Source File: EbeanEntityInformation.java    License: Apache License 2.0 5 votes vote down vote up
public EbeanEntityInformation(EbeanServer ebeanServer, Class<T> domainClass) {
    this.ebeanServer = ebeanServer;
    this.domainClass = domainClass;

    Class<?> idClass = ResolvableType.forClass(domainClass).resolveGeneric(0);

    if (idClass == null) {
        throw new IllegalArgumentException(String.format("Could not resolve identifier type for %s!", domainClass));
    }

    this.idClass = (Class<ID>) idClass;
}
 
Example 19
Source Project: play-ebean   Source File: EbeanDynamicEvolutions.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that generates the required evolution to properly run Ebean.
 *
 * @param server the EbeanServer.
 * @return the complete migration generated by Ebean
 */
public static String generateEvolutionScript(EbeanServer server) {
    try {
        SpiEbeanServer spiServer = (SpiEbeanServer) server;
        CurrentModel ddl = new CurrentModel(spiServer);

        String ups = ddl.getCreateDdl();
        String downs = ddl.getDropAllDdl();

        if (ups == null || ups.trim().isEmpty()) {
            return null;
        }

        return
            "# --- Created by Ebean DDL\r\n" +
            "# To stop Ebean DDL generation, remove this comment and start using Evolutions\r\n" +
            "\r\n" +
            "# --- !Ups\r\n" +
            "\r\n" +
            ups +
            "\r\n" +
            "# --- !Downs\r\n" +
            "\r\n" +
            downs;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 20
Source Project: tutorials   Source File: App2.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    ServerConfig cfg = new ServerConfig();
    cfg.setDefaultServer(true);
    Properties properties = new Properties();
    properties.put("ebean.db.ddl.generate", "true");
    properties.put("ebean.db.ddl.run", "true");
    properties.put("datasource.db.username", "sa");
    properties.put("datasource.db.password", "");
    properties.put("datasource.db.databaseUrl", "jdbc:h2:mem:app2");
    properties.put("datasource.db.databaseDriver", "org.h2.Driver");
    cfg.loadFromProperties(properties);
    EbeanServer server = EbeanServerFactory.create(cfg);

}
 
Example 21
Source Project: tutorials   Source File: App.java    License: MIT License 5 votes vote down vote up
@Transactional
public static void insertAndDeleteInsideTransaction() {

    Customer c1 = getCustomer();
    EbeanServer server = Ebean.getDefaultServer();
    server.save(c1);
    Customer foundC1 = server.find(Customer.class, c1.getId());
    server.delete(foundC1);
}
 
Example 22
Source Project: canal   Source File: Model.java    License: Apache License 2.0 5 votes vote down vote up
public void saveOrUpdate() {
    try {
        EbeanServer ebeanServer = Ebean.getDefaultServer();
        Object id = ebeanServer.getBeanId(this);
        if (id == null) {
            init();
            this.save();
        } else {
            this.update();
        }
    } catch (Exception e) {
        throw new OptimisticLockException(e);
    }
}
 
Example 23
Source Project: canal   Source File: EbeanConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean("ebeanServer")
public EbeanServer ebeanServer(DataSource dataSource) {
    ServerConfig serverConfig = new ServerConfig();
    serverConfig.setDefaultServer(true);
    serverConfig.setNamingConvention(new UnderscoreNamingConvention());
    List<String> packages = new ArrayList<>();
    packages.add("com.alibaba.otter.canal.admin.model");
    serverConfig.setPackages(packages);
    serverConfig.setName("ebeanServer");
    serverConfig.setDataSource(dataSource);
    serverConfig.setDatabaseSequenceBatchSize(1);
    serverConfig.setDdlGenerate(false);
    serverConfig.setDdlRun(false);
    return EbeanServerFactory.create(serverConfig);
}
 
Example 24
Source Project: spring-data-ebean   Source File: PartTreeEbeanQuery.java    License: Apache License 2.0 4 votes vote down vote up
public QueryPreparer(EbeanServer ebeanServer) {
    this.ebeanServer = ebeanServer;
}
 
Example 25
public DeleteExecution(EbeanServer ebeanServer) {
    this.ebeanServer = ebeanServer;
}
 
Example 26
Source Project: spring-data-ebean   Source File: SampleConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public QueryChannelService ebeanQueryChannelService(EbeanServer ebeanServer) {
  return new EbeanQueryChannelService(ebeanServer);
}
 
Example 27
Source Project: spring-data-ebean   Source File: SampleConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@Primary
public EbeanServer defaultEbeanServer(ServerConfig defaultEbeanServerConfig) {
  return EbeanServerFactory.create(defaultEbeanServerConfig);
}
 
Example 28
Source Project: example-springboot   Source File: EbeanFactoryBean.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getObjectType() {
  return EbeanServer.class;
}
 
Example 29
Source Project: example-springboot   Source File: BeanFinder.java    License: Apache License 2.0 4 votes vote down vote up
public BeanFinder(Class<T> type, EbeanServer server) {
	super(type);
	this.server = server;
}
 
Example 30
Source Project: example-springboot   Source File: BeanFinder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public EbeanServer db() {
	return server;
}