이 기사에서는 Maven 프로젝트 용 Spring Boot+Spring MVC+JPA를 구축하는 예를 소개합니다. 그것은 당신과 공유됩니다. 세부 사항은 다음과 같습니다.
스프링 부팅 지원을 추가하고 관련 패키지를 소개합니다.
1. Maven 프로젝트는 POM.XML에 필수 불가결합니다. Spring Boot의 도입은 공식 웹 사이트를 참조하십시오.
<부모> <groupid> org.springframework.boot </groupid> <artifactid> Spring-Boot-Starter-Parent </artifactid> <bersion> 1.5.9. release> </parent> <pecientency> <groupid> javax.servlet </groupid> <artifactid> javax.servlet-pipi </scope> <!-원치 않는 JAR 패키지를 컴파일하고 게시하고 게시합니다-> </depectency> <pectionement> <groupId> org.springframework </groupId> <artifactid> spring-webmvc </arevmvc </fexendency> <groupid> <groupId> org.springframework.boot> <Artifactid> Spring-Boot-starter-web </artifactid> </fectionency> <!-JPA JAR 패키지, 데이터베이스 작동-> <pectionency> <groupId> org.springframework.boot </groupId> <artifactid> 스프링-부트-스테이터 data-jpa </arepifactid> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-data-redis </artifactid> </eptinemency> <!-mysql driver-> <pectionency> <groupid> mysql </groupid> <artifactid> mysql-connector-java </expendency> <groupid> org.apache.shiro </groupid> <artifactid> Shiro-core </artifactid> <2.2.2 </version> </fectionency> <groupidency> <groupid> org.apache.shiro </groupid> <atifactid> shiro-spring </artifactid> 1.2 <20 <! -> <pectionency> <groupId> org.apache.shiro </groupId> <artifactid> Shiro-ehcache </artifactid> <버전> 1.2.2 </version> </fectionency> </fexendies> <플러그인> <groupid> org.springframework.boot </groupId> spring-hoot-mopactin> <executions> <execution> <goving> <goved> Repackage </goal> </gover> </execution> </executions> </plugin> </plugins> <FinalName> 이름 </finalName> </build>
2. 위의 코드는 스프링 부팅을 소개합니다. MySQL 데이터베이스 용 드라이버 JAR뿐만 아니라 Spring MVC 및 JPA;
시작 클래스를 작성하고 구성 파일을 설치하십시오.
1. 시작 클래스는 다음과 같습니다.
import org.springframework.boot.springApplication; import org.springframework.boot.autoconfigure.enableautoconfiguration; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.data.jpa.repo.config.endation java.io.ioexception; import com.my.config.commonProperties;@springbootApplication@enableautoconfiguration@enablejpaauditingpublic class application {public static void main (string [] args)은 ioexception {String loc = CommonProperties.loadProperties2System (System.GetProperty ( "spring.config.location")); system.getProperties (). setProperty ( "application.version", commonProperties.getVersion (application.class)); system.getProperties (). setProperty ( "app.home", loc + "/.."); SpringApplication.run (application.class, args); }}2. 구성 파일을 클래스 경로 외부에 배치하여 다시 포장되지 않고 수정을 용이하게합니다. Spring Boot 프로젝트는 일반적으로 JAR 패키지로 만들어집니다.
import java.io.file; import java.io.fileInputStream; import java.io.ioexception; import java.util.properties; import org.springframework.util.stringutils; public final commonproperties {public static final string ppt_key_app_home = "app.home"; 공개 정적 최종 문자열 default_app_home = "./"; public static final String getApphome () {return system.getProperty ( "./", "./"); } public static String loadProperties2System (String Location)은 ioException {String configlocation = location; 파일 CNF; if (! stringUtils.haslength (location)) {configlocation = "./config"; CNF = 새 파일 (configlocation); if (! cnf.exists () ||! cnf.isdirectory ()) {configlocation = "../config"; CNF = 새 파일 (configlocation); }} else {cnf = 새 파일 (위치); } file [] arg2 = cnf.listfiles (); int arg3 = arg2.length; for (int arg4 = 0; arg4 <arg3; ++ arg4) {file file = arg2 [arg4]; if (file.isfile () && file.getName (). EndSwith ( ". Properties")) {속성 ppt = new Properties (); fileInputStream fi = 새로운 fileInputStream (file); 던질 수있는 arg8 = null; try {ppt.load (fi); system.getProperties (). putall (ppt); } catch (Throwable Arg17) {arg8 = arg17; arg17 던지기; } 마침내 {if (fi! = null) {if (arg8! = null) {try {fi.close (); } catch (Throwable Arg16) {arg8.addsuppressed (arg16); }} else {fi.close (); }}}} return configlocation; } public static String getVersion (class <?> clazz) {패키지 pkg = clazz.getPackage (); 문자열 ver = pkg! = null? pkg.getimplementationVersion () : "정의되지 않은"; 반환 ver == null? "정의되지 않은": Ver; }JAR 패키지 디렉토리의 구성 폴더에 구성 파일을 로그 구성, Application.YML 파일, 기타 구성 파일 등을 포함하여 동일한 레벨에 배치하십시오.
자동 구성 클래스를 작성하십시오
Spring MVC의 Spring.xml 구성 파일 대신 회사*를 스캔하는 데 사용됩니다.
import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration;@configuration@componentscan ( "com.my.rs", "com.my.service", "com.my.repositoritor")))) org.springframework.boot.autoconfigure.web.httpmessageconverters; import org.springframework.context.annotation.bean; import org.sprameframework.context.annotation.configuration; import org.springframework.web.servlet.config org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;/*** preconfiguration**/ @configurationpublic class myconfiguration extends webmvcconfigureradapter {@bean public httpmessageconverters () {return new httpseconverters () {) {); } @override public void addresourcehandlers (ResourceHandlerRegistry Registry) {//registry.addresourcehandler("/** ") // addresourcelocations ("classpath :/meta-inf/resources/** "); }RS, 서비스, 저장소를 작성하십시오
패키지 com.my.rs; import java.util.list; import org.springframework.bind.annotation.requestbody; import org.spramframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestod; import; org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.responsebody; import com.my.entity.user; @requestmapping ({ "/api/user"}) public interface userrs { @addethod (values = ", method", method ", method") @responsebody public user saveuser (@requestbody user user); @requestMapping (value = "/update", method = {requestMethod.post}) @ResponseBody public user updateUser (@RequestBody User User); @requestmapping (value = "/delete", method = {requestMethod.post, requestMethod.delete}) public void deleteuser (@requestparam string [] userIds); @requestmapping (value = "/get", method = {requestmethod.get}) @ResponseBody public user getUser (@requestParam String userId); @requestmapping (value = "/query/all", method = {requestmethod.get}) public list <user> queryall (); @requestmapping (value = "/query/byname", method = {requestmethod.get}) public list <user> querybyname (@requestparam string name); @requestmapping (value = "/query/byparentid", method = {requestmethod.get}) 공개 목록 <user> QueryChildren (@requestparam String parentid); // 매개 변수 없음 Pagination query @requestmapping (value = "/query/page", method = {requestmethod.get}) public list <user> querybypage (@requestparam int pageno, @requestparam int pageize, @requestbody (requestbody)}}}; 패키지 com.my.rs.impl; import java.util.list; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.ack.annotation.autowired; import org.springframework.web.bind.annotation.requestbody; import; org.springframework.web.bind.annotation.restcontroller; import com.my.entity.user; import com.my.rs.userrs; import com.my.service.userservice; @RestControllerPublic Class USERRSIMPL은 USERRS {public static logger = loggerfact.getLogger (UserRSimpl); @autowired userervice _userservice; @override public user saveuser (@requestbody user user) {try {return _userservice.save (user); } catch (Throwable e) {logger.error (e.getMessage (), e); e 던지기; }} @override public user updateuser (@requestbody user user) {return _userservice.update (user); } @override public void deleteuser (string [] userIds) {for (string userId : userIds) {_userService.deleteById (userId); }} @override public list <user> queryall () {return _userservice.queryall (); } @override public list <user> querybyname (문자열 이름) {return _userservice.findbyName (name); } @override public list <user> QueryChildren (String Parentid) {return _userservice.findbyparentid (parentid); } @override public user getUser (string userId) {return _userservice.findbyid (userId); } @override public list <user> querybypage (int pageno, int pagesize, user user) {return null; }} package com.my.service; import java.util.list; import org.springframework.beans.beans.annotation.autowired; import org.spramframework.stereotyp.service; import com.my.entity.user; import com.my.ry.userrepositority uservicepublic classecice vase vasevice extend vase vasevice extends base raseverier. userrepository _userrepository; 공개 목록 <user> findByName (문자열 이름) {return _userRepository.findbyName (이름); } public list <user> findbyparentid (String parentid) {return _userrepository.findbyparentid (parentid); }} package com.my.repository; import java.util.list; import com.my.entity.user; public interface userrepository 확장 baserepository <user> {list <user> findbyname (문자열 이름); List <user> findbyparentid (String Parentid);}위의 내용은 약간 번거로운 계층 모델을 채택하지만 나중에 각 계층의 비즈니스 로직을 수정하는 것이 더 편리합니다.
JPA 관련 클래스는 다음과 같습니다.
package com.my.service; import java.io.serializable; import javax.persistence.entitymanager; import javax.transaction.transactional; import org.springframework.beans.ack.annotation.autowired; import com.my.repository.baseritory; Serializable> {@autowired baserepository <e> _baserepository를 확장합니다. @autowired entitymanager em; public e save (e baseUnit) {return _baserepository.saveAndflush (baseUnit); } public e update (e baseUnit) {return _baserePository.saveAndFlush (baseUnit); } public void deleteById (문자열 id) {_baserEpository.delete (id); } public java.util.list <e> QueryAll () {return _baserEpository.findall (); } public e findByid (문자열 ID) {return _baserEpository.getOne (id); }}package com.my.repository; import java.io.serializable; import org.springframework.data.jpa.repository.jparepository; import org.springframework.data.repository.norepositorybean; @norepositorybeanpublic interface 기준 <e> extrends jperepository <e, serializable>
엔티티 클래스 : 데이터베이스 필드와 관련하여 부모 클래스 @MappedSuperClass의 주석에주의를 기울여야합니다.
패키지 com.my.entity; import java.util.arraylist; import java.util.list; import javax.persistence.entity; import javax.persistence.manytomany; import org.hibernate.annotations.dynamicinsert; import org.hibernate.annotations.dynamicupdate; import; org.hibernate.validator.constraints.email; @entity (name = "db_user")@dynamicinsert@dynamicupdatepublic 클래스 사용자는 baseUnit { / *** 계정 상태* / public static enum av -3101319619397064425L; 개인 문자열 비밀번호; 개인 문자열 소금; / ** 계정 상태*/ 개인 AccountStatus 상태; / ** 인증 이메일*/ @email (message = "user.email 속성은 이메일 형식을 준수해야합니다") 개인 문자열 이메일; / ** 휴대 전화 번호*/ 개인 문자열 mobileno; / ** ID 번호*/ 개인 문자열 카디드; @manytomany (targetentity = robol.class) 비공개 목록 <string> rolids; /** 별명. 선택 과목. */ 개인 문자열 별명; 공개 문자열 getCardid () {return cardid; } public String getEmail () {반환 이메일; } public String getMobileno () {return mobileno; } public String getNickName () {return 닉네임; } public String getPassword () {return password; } public list <string> getRoleids () {if (reaconIds == null) {rolearIds = new ArrayList <> (); } return rolearIds; } public String getSalt () {return salt; } public AccountStatus getStatus () {반환 상태; } public void setcardid (String Cardid) {this.cardid = cardid; } public void seteMail (문자열 이메일) {this.email = 이메일; } public void setmobileno (String mobileno) {this.mobileno = mobileno; } public void setNickName (문자열 별명) {this.nickName = 별명; } public void setpassword (문자열 비밀번호) {this.password = password; } public void setroleids (list <string> relearids) {this.roleids = releids; } public void setsalt (문자열 소금) {this.salt = salt; } public void setstatus (AccountStatus 상태) {this.status = 상태; }} 패키지 com.my.entity; import java.io.serializable; import java.util.date; import javax.persistence.id; import javax.persistence.mappedsuperclass; import javax.validation.constraints.constraints.constraints.constraints.constrints.size; size org.springframework.data.annotation.createdby; import org.springframework.data.annotation.createddate; import org.sprameframework.data.annotation.lastmodifiedby; import org.spramework.data.annotation.lastmodifieddate; {@id @notnull public string id; / ** * 상위 단위 ID */ @Size (max = 32, message = "baseUnit.parentID 속성 길이는 32보다 클 수 없습니다") public String parentid; / ** 부모 유형*/ public parenttype parenttype; / *** 단위 이름*/ @notnull (message = "baseUnit.name 속성이 비어있을 수 없음") 공개 문자열 이름; @CreatedBy Public String CreateBy; @CreatedDate 공개 날짜가 생성되었습니다. @lastModifiedBy public String lastModifiedBy; / *** 마지막 업데이트 날짜*/ @lastModifiedDate Public Date LastModifiedDate; public String getId () {return id; } public void setId (String id) {this.id = id; } / *** 단위 이름을 가져옵니다** @return 필수* / public string getName () {return name; } / ** * * @return uuid, {} 및 - * / public String getParentId () {return parentid; } public parenttype getParentType () {return parenttype; } public String getStationId () {return StateId; } public String getThumbNailid () {return thathnailid; } public String getCreateBy () {return createby; } public void setcreateby (String CreateBy) {this.createby = createby; } public Date getCreatedate () {return createate; } public void setCreatedate (날짜 createate) {this.createdate = createate; } / ** * 단위 이름을 설정 * * @param name * 필수 * / public void setName (문자열 이름) {this.name = name; } / ** * {} 및 - * / public void setparentid (String Parentid) {this.parentid = parentid; } public String getLastModifiedBy () {return lastModifiedBy; } public void setLastModifiedBy (String lastModifiedBy) {this.lastModifiedBy = lastModifiedBy; } 공개 날짜 getLastModifiedDate () {return lastModifiedDate; } public void setLastModifiedDate (날짜 lastModifiedDate) {this.lastModifiedDate = lastModifiedDate; }}구성 파일 :
서버 : 16800 ContextPath :/로깅 : 구성 : ./config/logback.xml 스프링 : http : multipart : enabled : false dataSource : url : jdbc : jdbc : mysql : //127.0.0.1 : 3306/db? com.mysql.jdbc.driver JPA : 데이터베이스 : MySQL Show-SQL : True Hibernate : DDL-Auto : 업데이트 Jackson : Serialization : Indent_output : True
#hibernate : 데이터베이스 테이블 구조를 유지하는 엔티티 클래스의 특정 동작. 업데이트는 엔티티 클래스의 속성이 변경되면 테이블 구조가 업데이트된다는 것을 의미합니다. 여기서 우리는 또한 값을 창출 할 수 있습니다. 이는 마지막 생성 된 테이블이 시작시 삭제되고 엔티티 클래스에 따라 테이블을 재생성 함을 의미합니다. 현재 이전 테이블의 데이터가 지워집니다. 또한 값 Create-Drop을 취할 수 있습니다. 즉, 테이블이 시작시 엔터티 클래스를 기반으로 테이블이 생성되지만 세션 변환이 닫히면 테이블이 삭제됩니다. 유효성 검사는 엔티티 클래스와 데이터 테이블이 시작시 일관성이 있음을 의미합니다. 아무도 아무것도 수행되지 않았다는 것을 의미하지 않습니다. #show-sql은 hibernate 인쇄를 의미합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.