In diesem Artikel wird ein Beispiel für das Erstellen von Spring Boot+Spring MVC+JPA für das Maven -Projekt vorgestellt. Es wird mit Ihnen geteilt. Die Details sind wie folgt:
Fügen Sie die Spring -Boot -Unterstützung hinzu und stellen Sie verwandte Pakete ein:
1. Das Maven -Projekt ist für pom.xml unverzichtbar. Die Einführung von Spring Boot finden Sie auf der offiziellen Website:
<Ters </GroupId> org.springFramework.boot </GroupId> <artifactId> Spring-Boot-Starter-Parent </artifactId> <version> 1.5.Release </Version> </parent> <Depelen> <abhängigkeit> <GroupId> javax.servlet </gruppe </artifactId> javax.Servlet> </artifactId> javax.si <Scope> bereitgestellt </scope> <!-Kompilieren und veröffentlichen unerwünschte JAR-Pakete-> </abhängig> <depelzus> <gruppe> org.springFramework </gruppen> <artifactid> Spring-webmvc </artifactId> </abhängig> <De vorangebracht> <gruppe> org.sPlamework. <artifactid> Spring-Boot-Starter-Web </artifactId> </abhängig> <!-JPA JAR-Paket, Betrieb der Datenbank-> <Depopentcy> <Groupid> org.springFramework <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--mysql driver--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version> </dependency> <!-- shiro ehcache --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.2</version> </dependency> </dependencies> <build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <Leacutions> <Execution> <giele> <giel> Repackage </Ziel> </gielen> </Execution> </Executions> </plugin> </plugins> <finanzname> Name </finalName> </build>
2. Der obige Code führt Spring Start ein. Spring MVC und JPA sowie Treiber -Jar für die MySQL -Datenbank;
Schreiben Sie eine Startklasse und installieren Sie die Konfigurationsdatei:
1. Die Startkurs lautet wie folgt:
import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.enableAutoconfiguration; import org.springframework.boot.autoconfigure.springbootAplication; org.springframework.data.jpa.repository.config.EnableJpaAuditing;import java.io.IOException;import com.my.config.CommonProperties;@SpringBootApplication@EnableAutoConfiguration@EnableJpaAuditingpublic class Application { public static void main(String[] args) throws 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. Platzieren Sie die Konfigurationsdatei außerhalb des Klassenpfads, um die Änderung ohne Neuverpackung zu erleichtern. Spring -Boot -Projekte werden in der Regel zu Glaspaketen verarbeitet:
Import Java.io.file; Import java.io.fileinputstream; import java.io.ioxception; import Java.util.properties; public static Final String default_app_home = "./"; public static final String getAapphome () {return system.getProperty ("./", "./"); } public static String loadProperties2System (String -Speicherort) löst IOException {String configLocation = location; Datei CNF; if (! Stringutils.hasLength (Speicherort)) {configLocation = "./config"; cnf = neue Datei (configLocation); if (! cnf.exists () ||! cnf.isdirectory ()) {configLocation = "../config"; cnf = neue Datei (configLocation); }} else {cnf = neue Datei (Ort); } File [] arg2 = cnf.listfiles (); int arg3 = arg2.Length; für (int arg4 = 0; arg4 <arg3; ++ arg4) {file file = arg2 [arg4]; if (file.isfile () && file.getName (). Endswith (". Eigenschaften")) {Eigenschaften ppt = new Properties (); FileInputStream fi = new FileInputStream (Datei); Throwable arg8 = null; try {ppt.load (fi); System.getProperties (). Putall (PPT); } catch (throwable arg17) {arg8 = arg17; Wirf Arg17; } endlich {if (fi! = null) {if (arg8! = null) {try {fi.close (); } catch (throwable arg16) {arg8.addsupprimed (arg16); }} else {fi.close (); }}}} return configLocation; } public static String Getversion (Klasse <?> Clazz) {Paket pkg = clazz.getPackage (); String ver = pkg! = Null? pkg.getImplementationVersion (): "undefiniert"; return ver == null? "undefiniert": ver; }Platzieren Sie die Konfigurationsdatei im Konfigurationsordner des JAR -Paketverzeichnisses auf derselben Ebene, einschließlich Protokollkonfiguration, Application.yml -Datei, anderen Konfigurationsdateien usw.;
Schreiben Sie automatische Konfigurationsklassen
Wird zum Scannen von Unternehmen*verwendet, anstelle der Spring MVC -Konfigurationsdatei von Spring.xml:
import org.springframework.context.annotation.comPonentscan; org.springframework.boot.autoconfigure.web.httpMessageConverters; import org.springframework.context.annotation.bean; org.springframework.web.servlet.config.annotation.resourceHandlerregistry; org.springframework.web.servlet.config.annotation public httpMessageConverters CustomConverters () {neu httpMessageConverters () zurückgeben; } @Override public void addResourceHandlers (Ressourcehandlerregistry Registry) {//registry.addresourceHandler("/* ") // .addresourcelocations (" Classpath:/meta-inf/ressourcen/** "); }Schreiben Sie RS, Service, Repository
Paket com.my.rs; import java.util.list; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.ResponseBody; com.my.entity.user; @RequestMapping (value = "/add", method = {requestMethod.post}) @ResponseBody Public User SaveUser (@RequestBody -Benutzer); @RequestMapping (value = "/update", method = {requestMethod.post}) @ResponseBody Public User UpdateUser (@RequestBody -Benutzer); @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}) publiclist <Benetzbuchs <Unter> queryAll (); @RequestMapping (value = "/query/byname", method = {requestMethod.get}) publiclist <Benuche> queryByName (@RequestParam String Name); @RequestMapping (value = "/query/byparentid", method = {requestMethod.get}) publiclist <Bener> queryChildren (@RequestParam String parentId); // Keine Parameter -Pagination -Abfrage @RequestMapping (value = "/query/page", method = {requestMethod.get}) publiclist <Benetzbuchs <Benutzer> queryBypage (@RequestParam int pageno, @RequestParam Int PageSize, @RequestBody (fordert = false) Benutzer usw.}} usw.}} usw.}} usw.}} usw.}} usw.}} usw.}} usw.}}} usw.}}} user) Paket com.my.rs.impl; import java.util.list; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.bean.factory.Annotation.autowired; org.springframework.web.bind.annotation.restcontroller; import com.my.entity.user; import com.my.rs.userrs; com.my.service.userservice; @restcontrollerpublic class userSimpl implements users {öffentliches statisches Logger Logger Logger = Logger Logger = Logger = Public staty logger = LoggerFactory.getLogger (userrSimpl.class); @Autowired UserService _USERService; @Override public User SaveUser (@RequestBody -Benutzer) {try {return _userService.save (Benutzer); } catch (throwable e) {logger.Error (e.getMessage (), e); werfen e; }} @Override public user updateUser (@RequestBody -Benutzer) {return _USERService.update (Benutzer); } @Override public void deleteUser (string [] userIds) {für (String userId: userIDs) {_userService.deletebyId (userId); }} @Override publiclist <Künstlers> queryAll () {return _userService.queryall (); } @Override publiclist <Künstlers> queryByName (String -Name) {return _userService.findByName (Name); } @Override publiclist <Benetzes> queryChildren (string parentId) {return _userService.findbyparentID (parentId); } @Override öffentlicher Benutzer getUser (String userID) {return _USERService.findbyId (userId); } @Override public List <Unter> queryBypage (int pageno, int pageSize, Benutzer Benutzer) {return null; }} Paket com.my.service; import java.util.list; import org.springframework.beans.factory.Annotation.autowired; @Autowired userRepository _uSerRepository; public list <user> findByName (String -Name) {return _USERREPOSORY.FINDBYNAME (Name); } publiclist <Benetzwerks> findByparentID (String parentID) {return _uSerRepository.findbyparentID (parentId); }} Paket com.my.repository; import java.util.list; import com.my.entity.user; öffentliche interface userRepository erweitert BasieRePository <Beus> {list <Benote <User> findByName (String -Name); LIST <Bener> findByparentID (String -ParentID);}Das obige wird ein geschichteter Modell angewendet, das etwas umständlich ist, aber es ist bequemer, die Geschäftslogik jeder Schicht später zu ändern.
JPA-bezogene Klassen sind wie folgt:
Paket com.my.service; import java.io.serializable; import Javax.Persistence.EntityManager; Import Javax.transaction.transactional; BaseSeService <e erweitert serialisierbar> {@autowired BasieRePository <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); }} Paket com.my.repository; import Java.io.Serializable; import org.springframework.data.jpa.repository.jparepository; Serialisierbar> {}Entitätsklasse: In Bezug auf Datenbankfelder müssen Sie auf die Annotation in der übergeordneten Klasse @MappedSuperClass achten
package 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 class User extends BaseUnit { /** * Account status*/ public static enum AccountStatus { /** * Normal*/ Enable, // /** * Disable */ Disable } private static final long serialVersionUID = -3101319619397064425L; privates Zeichenfolgenkennwort; privates Stringsalz; / ** Kontostatus*/ privates Kontostatus Status; / ** Authentifizierungs -E -Mail*/ @email (Message = "user.Email -Attribut muss dem E -Mail -Format entsprechen") private Zeichenfolgen -E -Mail; / ** Handynummer*/ private String mobileno; / ** ID -Nummer*/ private String Cardid; @Manytomany (targetEntity = rollen.class) private list <string> rollen; /** Spitzname. Optional. */ privater String -Spitzname; public String getCardId () {return cardid; } public String getemail () {E -Mail zurückgeben; } public String getMobileno () {return mobileno; } public String getNickName () {return spickname; } public String getPassword () {Kennwort zurückgeben; } publiclist <string> getRoleids () {if (rollens == null) {rollenIds = new ArrayList <> (); } return rollens; } public String getalt () {return salt; } public AccountStatus getStatus () {Rückgabestatus; } public void setCardId (String Cardid) {this.cardId = CardId; } public void setemail (String -E -Mail) {this.email = E -Mail; } public void setMobileno (String mobileno) {this.mobileno = mobileno; } public void setNickName (String -Spitzname) {this.nickname = spitzname; } public void setPassword (String -Passwort) {this.password = password; } public void setRoleids (list <string> rollens) {this.roleids = rollenIds; } public void setSalt (String Salz) {this.Salt = salt; } public void setStatus (AccountStatus Status) {this.status = Status; }} Paket com.my.entity; import java.io.serializable; import java.util.date; import Javax.Persistence.id; Import Javax.Persistence.MappedsuperClass; Import Javax.validation.constraints.notnull; org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.createdDate; import org.springframework.data.annotation Serialisierbar {@id @notnull public String id; / ** * übergeordnete Einheits -ID */ @size (max = 32, Message = "BaseUnit.Parentid Attributlänge kann nicht größer als 32") öffentlicher String -ParentID; / ** Art der übergeordneten Einheit*/ public ParentType ParentType; / *** Einheitsname*/ @notnull (Message = "BaseUnit.Name Attribut kann nicht leer sein") öffentlicher String -Name; @Createdby Public String createBy; @CreatedDate Public Date Createdate; @LastModifiedby Public String lastModifiedby; / *** Letztes aktualisiertes Datum*/ @lastModifiedDate Public Datum LastModifiedDate; public String getid () {return id; } public void setID (String -ID) {this.id = id; } / *** den Namen der Einheit erhalten** @return erforderlich* / public String getName () {return name; } / ** * * @return uUid, ohne {} und - * / public String getParentID () {return pentId; } 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 (Datum erstellt) {this.createdate = createdate; } / ** * Setzen Sie den Namen des Einheit * * @param name * Erforderlich * / public void setName (String -Name) {this.name = name; } / ** * Setzen Sie die übergeordnete Einheit -ID * * @param parentId * uUid, ohne {} und - * / public void setParentID (String parentId) {this.parentID = parentID; } public String getLastModifiedBy () {return lastModifiedBy; } public void setLastModifiedBy (String lastModifiedBy) {this.lastModifiedBy = lastModifiedBy; } öffentliches Datum getLastModifiedDate () {return lastModifiedDate; } public void setLastModifiedDate (Datum lastModifiedDate) {this.lastModifiedDate = lastModifiedDate; }}Konfigurationsdatei:
Server: Port: 16800 CONTEXTPATH:/Logging: Konfiguration: ./config/logback.xml Spring: http: MultiPart: Aktiviert: Falsch DataSource: URL: JDBC: MySQL: //127.0.0.1: 3306/DB? UseUnicode = True & charakteristisch & charakteristisch & charakteristisch: com.mysql.jdbc.driver JPA: Datenbank: MySQL Show-SQL: TRUE Hibernate: DDL-Auto: Aktualisieren Sie Jackson: Serialisierung: indent_output: true: true
#HiBERNATE: Das spezifische Verhalten der Entitätsklasse, bei der die Datenbanktabellenstruktur aufrechterhalten wird. Update bedeutet, dass bei der Änderung der Eigenschaften der Entitätsklasse die Tabellenstruktur aktualisiert wird. Hier können wir auch den Wert erstellen. Dies bedeutet, dass die zuletzt generierte Tabelle beim Start gelöscht wurde und die Tabelle gemäß der Entity -Klasse regeneriert. Zu diesem Zeitpunkt werden die Daten in der vorherigen Tabelle gelöscht. Es kann auch den Wert erstellen, was bedeutet, dass die Tabelle basierend auf der Entitätsklasse beim Start generiert wird. Wenn jedoch die Sitzung der Sitzung geschlossen ist, wird die Tabelle gelöscht. Validate bedeutet, dass die Entitätsklasse und die Datentabelle beim Start konsistent sind. Keiner bedeutet, dass nichts getan wird. #show-SQL bedeutet Hibernate-Drucke echte SQL-Anweisung auf der Konsole beim Betrieb #jackson bedeutet formatierte Ausgabe JSON String
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.