Spring Boot ConfigurationProperties validate

使用@Query
可以在自定义的查询方法上使用@Query来指定该方法要执行的查询语句,比如:
@Query("select o from UserModel o where o.uuid=?1")
public List<UserModel> findByUuidOrAge(int uuid);
注意:
1:方法的参数个数必须和@Query里面需要的参数个数一致
2:如果是like,后面的参数需要前面或者后面加“%”,比如下面都对:
@Query("select o from UserModel o where o.name like ?1%")
public List<UserModel> findByUuidOrAge(String name);

@Query("select o from UserModel o where o.name like %?1")
public List<UserModel> findByUuidOrAge(String name);

@Query("select o from UserModel o where o.name like %?1%")
public List<UserModel> findByUuidOrAge(String name);

当然,这样在传递参数值的时候就可以不加‘%’了,当然加了也不会错

n还可以使用@Query来指定本地查询,只要设置nativeQuery为true,比如:
@Query(value="select * from tbl_user where name like %?1" ,nativeQuery=true)
public List<UserModel> findByUuidOrAge(String name);
注意:当前版本的本地查询不支持翻页和动态的排序

使用命名化参数,使用@Param即可,比如:
@Query(value="select o from UserModel o where o.name like %:nn")
public List<UserModel> findByUuidOrAge(@Param("nn") String name);

同样支持更新类的Query语句,添加@Modifying即可,比如:
@Modifying
@Query(value="update UserModel o set o.name=:newName where o.name like %:nn")
public int findByUuidOrAge(@Param("nn") String name,@Param("newName") String newName);
注意:
1:方法的返回值应该是int,表示更新语句所影响的行数
2:在调用的地方必须加事务,没有事务不能正常执行

http://si防违禁shuok防违禁.com/forum/blogPost/list/7000.html

 

Identity of entities is defined by their primary keys. Since firstname and lastname are not parts of the primary key, you cannot tell JPA to treat Users with the same firstnames and lastnames as equal if they have different userIds.

So, if you want to update a User identified by its firstname and lastname, you need to find that User by a query, and then change appropriate fields of the object your found. These changes will be flushed to the database automatically at the end of transaction, so that you don't need to do anything to save these changes explicitly.

EDIT:

Perhaps I should elaborate on overall semantics of JPA. There are two main approaches to design of persistence APIs:

  • insert/update approach. When you need to modify the database you should call methods of persistence API explicitly: you call insert to insert an object, or update to save new state of the object to the database.
  • Unit of Work approach. In this case you have a set of objects managed by persistence library. All changes you make to these objects will be flushed to the database automatically at the end of Unit of Work (i.e. at the end of the current transaction in typical case). When you need to insert new record to the database, you make the corresponding object managedManaged objects are identified by their primary keys, so that if you make an object with predefined primary key managed, it will be associated with the database record of the same id, and state of this object will be propagated to that record automatically.

JPA follows the later approach. save() in Spring Data JPA is backed by merge() in plain JPA, therefore it makes your entity managed as described above. It means that calling save() on an object with predefined id will update the corresponding database record rather than insert a new one, and also explains why save() is not called create().

http://stackoverflow.com/questions/11881479/how-do-i-update-an-entity-using-spring-data-jpa?rq=1

I think this is not possible with Spring Data JPA according to the docs. You have to look at plain JDBC, there are a few methods regarding batch insert/updates . There is also a nice ebook covering this topic.

http://stackoverflow.com/questions/33462221/how-to-implement-batch-update-using-spring-data-jpa

 

The implementation of the method

<S extends T> S save(S entity)

from interface

CrudRepository<T, ID extends Serializable> extends Repository<T, ID>

automatically does what you want. If the entity is new it will call persist on the entity manager, otherwise it will call merge

The code looks like this:

