この記事では、Maven Project用のSpring Boot+Spring MVC+JPAの構築例を紹介します。それはあなたと共有されます。詳細は次のとおりです。
スプリングブートサポートを追加し、関連するパッケージを紹介します。
1. Mavenプロジェクトは、pom.xmlにとって不可欠です。 Spring Bootの導入については、公式Webサイトを参照してください。
<parent> groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> <バージョン> 1.5.9.9.9.9.9.9.9.9.9.9.9.9.9.9.9.parent> <依存関係>依存関係> <groupid> javax.servlet </groupid> artifactid> javax.servleteletelet-aapied> <scope> revided </scope> <! - 不要なjarパッケージをコンパイルして公開 - > </dependency> <依存関係> <groupid> org.springframework </groupid> <artifactid> spring-webmvc </artifactid> </dependency> <dependency> <shipdency.springframework </groupid> <artifactid> spring-boot-starter-web </artifactid> </dependency> <! - jpa jarパッケージ、データベースの操作 - > <依存関係> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-data-jpa <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-boot-starter-data-redis </artifactid> </dependency> <! - mysqlドライバー - > <依存関係> <グループ<groupid> org.apache.shiro </groupid> <artifactid> shiro-core </artifactid> <version> 1.2.2 </version> </dependency> <dependency> groupid> org.apache.shiro.shiro.shiro ehcache-> <dependency> groupid> org.apache.shiro </groupid> <artifactid> shiro-ehcache </artifactid> <バージョン> 1.2.2 </version> </dependency> </dependencies> <build> <bragins> <groupid> orgwork.boot </groupid> <artifactid> spring-boot-maven-plugin </artifactid> <executions> <execution> <goal> repackage </goal> </goal> </execution> </executions> </plugin> </plugins> <finalName> name </finalName> </build>
2。上記のコードでは、Spring Bootを紹介します。 Spring MVCおよびJPA、およびMySQLデータベース用のドライバーJAR。
スタートアップクラスを作成し、構成ファイルをインストールします。
1.スタートアップクラスは次のとおりです。
Import org.springframework.boot.springApplication; Import org.springframework.boot.autoconfigure.enableautoconfiguration; Import org.springframework.boot.autoconfigure.springbootapplication; import springframework.data.jpa.repository.config.enablejpaauditing; import java.io.ioexception; import com.my.config.commonproperties;@springbootapplication; = 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。再梱包せずに変更を容易にするために、ClassPathの外側に構成ファイルを配置します。スプリングブートプロジェクトは通常、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_pheme = "App.home"; public static final string default_app_home = "./"; public static final string getapphome(){return System.getProperty( "./"、 "./"); } public static string loadproperties2system(string location)throws ioexception {string configlocation = location;ファイルCNF; if(!stringutils.haslength(location)){configlocation = "./config"; cnf = new file(configlocation); if(!cnf.exists()||!cnf.isdirectory()){configlocation = "../config"; cnf = new file(configlocation); }} else {cnf = new file(location); } 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 = new FileInputStream(file);スロー可能なarg8 = null; {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(); }}}} configlocationを返します。 } public static string getversion(class <?> clazz){パッケージpkg = clazz.getPackage();文字列ver = pkg!= null? pkg.getimplementationversion(): "未定義"; ver == nullを返しますか? 「未定義」:ver; }JARパッケージのディレクトリの構成フォルダーに構成ファイルを同じレベルに配置します。
自動構成クラスを作成します
Spring MVCのspring.xml構成ファイルの代わりに、会社*をスキャンするために使用します。
org.springframework.context.annotation.componentscan; Import org.springframework.context.annotation.configuration;@configuration@componentscan( "com.my.rs"、 "com.my.service"、 "com.my.my.my.my.my.my.my.my.my.my.my.my.my.my.my. org.springframework.autoconfigure.web.httpmessageconverters; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; Import org.springframistorwork.web.web.web.web.servelet.conframework Web.servlet.config.annotation.webmvcconfigureradapter;/*** preconfiguration**/ @configurationpublic class myconfigurationはwebmvcconfigureradapter {@bean public httpmessageconverters customconterters(){@bean public httpmessageconter {@bean public httpmessageconter {@bean public httpmessageconters extendsを拡張します。 } @Override public void addResourceHandlers(ResourceHandlerRegistry Registry){//registry.addresourcehandler("/** ")// .addresourcelocations(" classpath:/meta-inf/resources/** "); }RS、サービス、リポジトリを書き込みます
パッケージcom.my.rs; import java.util.list; import org.springframework.web.bind.annotation.requestbody; Import org.springframework.web.bind.annotation.requestmapping; Import org.springframework.web.bind.annotation.requestmethod; requestmethod; org.springframework.web.bind.annotation.requestparam; Import org.springframework.web.bind.annotation.responsebody; Import com.my.entity.user; @requestmapping({"/api/user"})公開インターフェースuserrs @ResponseBodyパブリックユーザーSaveUSER(@RequestBodyユーザーユーザー); @RequestMapping(value = "/update"、method = {requestmethod.post})@responsebody public user updateUser(@requestbody user users); @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})public list <user> queryChildren(@RequestParam String darterID); //パラメーターページネーションQuery @RequestMapping(value = "/query/page"、method = {requestmethod.get})public list <user> querybypage(@requestparam int pageno、@requestparam int pagesize、 @requestbody(rebys = fals)ユーザーユーザー);}パッケージcom.my.rs.impl; import java.util.list; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.Annotation; org.springframework.web.bind.annotation.RestController;import com.my.entity.User;import com.my.rs.UserRS;import com.my.service.UserService;@RestControllerpublic class UserRSImpl implements UserRS{ public static Logger logger = LoggerFactory.getLogger(UserRSImpl.class); @autowired userservice _userservice; @OverrideパブリックユーザーSaveUSER(@RequestBodyユーザー){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(string name){return _userservice.findbyname(name); } @Override public List <user> queryChildren(String derperid){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; }}パッケージcom.my.service; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import com.my.entity.user; import com.my.repository.userrepository; @autowired userrepository _userrepository; public list <user> findbyname(string name){return _userrepository.findbyname(name); } public list <user> findbyparentid(string parentid){return _userrepository.findbyparentid(parentid); }}パッケージcom.my.repository; import java.util.list; import com.my.entity.user; public interface userrepository拡張baserepository <user> {list <user> findbyname(string name);リスト<ユーザー> FindByparentID(StringParentID);}上記は層状モデルを採用していますが、これは少し面倒ですが、各レイヤーのビジネスロジックを後で変更する方が便利です。
JPA関連のクラスは次のとおりです。
パッケージcom.my.service; import java.io.serializable; import javax.persistence.entitymanager; import javax.transaction.transactional; import org.springframework.factory.annotation.Autowired; Import com.my.repository.baserpository./**@@@@@@@@@@@@commentory. baseService <e extends 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(string id){_baserepository.delete(id); } public java.util.list <e> queryall(){return _baserepository.findall(); } public e findbyid(string id){return _baserepository.getone(id); }}パッケージcom.my.repository; import java.io.serializable; import org.springframework.data.jpa.repository.jparepository; import org.springframework.data.repository.norepositorybean;
エンティティクラス:データベースフィールドに関連して、親クラスの注釈に注意を払う必要があります
パッケージ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.dynamimupdate; dynamimupdate; org.hibernate.validator.constraints.email; @Entity(name = "db_user")@dynamicincentert@dynamicupdatepublic class users extends baseunit { / ***アカウントステータス* /パブリックスタティックenum accountstatus { / *** normal* / enable、// ** ** disable* / disable static _isable} disable _> disable static disable* / ** -3101319619397064425L;プライベート文字列パスワード。プライベートストリングソルト; / **アカウントステータス*/ private accountStatusステータス。 / **認証メール*/ @email(message = "user.email属性は、電子メール形式に準拠する必要があります")private string email; / **携帯電話番号*/プライベートストリングモービレノ; / ** ID番号*/ private string cardid; @manytomany(targetentity = role.class)private list <string> roleids; /**ニックネーム。オプション。 */ private string nickname; public string getCardid(){return cardid; } public string getemail(){return email; } public string getMobileno(){return mobileno; } public string getnickname(){return nickname; } public string getPassWord(){パスワードを返します。 } public list <String> getRoleids(){if(roleIds == null){roleIds = new arrayList <>(); } return roleds; } public string getSalt(){return salt; } public AccountStatus getStatus(){return status; } public void setcardid(string cardid){this.cardid = cardid; } public void setemail(string email){this.email = email; } public void setmobileno(String Mobileno){this.mobileno = mobileno; } public void setnickname(string nickname){this.nickname = nickname; } public void setPassword(string password){this.password = password; } public void setroleids(list <string> roleids){this.roleds = roleIds; } public void setSalt(String Salt){this.salt = salt; } public void setStatus(accountstatus status){this.status = status; }}パッケージcom.my.entity; import java.io.serializable; import java.util.date; import javax.persistence.id; import javax.persistence.mappsuperclass; import javax.validation.constraint.notnull; Import javax.validation.constraints.sizezize; springframework.data.annotation.createdby; Import org.springframework.data.annotation.createddate; Import org.springframework.data.annotation.lastModifiedby; Import org.springframework.data.annotation.lastmodifieddate.lastModifieddate serializable {@id @notnull public string id; / ** *親ユニットID */ @size(max = 32、message = "baseunit.parentid属性の長さは32"を超えることはできません)public string parentid; / **親ユニットのタイプ*/ public parentType parentType; / ***ユニット名*/ @notnull(message = "baseunit.name属性は空にすることはできません")public string name; @createdbyパブリック文字列createby; @CreateDDATE Public Date Createdate; @lastModifiedBy public String lastModifiedBy; / ***最終更新日*/ @lastModifiedDate publicModifiedDate; public string getId(){return id; } public void setid(string id){this.id = id; } / ***ユニットの名前を取得** @return reculy* / public string getname(){return name; } / ** * * @return uuid、{}および - * / public string getParentId(){return derperid; } public parentType getParentType(){return parentType; } public string getStationId(){return StationID; } public String getThumbnailid(){return thumbnailid; } public string getCreateby(){return createby; } public void setcreateby(string createby){this.createby = createby; } public date getCreateDate(){return createdate; } public void setCreateDate(date recutedate){this.createdate = createdate; } / ** *ユニットの名前を設定 * * @param name * exicly * / public void setName(string name){this.name = name; } / ** *親ユニットIDを設定 * * * @param parentID * uuid、{}および - * / public void setParentID(string darterid){this.parentid = darperid; } public string getLastModifiedBy(){return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy){this.lastModifiedBy = lastModifiedBy; } public date getLastModifiedDate(){return lastModifiedDate; } public void setLastModifiedDate(date lastModifiedDate){this.lastModifiedDate = lastModifiedDate; }}構成ファイル:
サーバー:ポート:16800 ContextPath:/logging:config:./config/logback.xml spring:http:multipart:enabled:false dataSource:url:jdbc://127.0.0.1:3306/db? com.mysql.jdbc.Driver JPA:データベース:MySQL show-sql:true hibernate:ddl-auto:update jackson:serialization:indent_output:true
#HiberNate:データベーステーブル構造を維持するエンティティクラスの特定の動作。更新とは、エンティティクラスのプロパティが変更されると、テーブル構造が更新されることを意味します。ここでは、価値のある値を取得することもできます。これにより、最後の生成されたテーブルが起動時に削除され、エンティティクラスに従ってテーブルを再生したことがわかります。この時点で、前の表のデータがクリアされます。また、値Create-Dropを取得することもできます。つまり、テーブルはスタートアップのエンティティクラスに基づいて生成されますが、SessionFactoryが閉じられると、テーブルが削除されます。検証とは、エンティティクラスとデータテーブルが起動時に一貫していることを意味します。何も行われないことを意味しません。 #show-sqlは、操作するときにコンソールにhibernateを意味するhibernate inger sqlステートメントを意味します#jacksonはフォーマットされた出力json文字列を意味します
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。