2017-05-03 11 views
-1

내가 자바 1.8를 사용하고, 봄 부팅 및 MongoDB를 내가 최대 절전 모드 - 검증과이를 제어하려고 내가 주석을 통해 클래스 필드의 문자를 제한 할 주석은 java의 클래스 필드 문자를 제한 할 수 있습니까?

MongoDB를

에 대해 배울 데이터베이스에서 일부 데이터를 저장 :

import javax.validation.constraints.Size; 
import org.springframework.data.annotation.Id; 
import org.springframework.data.mongodb.core.mapping.Document; 
import org.springframework.data.mongodb.core.mapping.Field; 

@Document(collection = "MusicGroup") 
public class MusicGroup { 

    @Id 
    private String id; 
    @Size(min = 7, max = 7, message = "title need to have only 4 characters") 
    @Field("Title") 
    private String title; 
    @Size(min = 11, max = 11, message = "type need to have only 11 characters") 
    @Field("Type") 
    private String type; 
    @Field("Members") 
    private List<String> members; 

    public MusicGroup(String titulo, String tipo, List<String> integrantes) { 
     this.title = titulo; 
     this.type = tipo; 
     this.members = integrantes; 
    } 

하지만 난 MongoDB를 오순절에이 코드이를 삽입 할 때 :

@Service 
public class MusicGroupServiceImpl implements MusicGroupService { 

    @Autowired 
    private MusicGroupRepository repository; 

    public MusicGroupServiceImpl() { 

    } 

    @Override 
    public void storeGroup(){ 

     String[] memberList = new String[3]; 
     memberList[0] = "A"; 
     memberList[1] = "B"; 
     memberList[2] = "C"; 

     MusicGroup group = new MusicGroup("Panteraaaaaa", "Heavy Metallllllllllllllll", memberList); 

     repository.save(group); 

    } 

} 

Panteraaaaaa 7 및 중공업 Metallllllllllllllll 같은보다 큰 길이있을 때 아무 문제없이 일을 수행을

나는 는 주석을 통해 자바의 필드의 문자 드 길이를 제어 할 수있는 질문을 실현하기 위해 내 pom.xml 파일

<parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.5.3.RELEASE</version> 
     <relativePath/> 
    </parent> 

    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-mongodb</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-test</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver 
     <dependency> 
      <groupId>org.mongodb</groupId> 
      <artifactId>mongo-java-driver</artifactId> 
      <version>3.4.2</version> 
     </dependency>--> 
     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.12</version> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.hamcrest</groupId> 
      <artifactId>hamcrest-core</artifactId> 
      <version>1.3</version> 
      <scope>test</scope> 
     </dependency> 
     <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> 
     <dependency> 
      <groupId>com.google.code.gson</groupId> 
      <artifactId>gson</artifactId> 
      <version>2.8.0</version> 
      <type>jar</type> 
     </dependency> 
     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> 
     <dependency> 
      <groupId>org.hibernate</groupId> 
      <artifactId>hibernate-validator</artifactId> 
      <version>5.4.1.Final</version> 
     </dependency> 
    </dependencies> 
    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 
</project> 

에 해당하는 다음 코드를 첨부? 또는 이것을 제어하는 ​​방법을 수행해야합니다.

+1

것은 당신이 시도를 할 수있는 경우에 http://stackoverflow.com/questions/22568962/how-to에서 허용 대답 -i-get-spring-data-mongodb-to-validate-my-objects도 사용할 수 있습니까? – dunni

+0

귀하의 의견을 주셔서 감사합니다, acepted 질문은 정확하게 내 문제에 대한 해결책이 아니지만 그것은 나를지도, 내가 몇 분 안에 내가 필드의 크기를 확인 짓을했을거야 – MaQuiNa1995

답변

0

안녕하세요 모두 내가 마지막으로 발견 난 단지 여기에 코드를 새로운 클래스를 수행하는 데 필요한 필드

의 검증 크기에 대한 해결책 :

import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.annotation.Bean; 
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener; 
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 

@SpringBootApplication 
public class Configuration { 

    @Bean 
    public ValidatingMongoEventListener validatingMongoEventListener() { 
     return new ValidatingMongoEventListener(validator()); 
    } 

    @Bean 
    public LocalValidatorFactoryBean validator() { 
     return new LocalValidatorFactoryBean(); 
    } 
} 

다음에 크기 주석의 장소 변경을 세터

@Document(collection = "MusicGroup") 
public class MusicGroup { 

    @Id 
    private String id; 
    @Field("Title") 
    private String title; 
    @Field("Type") 
    private String type; 
    @Field("Members") 
    private String[] members; 

    public MusicGroup() { 
    } 

    @Size(min = 7, max = 7) 
    public String getTitle() { 
     return title; 
    } 

    @Size(min = 11, max = 11) 
    public String getType() { 
     return type; 
    } 

    // Other getters, setters and to String() 

} 

는 치어에 추가 :

<dependency> 
     <groupId>org.glassfish.web</groupId> 
     <artifactId>el-impl</artifactId> 
     <version>2.2</version> 
    </dependency> 
,451,515,

와 나는 새로운 객체 MusicGroup 만들 때 : 프로그램을 실행할 때 이렇게하면

String[] memberList = new String[3]; 
memberList[0] = "typeA"; 
memberList[1] = "typeB"; 
memberList[2] = "typec"; 

MusicGroup grupo = new MusicGroup(); 

grupo.setType("888888888889"); 
grupo.setTitle("hhhhhhh"); 
grupo.setIntegrantes(memberList); 

musicaService.storeGroup(grupo); 

는이 같은 예외 줄 것이다 :

java.lang.IllegalStateException: Failed to execute CommandLineRunner 
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE] 
    at es.cic.cmunoz.MongoDbMascotaApplication.main(MongoDbMascotaApplication.java:32) [classes/:na] 
Caused by: javax.validation.ConstraintViolationException: null 
    at org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener.onBeforeSave(ValidatingMongoEventListener.java:67) ~[spring-data-mongodb-1.10.3.RELEASE.jar:na] 
    ... 

을하지만 당신은 유효한 문자열을 넣을 경우 이 방법

grupo.setType("88888888888"); 

은 늘 당신에게 excepion을 제공

자신의 의견에 대한 dunni-

덕분에,이 솔루션에

PD 나를 안내 : 당신은 당신이 getter 메소드에 @Max (번호) 또는 @min (번호)를 사용할 필요가 INT 같은 숫자 필드의 유효성을 검사하려면

자세한 내용은이 문서를 참조하십시오 : http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-message-interpolation.html#section-resource-bundle-locator

사용자 정의 메시지를 추가 : https://raymondhlee.wordpress.com/2014/07/26/including-field-value-in-validation-message-using-spring-validation-framework-for-jsr-303/

1

개체의 유효성을 검사하지 않습니다. 그냥 제한을 제공합니다. 당신은 당신의 방법을 아래와 같은 객체를 얻고 다시 시도 할 수 있습니까?

storeGroup (@Validated MusicGroup group) { 
.... 
} 

편집 : @Validated 주석과 @Valid 주석을 확인하십시오.

+0

미안 해요, @Validated 태그 doesnt 작품 저, 그것은 유효한 객체가 아닌 데이터베이스에 저장할 수있었습니다. – MaQuiNa1995