public <S extends T> S save(S entity) {
    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

and can be found here. Note that SimpleJpaRepository is the class that automatically implements CrudRepository in Spring Data JPA.

Therefore, there is no need to supply a custom saveOrUpdate() method. Spring Data JPA has you covered.

http://stackoverflow.com/questions/24420572/update-or-saveorupdate-in-crudrespository-is-there-any-options-available

29.3.3 Creating and dropping JPA databases

By default, JPA databases will be automatically created only if you use an embedded database (H2, HSQL or Derby). You can explicitly configure JPA settings usingspring.jpa.* properties. For example, to create and drop tables you can add the following to your application.properties.

spring.jpa.hibernate.ddl-auto=create-drop

Hibernate’s own internal property name for this (if you happen to remember it better) is hibernate.hbm2ddl.auto. You can set it, along with other Hibernate native properties, using spring.jpa.properties.* (the prefix is stripped before adding them to the entity manager). Example:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

passes hibernate.globally_quoted_identifiers to the Hibernate entity manager.

By default the DDL execution (or validation) is deferred until the ApplicationContext has started. There is also a spring.jpa.generate-ddl flag, but it is not used if Hibernate autoconfig is active because the ddl-auto settings are more fine-grained.

29.3.4 Open EntityManager in View

If you are running a web application, Spring Boot will by default register OpenEntityManagerInViewInterceptor to apply the "Open EntityManager in View" pattern, i.e. to allow for lazy loading in web views. If you don’t want this behavior you should set spring.jpa.open-in-view to false in your application.properties.

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-creating-and-dropping-jpa-databases

org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation

    @Override
    public boolean isNew(T entity) {

        if (versionAttribute == null || versionAttribute.getJavaType().isPrimitive()) {
            return super.isNew(entity);
        }

        BeanWrapper wrapper = new DirectFieldAccessFallbackBeanWrapper(entity);
        Object versionValue = wrapper.getPropertyValue(versionAttribute.getName());

        return versionValue == null;
    }

org.springframework.data.repository.core.support.AbstractEntityInformation

    /*
     * (non-Javadoc)
     * @see org.springframework.data.repository.core.EntityInformation#isNew(java.lang.Object)
     */
    public boolean isNew(T entity) {

        ID id = getId(entity);
        Class<ID> idType = getIdType();

        if (!idType.isPrimitive()) {  //如果不是基本类型
            return id == null;
        }

        if (id instanceof Number) {
            return ((Number) id).longValue() == 0L;
        }

        throw new IllegalArgumentException(String.format("Unsupported primitive id type %s!", idType));
    }

 

    /*
     * (non-Javadoc)
     * @see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object)
     */
    @SuppressWarnings("unchecked")
    public ID getId(T entity) {

        BeanWrapper entityWrapper = new DirectFieldAccessFallbackBeanWrapper(entity);

        if (idMetadata.hasSimpleId()) {
            return (ID) entityWrapper.getPropertyValue(idMetadata.getSimpleIdAttribute().getName());
        }

        BeanWrapper idWrapper = new IdentifierDerivingDirectFieldAccessFallbackBeanWrapper(idMetadata.getType(), metamodel);
        boolean partialIdValueFound = false;

        for (SingularAttribute<? super T, ?> attribute : idMetadata) {
            Object propertyValue = entityWrapper.getPropertyValue(attribute.getName());

            if (propertyValue != null) {
                partialIdValueFound = true;
            }

            idWrapper.setPropertyValue(attribute.getName(), propertyValue);
        }

        return (ID) (partialIdValueFound ? idWrapper.getWrappedInstance() : null);
    }
    /*
     * (non-Javadoc)
     * @see org.springframework.data.repository.core.EntityInformation#getIdType()
     */
    @SuppressWarnings("unchecked")
    public Class<ID> getIdType() {
        return (Class<ID>) idMetadata.getType();
    }

 

 

 

 

5.7. Transactionality

CRUD methods on repository instances are transactional by default.

http://docs.spring.io/spring-data/jpa/docs/1.11.0.RELEASE/reference/html/

 

 

 

33. Calling REST services
If you need to call remote REST services from your application, you can use Spring Framework’s RestTemplate class. Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed. The auto-configured RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied to RestTemplate instances.

Here’s a typical example:

@Service
public class MyBean {

    private final RestTemplate restTemplate;

    public MyBean(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public Details someRestCall(String name) {
        return this.restTemplate.getForObject("/{name}/details", Details.class, name);
    }

}

RestTemplateBuilder includes a number of useful methods that can be used to quickly configure a RestTemplate.
For example, to add BASIC auth support you can use builder.basicAuthorization("user", "password").build().

33.1 RestTemplate customization
There are three main approaches to RestTemplate customization, depending on how broadly you want the customizations to apply.

To make the scope of any customizations as narrow as possible, inject the auto-configured RestTemplateBuilder and then call its methods as required. Each method call returns a new RestTemplateBuilder instance so the customizations will only affect this use of the builder.

To make an application-wide, additive customization a RestTemplateCustomizer bean can be used. All such beans are automatically registered with the auto-configured RestTemplateBuilder and will be applied to any templates that are built with it.

Here’s an example of a customizer that configures the use of a proxy for all hosts except 192.168.0.5:

static class ProxyCustomizer implements RestTemplateCustomizer {

    @Override
    public void customize(RestTemplate restTemplate) {
        HttpHost proxy = new HttpHost("proxy.example.com");
        HttpClient httpClient = HttpClientBuilder.create()
                .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {

                    @Override
                    public HttpHost determineProxy(HttpHost target,
                            HttpRequest request, HttpContext context)
                                    throws HttpException {
                        if (target.getHostName().equals("192.168.0.5")) {
                            return null;
                        }
                        return super.determineProxy(target, request, context);
                    }

                }).build();
        restTemplate.setRequestFactory(
                new HttpComponentsClientHttpRequestFactory(httpClient));
    }

}

Lastly, the most extreme (and rarely used) option is to create your own RestTemplateBuilder bean.
This will switch off the auto-configuration of a RestTemplateBuilder and will prevent any RestTemplateCustomizer beans from being used.

 

 

 

29.4 Using H2’s web console
The H2 database provides a browser-based console that Spring Boot can auto-configure for you. The console will be auto-configured when the following conditions are met:

You are developing a web application
com.h2database:h2 is on the classpath
You are using Spring Boot’s developer tools
[Tip]
If you are not using Spring Boot’s developer tools, but would still like to make use of H2’s console, then you can do so by configuring the spring.h2.console.enabled property with a value of true. 
The H2 console is only intended for use during development so care should be taken to ensure that spring.h2.console.enabled is not set to true in production.
29.4.1 Changing the H2 console’s path

By default the console will be available at /h2-console. You can customize the console’s path using the spring.h2.console.path property.

29.4.2 Securing the H2 console

When Spring Security is on the classpath and basic auth is enabled, the H2 console will be automatically secured using basic auth. The following properties can be used to customize the security configuration:

security.user.role
security.basic.authorize-mode
security.basic.enabled

 

 

You should at least specify the url using the spring.datasource.url property or Spring Boot will attempt to auto-configure an embedded database.
[Tip]
You often won’t need to specify the driver-class-name since Spring boot can deduce it for most databases from the url.
[Note]
For a pooling DataSource to be created we need to be able to verify that a valid Driver class is available, so we check for that before doing anything. I.e. if you set spring.datasource.driver-class-name=com.mysql.jdbc.Driver then that class has to be loadable.

 

28.3.2 Single Sign On

An OAuth2 Client can be used to fetch user details from the provider (if such features are available) and then convert them into an Authentication token for Spring Security. 
The Resource Server above support this via the user-info-uri property This is the basis for a Single Sign On (SSO) protocol based on OAuth2, 
and Spring Boot makes it easy to participate by providing an annotation @EnableOAuth2Sso. 
The Github client above can protect all its resources and authenticate using the Github /user/ endpoint, 
by adding that annotation and declaring where to find the endpoint (in addition to the security.oauth2.client.* configuration already listed above):

 

 

If Spring Security is on the classpath then web applications will be secure by default with ‘basic’ authentication on all HTTP endpoints.
To add method-level security to a web application you can also add @EnableGlobalMethodSecurity with your desired settings.

 

If you fine-tune your logging configuration, ensure that the org.springframework.boot.autoconfigure.security category is set to log INFO messages, otherwise the default password will not be printed.

 

You can change the password by providing a security.user.password. This and other useful properties are externalized via SecurityProperties (properties prefix "security").

org.springframework.boot.autoconfigure.security.SecurityProperties.User

 

 

27.1.5 Static Content

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. 
It uses the ResourceHttpRequestHandler from Spring MVC so you can modify that behavior by adding your own WebMvcConfigurerAdapter and overriding the addResourceHandlers method.

 You can customize the static resource locations using spring.resources.staticLocations (replacing the default values with a list of directory locations). If you do this the default welcome page detection will switch to your custom locations, so if there is an index.html in any of your locations on startup, it will be the home page of the application.

 

In addition to the ‘standard’ static resource locations above, a special case is made for Webjars content. 
Any resources with a path in /webjars/** will be served from jar files if they are packaged in the Webjars format.

 

 

24.7.4 @ConfigurationProperties Validation

Spring Boot will attempt to validate external configuration, by default using JSR-303 (if it is on the classpath).
You can simply add JSR-303 javax.validationconstraint annotations to your @ConfigurationProperties class:

@ConfigurationProperties(prefix="foo")
public class FooProperties {

    @NotNull
    private InetAddress remoteAddress;

    // ... getters and setters

}

 

In order to validate values of nested properties, you must annotate the associated field as @Valid to trigger its validation. For example, building upon the aboveFooProperties example:

@ConfigurationProperties(prefix="connection")
public class FooProperties {

    @NotNull
    private InetAddress remoteAddress;

    @Valid
    private final Security security = new Security();

    // ... getters and setters

    public static class Security {

        @NotEmpty
        public String username;

        // ... getters and setters

    }

}

You can also add a custom Spring Validator by creating a bean definition called configurationPropertiesValidator. The @Bean method should be declared static. The configuration properties validator is created very early in the application’s lifecycle and declaring the @Bean method as static allows the bean to be created without having to instantiate the @Configuration class. This avoids any problems that may be caused by early instantiation. There is a property validation sample so you can see how to set things up.

 

时间: 2024-11-01 19:42:16

Spring Boot ConfigurationProperties validate的相关文章

【spring Boot】spring boot1.5以上版本@ConfigurationProperties取消location注解后的替代方案

前言 =========================================== 初步接触Spring Boot =========================================== 资源文件中自定义属性值,配置在一个对象bean上,然后在程序中可以使用bean的属性值.  一.     二. @Component标志本类为一个bean @PropertySource(value = "classpath:/application.properties")

57. Spring 自定义properties升级篇【从零开始学Spring Boot】

 注解ConfigurationProperties和EnableAutoConfiguration的区别: @EnableConfigurationProperties tells Spring to treat this class as a consumer of application.yml/properties values( {@link ConfigurationProperties} beans can be registered in the standard way (fo

spring boot 2.0特性之外部化配置

简介 spring boot允许你外部化其配置以便你能够在不同的环境中使用相同的代码.可以通过使用properties,YAML 文件,环境变量,以及命名行参数等形式外部化其配置.属性值可以通过@value的形式直接注入到bean中去(其通过spring 的抽象或者是通过使用@ConfigurationProperties绑定其结构化对象) spring boot使用了一种特别的 PropertySource允许你覆盖其值,其覆盖顺序如下: 1. devtools的环境变量被设置,则优先使用(其

springboot(十一):Spring boot中mongodb的使用

mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置漏洞被攻击,数据被删,引起了人们的注意,感兴趣的可以看看这篇文章:场屠戮MongoDB的盛宴反思:超33000个数据库遭遇入侵勒索,同时也说明了很多公司生产中大量使用mongodb. mongodb简介 MongoDB(来自于英文单词"Humongous",中文含义为"庞大&qu

Spring Boot Dubbo applications.properties 配置清单

摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 与其纠结,不如行动学习.Innovate ,And out execute ! 』 本文提纲 一.前言 二.applications.properties 配置清单 三.@Service 服务提供者常用配置 四.@Reference 服务消费者常用配置 五.小结   运行环境:JDK 7 或 8.Maven 3.0+ 技术栈:SpringBoot 1.5+..Dubbo 2.5+ 一.

深入学习微框架:Spring Boot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以 及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. 多年以来,Spring IO平台饱受非议的一点就是大量的XML配置以及复杂的依赖管理.在去年的SpringOne 2GX会议上,Pivotal的CTO Adrian Co

Spring Boot MyBatis 通用Mapper插件集成

看本文之前,请确保你已经在SpringBoot中集成MyBatis,并能正常使用. 如果没有,那么请先移步 http://blog.csdn.net/catoop/article/details/50553714 做了解后,再按本文步骤操作. 使用MyBatis在我们通过xml集中配置SQL,并通过创建接口Mapper文件来完成持久化DAO层(mybatis内部使用的是动态代理,所以我们不需要自己编写实现类). 然而在实际开发中,单表操作非常多,如果你也想像JPA.JDBC那样做一个所谓的Bas

一篇文章学会spring boot(包括jms和hessian的集成)

之前在学习spring cloud微服务的时候,由于spring cloud的基础是spring boot,因此曾简单地了解过spring boot,但也只是简单的了解过而已. 而现在,需要把struts2项目改为spring boot,一开始时以为是整个项目重构,不仅限于struts2部分,因此就相对更系统.更细致的学了一下spring boot. 整个过程由易到难,大概分成了这么些模块: 一.创建简单的spring boot web项目 很多时候学一个新的东西,都需要从最简单的地方开始,然后

Spring Boot使用Druid和监控配置

完美与Spring Boot集成. 1.编写Spring Boot Druid配置类 DruidDataSourceProperties.java package org.paascloud.ops.config; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.Properties; /** * Created by meyer on 2017/1/15.