บทความนี้แนะนำตัวอย่างของการสร้าง Spring Boot+Spring MVC+JPA สำหรับโครงการ Maven มันถูกแบ่งปันกับคุณ รายละเอียดมีดังนี้:
เพิ่มสปริงบูตสนับสนุนและแนะนำแพ็คเกจที่เกี่ยวข้อง:
1. โครงการ Maven นั้นขาดไม่ได้สำหรับ POM.XML สำหรับการแนะนำของ Spring Boot โปรดดูเว็บไซต์ทางการ:
<carent> <roupId> org.springframework.boot </groupId> <ratifactid> Spring-Boot-Starter-Parent </artifactid> <Sersion> 1.5.9.Release </เวอร์ชัน> </Parent> <cope> ให้ </cope> <!-รวบรวมและเผยแพร่แพ็คเกจขวดที่ไม่ต้องการ-> </การพึ่งพาอาศัย> <การพึ่งพา> <roupId> org.springframework </groupId> <ArtIfactId> Spring-Boot-Starter-Web </ArtifactId> </derpendency> <!-JPA JAR แพ็คเกจการใช้งานฐานข้อมูล-> <การพึ่งพาอาศัย> <roupId> org.springframework.boot </groupid> <RoupID> org.springframework.boot </groupId> <ratifactid> Spring-Boot-Starter-Data-Redis </artifactid> </การพึ่งพาอาศัย> <! <RoupID> org.apache.shiro </groupId> <ratifactid> Shiro-core </artifactId> <Sersion> 1.2.2 </เวอร์ชั่น> </การพึ่งพา> <การพึ่งพา> <roupId> org.apache.shiro </groupid> ehcache-> <การพึ่งพา> <roupId> org.apache.shiro </groupId> <ratifactid> Shiro-Ehcache </artifactid> <version> 1.2.2 </เวอร์ชัน> </derness> </การพึ่งพาอาศัย <ArtIfactId> Spring-Boot-Maven-Plugin </artifactId> <cenections> <การดำเนินการ> <goals> <source> การบรรจุใหม่ </เป้าหมาย> </เป้าหมาย> </Execution>
2. รหัสด้านบนแนะนำสปริงบูต Spring MVC และ JPA รวมถึงขวดไดรเวอร์สำหรับฐานข้อมูล MySQL;
เขียนคลาสเริ่มต้นและติดตั้งไฟล์การกำหนดค่า:
1. คลาสเริ่มต้นมีดังนี้:
นำเข้า org.springframework.boot.springapplication; นำเข้า org.springframework.boot.autoconfigure.enableautoconfiguration นำเข้า org.springframework.boot.autoconfigure.springbootapplication; org.springframework.data.jpa.repository.config.enablejpaauditing; นำเข้า java.io.ioexception; นำเข้า com.my.config.commonproperties;@springbootapplication@enableautoconfiguration@enablejpaauditingpublic 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. วางไฟล์การกำหนดค่านอก classPath เพื่ออำนวยความสะดวกในการแก้ไขโดยไม่ต้องบรรจุใหม่ โดยทั่วไปโครงการบูตฤดูใบไม้ผลิจะทำในแพ็คเกจ Jar:
นำเข้า java.io.file; นำเข้า java.io.fileinputstream; นำเข้า java.io.ioexception; นำเข้า java.util.properties; นำเข้า org.springframework.util.stringutils; สตริงสุดท้ายคงที่สาธารณะ default_app_home = "./"; สตริงสุดท้ายคงที่สาธารณะ getApphome () {return system.getProperty ("./", "./"); } สตริงสาธารณะคงที่ loadProperties2System (ตำแหน่งสตริง) พ่น IOException {สตริงการกำหนดค่า = ตำแหน่ง; ไฟล์ CNF; if (! stringutils.haslength (ตำแหน่ง)) {configlocation = "./config"; CNF = ไฟล์ใหม่ (การกำหนดค่า); if (! cnf.exists () ||! cnf.isdirectory ()) {configlocation = "../config"; CNF = ไฟล์ใหม่ (การกำหนดค่า); }} else {cnf = ไฟล์ใหม่ (ตำแหน่ง); } ไฟล์ [] arg2 = cnf.listfiles (); int arg3 = arg2.length; สำหรับ (int arg4 = 0; arg4 <arg3; ++ arg4) {ไฟล์ไฟล์ = arg2 [arg4]; if (file.isfile () && file.getName (). endswith (". properties")) {คุณสมบัติ ppt = คุณสมบัติใหม่ (); FileInputStream FI = ใหม่ FileInputStream (ไฟล์); arg8 ที่โยนได้ = null; ลอง {ppt.load (fi); System.getProperties (). Putall (ppt); } catch (throwable arg17) {arg8 = arg17; โยน arg17; } ในที่สุด {ถ้า (fi! = null) {ถ้า (arg8! = null) {ลอง {fi.close (); } catch (throwable arg16) {arg8.addsuppressed (arg16); }} else {fi.close (); }}}} ส่งคืนการกำหนดค่า; } String Public String GetVersion (คลาส <?> Clazz) {แพ็คเกจ pkg = clazz.getPackage (); String ver = pkg! = null? pkg.getimplementationversion (): "undefined"; return ver == null? "ไม่ได้กำหนด": ver; -วางไฟล์การกำหนดค่าในโฟลเดอร์ config ของไดเรกทอรีของแพ็คเกจ JAR ในระดับเดียวกันรวมถึงการกำหนดค่าบันทึกไฟล์ application.yml ไฟล์การกำหนดค่าอื่น ๆ ฯลฯ ;
เขียนคลาสการกำหนดค่าอัตโนมัติ
ใช้ในการสแกน บริษัท*แทนที่จะเป็นไฟล์กำหนดค่า Spring.xml ของ Spring MVC:
นำเข้า org.springframework.context.annotation.componentscan; นำเข้า org.springframework.context.annotation.configuration;@configuration@componentscan (basepackages = {"com.my.rs", "com.my.service" org.springframework.boot.autoconfigure.web.httpmessageConverters; นำเข้า org.springframework.context.annotation.bean; นำเข้า org.springframework.context.annotation.configuration; org.springframework.web.servlet.config.annotation.resourcehandlerregistry นำเข้า org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; httpmessageConverters customconverters () {ส่งคืน httpmessageConverters ใหม่ (); } @Override โมฆะสาธารณะ addResourceHandlers (ResourceHandlerRegistry Registry) {//registry.addresourceHandler("/** ") // .addresourceLocations (" classpath:/meta-inf/resources/** "); -เขียน RS, บริการ, ที่เก็บ
แพ็คเกจ com.my.rs; นำเข้า java.util.list; นำเข้า org.springframework.web.bind.annotation.requestbody; นำเข้า org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestparam; นำเข้า org.springframework.web.bind.annotation.responsebody; นำเข้า com.my.entity.user; @requestmapping ({"/api/user"}) @RequestMapping (value = "/เพิ่ม", method = {requestMethod.post}) @ResponseBody ผู้ใช้สาธารณะผู้ใช้ SaveUser (@requestbody ผู้ใช้ผู้ใช้); @RequestMapping (value = "/update", method = {requestMethod.post}) @ResponseBody UperiteUser ผู้ใช้สาธารณะ (@requestbody ผู้ใช้ผู้ใช้); @RequestMapping (value = "/ลบ", method = {requestMethod.post, requestMethod.delete}) โมฆะสาธารณะ deleteUser (@requestparam string [] userIds); @RequestMapping (value = "/get", method = {requestMethod.get}) @ResponseBody ผู้ใช้สาธารณะ GetUser (@RequestParam String userId); @RequestMapping (value = "/query/all", method = {requestmethod.get}) รายการสาธารณะ <user> queryall (); @RequestMapping (value = "/query/byname", method = {requestMethod.get}) รายการสาธารณะ <user> queryByName (@requestparam ชื่อสตริง); @RequestMapping (value = "/query/byparentId", method = {requestMethod.get}) รายการสาธารณะ <user> querychildren (@requestparam สตริง parentid); // ไม่มีพารามิเตอร์ pagination Query @RequestMapping (value = "/query/page", method = {requestMethod.get}) รายการสาธารณะ <ผู้ใช้> queryByPage (@requestparam int pageno, @requestparam int pagesize, @requestbody แพ็คเกจ com.my.rs.impl; นำเข้า java.util.list; นำเข้า org.slf4j.logger; นำเข้า org.slf4j.loggerfactory; นำเข้า org.springframework.beans.factory.annotation.autowired; org.springframework.web.bind.annotation.restcontroller; นำเข้า com.my.entity.user; นำเข้า com.my.rs.userrs; นำเข้า com.my.service.userservice; @restcontrollerpublic userrsimpl @autowired Userservice _userService; @Override ผู้ใช้สาธารณะ SaveUser (@requestbody ผู้ใช้ผู้ใช้) {ลอง {return _userService.save (ผู้ใช้); } catch (throwable e) {logger.error (e.getMessage (), e); โยน e; }} @Override Uper UpdateUser ผู้ใช้สาธารณะ (@requestbody ผู้ใช้ผู้ใช้) {return _userService.update (ผู้ใช้); } @Override โมฆะสาธารณะ DELETEUSER (String [] USERIDS) {สำหรับ (String userId: userIds) {_usERSERVICE.DELETEBYID (USERIDID); }} @Override รายการสาธารณะ <user> queryall () {return _userService.Queryall (); } @Override รายการสาธารณะ <user> queryByName (ชื่อสตริง) {return _usERSERVICE.FINDBYNAME (ชื่อ); } @Override รายการสาธารณะ <user> querychildren (สตริง parentid) {return _userService.findByParentId (parentId); } @Override ผู้ใช้สาธารณะ GetUser (String userId) {return _usERSERVICE.FINDBYID (USERID); } @Override รายการสาธารณะ <user> queryByPage (int pageno, int pageSize, ผู้ใช้ผู้ใช้) {return null; - แพ็คเกจ com.my.service; นำเข้า java.util.list; นำเข้า org.springframework.beans.factory.annotation.autowired; นำเข้า org.springframework.stereotype.service; นำเข้า com.my.entity.user; Baseservice <user> {@autowired UserRepository _userRepository; รายการสาธารณะ <user> findByName (ชื่อสตริง) {return _userRepository.findByName (ชื่อ); } รายการสาธารณะ <user> findByParentId (String parentId) {return _userrepository.findByParentId (parentId); - แพ็คเกจ com.my.repository; นำเข้า java.util.list; นำเข้า com.my.entity.user; อินเตอร์เฟสสาธารณะ userrepository ขยาย baseRepository <user> {รายการ <ผู้ใช้> findByName (ชื่อสตริง); รายการ <user> findByParentId (สตริง parentId);}ข้างต้นใช้แบบจำลองเลเยอร์ซึ่งค่อนข้างยุ่งยาก แต่ก็สะดวกกว่าในการปรับเปลี่ยนตรรกะทางธุรกิจของแต่ละชั้นในภายหลัง
คลาสที่เกี่ยวข้องกับ JPA มีดังนี้:
แพ็คเกจ com.my.service; นำเข้า java.io.serializable; นำเข้า Javax.persistence.entityManager; นำเข้า Javax.transaction.transactional; นำเข้า org.springframework.beans.factory.Antation.Autowired; คลาส Baseservice <e ขยาย serializable> {@autowired baseRepository <e> _BaseRepository; @autowired EntityManager Em; สาธารณะ e บันทึก (e baseUnit) {return _baseRepository.saveandflush (baseUnit); } การอัปเดตสาธารณะ e (e baseUnit) {return _baserepository.saveandflush (baseunit); } โมฆะสาธารณะ DELETEBYID (String ID) {_BaserePository.delete (ID); } สาธารณะ java.util.list <E> queryall () {return _baserepository.findall (); } สาธารณะ e findById (รหัสสตริง) {return _baserepository.getone (id); - แพ็คเกจ com.my.repository; นำเข้า java.io.serializable; นำเข้า org.springframework.data.jpa.repository.jparepository; นำเข้า org.springframework.data.repository.norepositorybean; serializable> {}ระดับเอนทิตี: เกี่ยวข้องกับฟิลด์ฐานข้อมูลคุณต้องให้ความสนใจกับคำอธิบายประกอบในคลาสแม่ @MappedSuperClass
แพ็คเกจ com.my.entity; นำเข้า java.util.arraylist; นำเข้า java.util.list; นำเข้า Javax.persistence.entity; นำเข้า Javax.persistence.manytomany; นำเข้า org.hibernate.annotations.dynamicinsert; org.hibernate.validator.constraints.email; @Entity (name = "db_user")@dynamicinsert@dynamicupdatePublic ผู้ใช้ระดับขยาย baseUnit { / *** สถานะบัญชี* / enum enum enum enum Statatus -3101319619397064425L; รหัสผ่านสตริงส่วนตัว เกลือสตริงส่วนตัว / ** สถานะบัญชี*/ สถานะบัญชีส่วนตัว; / ** อีเมลการรับรองความถูกต้อง*/ @email (message = "user.email แอตทริบิวต์ต้องปฏิบัติตามรูปแบบอีเมล") อีเมลสตริงส่วนตัว; / ** หมายเลขโทรศัพท์มือถือ*/ สตริงส่วนตัว Mobileno; / ** หมายเลขรหัส*/ สตริงส่วนตัว cardid; @Manytomany (TargetEntity = Role.class) รายการส่วนตัว <String> Roleids; /** ชื่อเล่น ไม่จำเป็น. */ ชื่อเล่นสตริงส่วนตัว; สตริงสาธารณะ getCardid () {return cardid; } สตริงสาธารณะ getEmail () {ส่งคืนอีเมล; } สตริงสาธารณะ getMobileno () {return mobileno; } สตริงสาธารณะ getNickName () {return ชื่อเล่น; } สตริงสาธารณะ getPassword () {ส่งคืนรหัสผ่าน; } รายการสาธารณะ <String> getRoleids () {ถ้า (roleids == null) {roleids = new ArrayList <> (); } return Roleids; } สตริงสาธารณะ getSalt () {กลับเกลือ; } Public AccountStatus getStatus () {สถานะการส่งคืน; } โมฆะสาธารณะ setCardid (สตริง cardid) {this.cardid = cardid; } โมฆะสาธารณะ setEmail (อีเมลสตริง) {this.email = อีเมล; } โมฆะสาธารณะ setMobileno (สตริง mobileno) {this.mobileno = mobileno; } โมฆะสาธารณะ setNickName (ชื่อเล่นสตริง) {this.nickName = ชื่อเล่น; } โมฆะสาธารณะ setPassword (รหัสผ่านสตริง) {this.password = รหัสผ่าน; } โมฆะสาธารณะ setroleids (รายการ <String> RoleIds) {this.roleids = roleids; } โมฆะสาธารณะ setSalt (เกลือสตริง) {this.salt = เกลือ; } โมฆะสาธารณะ setStatus (สถานะบัญชี) {this.status = สถานะ; - แพ็คเกจ com.my.entity; นำเข้า java.io.serializable; นำเข้า java.util.date นำเข้า Javax.persistence.id; นำเข้า Javax.persistence.mappedsuperclass; นำเข้า Javax.validation.constraints.notnull; org.springframework.data.annotation.createdby; นำเข้า org.springframework.data.annotation.createddate; นำเข้า org.springframework.data.annotation.lastmodifiedby; ดำเนินการ serializable {@id @notnull String String id; / ** * รหัสหน่วยหลัก */ @Size (สูงสุด = 32, message = "baseUnit.parentId ความยาวแอตทริบิวต์ไม่สามารถมากกว่า 32") สตริงสาธารณะ parentid; / ** ประเภทของหน่วยแม่*/ parenttype parenttype สาธารณะ; / *** ชื่อหน่วย*/ @NotNull (message = "baseUnit.name แอตทริบิวต์ไม่สามารถว่างเปล่า") ชื่อสตริงสาธารณะ; @CreatedBy Public String CreateBy; @CreatedDate วันที่สาธารณะสร้างขึ้น; @lastmodifiedby สตริงสาธารณะ LastModifiedBy; / *** วันที่อัปเดตล่าสุด*/ @lastmodifieddate วันที่สาธารณะ LastModifiedDate; สตริงสาธารณะ getId () {return id; } โมฆะสาธารณะ setId (รหัสสตริง) {this.id = id; } / *** รับชื่อของหน่วย** @return ต้องการ* / สตริงสาธารณะ getName () {ชื่อคืน; } / ** * * @return UUID ไม่รวม {} และ - * / สตริงสาธารณะ getParentId () {return parentId; } public ParentType getParentType () {return parentType; } สตริงสาธารณะ getStationId () {return stationId; } Public String getThumbNailId () {return thumbnailid; } สตริงสาธารณะ getCreateBy () {return createBy; } โมฆะสาธารณะ setCreateBy (String createBy) {this.createBy = createBy; } วันที่สาธารณะ getCreatedate () {return complementate; } โมฆะสาธารณะ setCreatedate (วันที่ที่สร้างขึ้น) {this.createdate = สร้างขึ้น; } / ** * ตั้งชื่อของหน่วย * * @param ชื่อ * ต้องการ * / โมฆะสาธารณะ setName (ชื่อสตริง) {this.name = name; } / ** * ตั้งค่ารหัสหน่วยแม่ * * @param parentid * uuid ไม่รวม {} และ - * / โมฆะสาธารณะ setParentId (สตริง parentId) {this.parentId = parentId; } สตริงสาธารณะ getLaStModifiedBy () {return lastModifiedBy; } โมฆะสาธารณะ setLastModifiedBy (สตริง lastModifiedBy) {this.lastModifiedBy = lastModifiedBy; } วันที่สาธารณะ getLaStModifiedDate () {return lastModifiedDate; } โมฆะสาธารณะ setLastModifiedDate (วันที่ lastModifiedDate) {this.lastModifiedDate = lastModifiedDate; -ไฟล์กำหนดค่า:
เซิร์ฟเวอร์: พอร์ต: 16800 ContextPath:/การบันทึก: config: ./config/logback.xml Spring: http: Multipart: เปิดใช้งาน: DataSource: url: jdbc: mysql: //127.0.0.1: 3306/db? com.mysql.jdbc.driver jpa: ฐานข้อมูล: mysql show-sql: true hibernate: ddl-auto: อัปเดต Jackson: serialization: indent_output: จริง
#Hibernate: พฤติกรรมเฉพาะของคลาสเอนทิตีที่รักษาโครงสร้างตารางฐานข้อมูล การอัปเดตหมายความว่าเมื่อคุณสมบัติของการเปลี่ยนแปลงคลาสเอนทิตีโครงสร้างตารางจะได้รับการปรับปรุง ที่นี่เราสามารถนำค่าสร้าง การสร้างนี้หมายความว่าตารางที่สร้างขึ้นล่าสุดถูกลบเมื่อเริ่มต้นและสร้างตารางใหม่ตามคลาสเอนทิตี ในเวลานี้ข้อมูลในตารางก่อนหน้าจะถูกล้าง นอกจากนี้ยังสามารถใช้ค่าสร้างการวางซึ่งหมายความว่าตารางถูกสร้างขึ้นตามคลาสเอนทิตีเมื่อเริ่มต้น แต่เมื่อปิดเซสชันการปิดตารางจะถูกลบ การตรวจสอบหมายความว่าคลาสเอนทิตีและตารางข้อมูลมีความสอดคล้องกันเมื่อเริ่มต้น ไม่มีหมายความว่าไม่มีอะไรทำ #show-sql หมายถึง hibernate พิมพ์คำสั่ง SQL จริงบนคอนโซลเมื่อใช้งาน #jackson หมายถึงสตริงเอาต์พุต json ที่จัดรูปแบบ
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น