คำนำ
วันนี้ฉันจะตรวจสอบการก่อสร้าง SpringMVC+Hibernate ตอนแรกฉันคิดว่ากรอบการควบคุมการอนุญาตความปลอดภัยในฤดูใบไม้ผลิจะรวมอยู่ในนั้น แต่ฉันพบว่ามีเนื้อหามากเกินไป ปล่อยให้บทความถัดไป บทความนี้ส่วนใหญ่สร้าง SpringMVC4.1.4 และ Hibernate4.3.8 ฉันเคยใช้ SpringMVC มาก่อน ส่วนนี้คุ้นเคยกับมันมาก ท้ายที่สุด SpringMVC ได้รับการพัฒนามานานกว่าหนึ่งปี เวลานี้เลเยอร์การคงอยู่ใช้ไฮเบอร์เนตแหล่งข้อมูลใช้ C3P0 และฐานข้อมูลใช้ MySQL ชั่วคราว ฉันต้องการตรวจสอบไฮเบอร์เนตเป็นหลัก แนวคิดในการสร้างกรอบของ SpringMVC+Hibernate มีดังนี้:
1. ฐานข้อมูลการออกแบบ: ออกแบบโครงสร้างตารางที่ดีที่สุดที่จะตอบสนอง 3NF และใช้เครื่องมือไฮเบอร์เนตเพื่อสร้างเอนทิตีเอนทิตีที่สอดคล้องกันโดยอัตโนมัติ
1. สร้างโครงการ Maven และป้อนการพึ่งพาแพ็คเกจ Maven ตามต้องการ
2. สร้างสปริง: กำหนดค่าสปริงฉีดถั่วชั้นควบคุม
3. สร้างไฮเบอร์เนต: กำหนดค่าแหล่งข้อมูลกำหนดค่าเซสชัน factory กำหนดค่าการทำธุรกรรมและกำหนดค่าแคชรอง Ehcache
4. ทดสอบการก่อสร้างเฟรมเวิร์กของฤดูใบไม้ผลิ+ไฮเบอร์เนตเขียนหน่วยทดสอบ Junit, การกำหนดค่าการทำธุรกรรมการทดสอบ ฯลฯ
5. อินพุต SpringMVC: กำหนดค่าข้อมูลการกำหนดค่า SpringMVC
6. กำหนดค่า Web.xml Container
7. ทดสอบการรวมของสามเฟรมเวิร์ก: Maven Compiles, แพ็คเกจและการปรับใช้เซิร์ฟเวอร์และการทดสอบ
1. การออกแบบฐานข้อมูล
ออกแบบตารางการอนุญาตบทบาทและผู้ใช้ แน่นอนหากผู้ใช้สามารถมีหลายบทบาทบทบาทหนึ่งเป็นเจ้าของผู้ใช้หลายคน บทบาทหนึ่งมีหลายสิทธิ์และหนึ่งสิทธิ์สอดคล้องกับหลายบทบาท ดังนั้นตามการออกแบบโครงสร้างตารางฐานข้อมูลหากตรงกับ 3NF เราต้องมี 5 ตารางที่จะมีอยู่ ข้อมูลเฉพาะของตารางไม่ได้อยู่ในรายการ (คุณสามารถดาวน์โหลดได้ในซอร์สโค้ดและยังมีฐานข้อมูลอยู่ในนั้น) และความสัมพันธ์ของตารางมีดังนี้:
เฉพาะใน ID นี้คือ UUID (36 บิต)
2. สร้างโครงการ maven และเขียนไฟล์ pom.xml
สร้างโครงการ Maven Webapp เขียนไฟล์ pom.xml และแนะนำการพึ่งพาแพ็คเกจที่จำเป็น ฉันจะทำแผนที่ทั้งหมดที่ต้องการที่นี่
เนื้อหาของไฟล์ pom.xml มีดังนี้:
<Project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http:/MANCMMMMMMMMMMMMMMMMMMMMMMMMMMBM http://maven.apache.org/maven-v4_0_0.xsd "> <modersion> 4.0.0 </modelversion> <roupid> org.andy.sh </groupid> <ratifactid> SpringMvc_Hibernate_demo </Artifactid> <name> springmvc_hibernate_demo maven webapp </name> <url> http://maven.apache.org </url> <properties> <project.build.sourceencoding> utf-8 </project.build.sourceencoding> <hibernate.version> 4.3.8.final </hibernate.version> <jackson.version> 2.5.0 </jackson.version> </premerties> <pendencies> <!-junit-> <pendency> <derctid> junit </groupid> <!-ฤดูใบไม้ผลิ-> <การพึ่งพา> <roupId> org.springframework </groupId> <ratifactId> Spring-core </artifactid> <persion> $ {spring.version} </เวอร์ชัน> </predency> <cerson> $ {spring.version} </version> </การพึ่งพา> <การพึ่งพา> <loupId> org.springframework </groupId> <ratifactid> Spring-context </artifactid> <version> $ {Spring.version} </เวอร์ชัน> <ArtIfactId> Spring-Tx </artifactId> <persion> $ {Spring.version} </เวอร์ชัน> </การพึ่งพา> <การพึ่งพา> <roupId> org.springframework </groupId> <atifactid> Spring-Web </artifactid> <RoupID> org.springFramework </groupId> <ratifactId> การทดสอบสปริง </artifactId> <cerson> $ {Spring.version} </pred> <pope> ทดสอบ </cope> </predency> <! <ArtIfactId> Spring-WEBMVC </artIfactId> <persion> $ {spring.version} </Serve> </การพึ่งพา> <!-เมื่อรวมฐานข้อมูลเชิงสัมพันธ์คุณต้องกำหนดค่าเช่น Hibernate JPA -> <predency> <roupId> org.springframework </groupId> <ratifactId> สปริง-orm </artifactid> <cerson> $ {Spring.version} </senture> </derpendency> <!-hibernate-> <predency> <cersion> $ {hibernate.version} </version> </การพึ่งพา> <การพึ่งพา> <loupId> org.hibernate </groupId> <ratifactid> hibernate-ehcache </artifactid> <persion> $ {hibernate.version} <RoupID> net.sf.ehcache </groupId> <ratifactid> ehcache </artifactid> <cersion> 2.9.0 </เวอร์ชัน> </การพึ่งพาอาศัย> <!-log4j-> <cendency> <roupid> log4j </groupid> <การพึ่งพา> <roupId> mysql </groupId> <ratifactId> mysql-connector-java </artifactid> <sersion> 5.1.34 </version> </derness> <!-แหล่งข้อมูล C3P0-> </permentency> <!-JSON-> <การพึ่งพา> <roupId> com.alibaba </groupId> <ratifactId> fastjson </artifactid> <cersion> 1.2.3 </เวอร์ชัน> </perctidency> <Sersion> $ {Jackson.Version} </Sident> </การพึ่งพา> <การพึ่งพา> <roupId> com.fasterxml.jackson.core </groupid> <ratifactid> Jackson-Core </artifactid> <version> $ {Jackson.Version} <ArtIfactId> Jackson-Databind </artifactId> <sersion> $ {Jackson.version} </Side> </การพึ่งพา> <!-AOP-> <การพึ่งพาอาศัย> <roupId> org.aspectj </groupid> <ratifactid> <RoupID> javax.servlet </groupId> <ratifactId> servlet-api </artifactid> <sersion> 3.0-alpha-1 </version> <pope> ให้ </cope> </predency> </perencies> <uffect> <mavenname> <plugins> <!-เรียกใช้การทดสอบหน่วย Junit ในคลาสที่แยกได้-> <plugin> <การกำหนดค่า> <SkipTestS> True </SkipTestS> </การกำหนดค่า> </plugin> <plugin> <loupid> org.apache.maven.plugins </groupId> <swexml> src/main/webapp/web-inf/web.xml </webxml> </การกำหนดค่า> </plugin> <!-สร้าง Java doc-> <plugin> <loupid> org.apache.maven.plugins </groupid> <JavadocDirectory> Target/javadoc </javadocDirectory> <solormeOututputDirectory> เป้าหมาย/Javadoc </reportoutputDirectory> <parset> UTF-8 </charset> <coding> UTF-8 </encoding> ปรับใช้เป็นแบบดั้งเดิม-> <plugin> <roupId> org.codehaus.cargo </groupId> <ratifactid> Cargo-Maven2-Plugin </artifactid> <sersion> 1.0 </เวอร์ชัน> <การกำหนดค่า> <atainer> </container> <การกำหนดค่า> <ply> ที่มีอยู่ </type> <mome> d: /webserver/apache-tomcat-6.0.39 </ome> </การกำหนดค่า> </การกำหนดค่า> </plugin>3. แนะนำการกำหนดค่าสปริง
เขียนไฟล์การกำหนดค่าและวางไฟล์การกำหนดค่าในไดเรกทอรี SRC/Main/Resource Resource (เดียวกันด้านล่าง)
ข้อมูลการกำหนดค่าที่ต้องการโดยโครงการ config.properties
#Application configs#jdbc c3p0 configjdbc.driver = com.mysql.jdbc.driverjdbc.url = jdbc: mysql: // localhost: 3306/work? useunicode = true & riblementencoding = utf-8jdbc.username = rootjdbc. org.hibernate.dialect.mysqldialecthibernate.show_sql = truehibernate.format_sql = talsehibernate.hbm2ddl.auto = updiefhibernate.cache.use_second_level_cache = treanhibernate.cachet.cachet.cachet.cashe.cashe.cache.s org.hibernate.cache.ehcache.ehcacheregionfactoryhibernate.cache.provider_configuration_file_resource_path = ehcache.xml
3.1. การกำหนดค่าสปริง
ไฟล์กำหนดค่าของ Spring.xml มีดังนี้:
<? xml version = "1.0" การเข้ารหัส = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://ww.w3.org/2001/xml xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <! Bean-> <บริบท: Component-Scan base-package = "org.andy.work.service.impl, org.andy.work.dao.impl" /> </epeans>
สปริงด้านบนกำหนดค่าการจัดการการฉีดถั่วอัตโนมัติของถั่วส่วนประกอบที่เกี่ยวข้องภายใต้แพ็คเกจ เราจำเป็นต้องส่งมอบคลาสการใช้งานของ DAO และบริการเพื่อฤดูใบไม้ผลิเพื่อจัดการเช่น (@Repository, @Service)
3.2. แนะนำการกำหนดค่าไฟล์บันทึก log4j
ไฟล์การกำหนดค่าของ log4j.properties มีดังนี้: ### ตั้งค่าระดับบันทึก ### log4j.rootlogger = ข้อมูล, c, d, e ### คอนโซล ### log4j.appender.c = org.apache.log4j.consolependerlog4j.appender.c org.apache.log4j.patternlayoutlog4j.appender.c.layout.conversionPattern = [springmvc_hibernate_demo] [%p] [%-d {yyyy-mm-dd hh: mm: ss}]%C.%m (%l) | %m%n ### ไฟล์บันทึก ### log4j.appender.d = org.apache.log4j.dailyrollingFilePenderLog4j.appender.d.file = ../logs/springmvc_hibernate_demo.loglog4j.appender log4j.appender.d.layout = org.apache.log4j.patternlayoutlog4j.appender.d.layout.conversionPattern = [springmvc_hibernate_demo] [%p] [%-d {yyyy-mm-dd HH: MM: SS}] %m%n ### ยกเว้น ### log4j.appender.e = org.apache.log4j.dailyrollingFilePenderlog4j.appender.e.file = ../logs/springmvc_hibernate_demo_error.loglog4j.appender.epend. log4j.appender.e.layout = org.apache.log4j.patternlayoutlog4j.appender.e.layout.conversionPattern = [sspringmvc_hibernate_demo] [%p] [%-d {yyyy-mm-dd: mm: ss} %m%n 4. การกำหนดค่าไฮเบอร์เนต
การกำหนดค่าของไฮเบอร์เนตส่วนใหญ่รวมถึง: การกำหนดค่าแหล่งข้อมูล C3P0 การกำหนดค่า SessionFactory การกำหนดค่าตัวจัดการธุรกรรมและการกำหนดค่าการจัดการธุรกรรม ไฟล์ Spring-hibernate.xml มีดังนี้:
<? xml version = "1.0" การเข้ารหัส = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://ww.w3.org/2001/xml xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalocation = "http:/ http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://ww.springframework http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1. id = "dataSource" destroy-method = "close"> <property name = "driverclass" value = "$ {jdbc.driver}" /> <property name = "jdbcurl" value = "$ {jdbc.url}" /> value = "$ {jdbc.password}" /> <!-การหมดเวลาขอหมดเวลา-> <property name = "CheckOutTimeOut" value = "30000" /> <!-ตรวจสอบการเชื่อมต่อที่ไม่ได้ใช้งานทั้งหมดในพูลเชื่อมต่อทุก 60 วินาที ค่าเริ่มต้น: 0, ไม่ตรวจสอบ-> <property name = "IdleConnectionTestPeriod" value = "30" /> <!-เวลาว่างสูงสุดสำหรับการเชื่อมต่อฐานข้อมูลการเชื่อมต่อพูลการเชื่อมต่อ-> <ชื่อคุณสมบัติ = "maxidLetime" value = "30" /> <! /> <property name = "maxPoolSize" value = "20" /> <!- จำนวนการเชื่อมต่อที่ได้รับจาก C3P0 ในเวลาเดียวกันในครั้งเดียวเมื่อการเชื่อมต่อในพูลเชื่อมต่อหมด ค่าเริ่มต้น: 3-> <property name = "AcquireIncrement" value = "5" /> </ebean> <!-กำหนดค่า Hebernate SessionFactory-> <bean id = "SessionFactory"> <!-ดูซอร์สโค้ดสำหรับการฉีดวัคซีน-> <props> <prop key = "hibernate.dialect"> $ {hibernate.dialect} </prop> <prop key = "hibernate.show_sql"> $ {hibernate.show_sql} </prop> key = "hibernate.hbm2ddl.auto"> $ {hibernate.hbm2ddl.auto} </prop> <!-เปิดแคชระดับ 2 Ehcache-> <prop key = "hibernate.cache.use_second_level_cache" key = "hibernate.cache.use_query_cache"> $ {hibernate.cache.use_query_cache} </prop> <prop key = "hibernate.cache.region.factory_class"> $ {hibernate.cache.region.factory_class key = "hibernate.cache.provider_configuration_file_resource_path"> $ {hibernate.cache.provider_configuration_file_resource_path} </props> </props> </คุณสมบัติ> <! value = "org.andy.work.entity" /> </ebean> <!-กำหนดค่าตัวจัดการธุรกรรม-> <bean id = "transactionManager"> <property name = "SessionFactory" ref = "SessionFactory" /> </epean> <! กำหนดค่าความหมายการประมวลผลธุรกรรมโดยละเอียด-> <tx: แอตทริบิวต์> <tx: method name = "แทรก*" การแพร่กระจาย = "จำเป็น" /> <tx: method name = "update*" การแพร่กระจาย = "จำเป็น" /> <tx: method = "ลบ*" การสนับสนุน-"tx- name = "find*" การแพร่กระจาย = "สนับสนุน" read-only = "true" /> <tx: method name = "find*" การแพร่กระจาย = "สนับสนุน" read-only = "true" /> <!-คนอื่นใช้วิธีการทำธุรกรรมเริ่มต้น-> <tx: method = "*" /> pointcut-> <aop: pointcut id = "transactionpointcut" expression = "การดำเนินการ (*org.andy.work.service ..*Impl.*(.. ))" /> <! </aop: config> </ beans> ข้างต้นได้รับการกำหนดค่าด้วยแคชทุติยภูมิและ ehcache สำหรับข้อมูลเฉพาะที่เกี่ยวข้องโปรดดูบทความก่อนหน้านี้แคชทุติยภูมิ Hibernate และการกำหนดค่าการก่อสร้าง Ehcache ต่อไปนี้คือการกำหนดค่าของแคชรอง
4.1. การกำหนดค่า ehcache.xml
<? xml เวอร์ชัน = "1.0" การเข้ารหัส = "utf-8"?> <ehcache xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: nonamespaceschemalocation = " การตั้งค่า defaultcache -> <defaultCache maxElementsInMemory = "1,000" Eternal = "false" timetoidleseconds = "120" timetoLiveSeconds = "120" maxElementOndisk = "1000000" การตั้งค่า OverflowTodisk = "True" MemoryStoreEvictionPolicy = "LRU" -> <cache name = "org.andy.work.entity.acctuser" MaxElementsInMemory = "2" MemoryStoreEvictionPolicy = "LRU" Eternal = "true" diskpersistent = "false" overflowTodisk =
แคชทุติยภูมิไฮเบอร์เนตข้างต้น ehcache คือ d:/ehcache
5. สร้างกิจการธุรกิจ
หลังจากออกแบบตารางข้อมูลเอนทิตีไฮเบอร์เนตจะมีเครื่องมือไฮเบอร์เนตที่สร้างขึ้นโดยอัตโนมัติ Eclipse ต้องการการติดตั้งปลั๊กอินเครื่องมือไฮเบอร์เนต (ฉันติดตั้งออนไลน์หลายครั้ง แต่ไม่ประสบความสำเร็จขอแนะนำให้ใช้ลิงก์เพื่อติดตั้งออฟไลน์และภาคผนวกจะแนะนำ) ดังนั้นจึงไม่จำเป็นต้องเขียนด้วยตนเอง นี่คือเอนทิตีที่มีข้อมูลผู้ใช้ acctuser.java
แพ็คเกจ org.andy.work.entity; // สร้าง 2015-2-3 10:43:00 โดยเครื่องมือไฮเบอร์เนต 4.0.0Import java.util.date นำเข้า java.util.hashset; นำเข้า java.util.set; นำเข้า Javax.persistence.column javax.persistence.id; นำเข้า Javax.persistence.joincolumn; นำเข้า Javax.persistence.jointable; นำเข้า Javax.persistence.manytomany; นำเข้า Javax.persistence.Table; org.hibernate.annotations.cache; นำเข้า org.hibernate.annotations.cacheconcurrencystrategy; นำเข้า com.fasterxml.jackson.annotation.jsonignoreproperties; cacheconcurrencystrategy.read_write) คลาสสาธารณะ acctuser ใช้ java.io.serializable { / ** * * * / ส่วนตัวคงที่สุดท้ายสุดท้าย serialversionuid = 6980093847795726310L; รหัสสตริงส่วนตัว; ชื่อเล่นสตริงส่วนตัว; โทรศัพท์สตริงส่วนตัว เวลาลงทะเบียนวันที่ส่วนตัว ชุดส่วนตัว <Cctrole> acctroles = new hashset <Cctrole> (0); Public Acctuser () {} Public Acctuser (String ID, String NickName) {this.id = id; this.nickName = ชื่อเล่น; } Public AcctUser (String ID, String NickName, String โทรศัพท์, วันที่ลงทะเบียนเวลา, ตั้งค่า <cctrole> acctroles) {this.id = id; this.nickName = ชื่อเล่น; this.telephone = โทรศัพท์; this.registertime = registertime; this.acctroles = acctroles; } @id @column (name = "id", ไม่ซ้ำกัน = true, nullable = false, length = 36) public String getId () {return this.id; } โมฆะสาธารณะ setId (รหัสสตริง) {this.id = id; } @column (name = "nick_name", nullable = false) สตริงสาธารณะ getNickName () {return this.nickName; } โมฆะสาธารณะ setNickName (ชื่อเล่นสตริง) {this.nickName = ชื่อเล่น; } @column (name = "โทรศัพท์") สตริงสาธารณะ getTelephone () {return this.telephone; } โมฆะสาธารณะ setTelephone (โทรศัพท์สตริง) {this.telephone = โทรศัพท์; } @temporal (temporaltype.timestamp) @column (name = "register_time", ความยาว = 19) วันที่สาธารณะ getregistertime () {return this.registertime; } โมฆะสาธารณะ setregistertime (วันที่ลงทะเบียน) {this.registertime = registertime; } @jsonignoreproperties (value = {"acctusers", "acctauthorities"}) @Manytomany (fetch = fetchType.lazy) @cache (การใช้งาน = cacheconcurrencystrategy.read_write) @jointable (name = "acct_user_role "user_id", nullable = false, updateable = false)}, inversejoincolumns = {@joincolumn (name = "role_id", nullable = false, updatable = false)}) ชุดสาธารณะ <Ictrole> getActroles () } โมฆะสาธารณะ setAcctroles (SET <Cctrole> acctroles) {this.acctroles = acctroles; - มีบางสิ่งที่ควรทราบด้านบน:
ส่วนใหญ่ข้างต้นจะถูกสร้างขึ้นโดยอัตโนมัติโดยเครื่องมือไฮเบอร์เนต แต่มีหลายอย่างที่ต้องเพิ่มด้วยตนเอง:
1. หากเอนทิตีนี้ใช้แคชระดับ 2 คุณต้องเพิ่มคำอธิบายประกอบ @Cache;
2. หากมีองค์ประกอบที่ตั้งค่า (ตั้ง, แผนที่, รายการ) ในเอนทิตีและหากเอนทิตีต้องการใช้แคชทุติยภูมิองค์ประกอบชุดเหล่านี้จะต้องเพิ่มด้วย @cache คำอธิบายประกอบ
3. @JSONIGNOREPROPERTIES คำอธิบายประกอบคือการป้องกันไม่ให้ SpringMVC ผลิตเอาท์พุทลูปเมื่อ JSON กลับมา หากไม่ได้รับการกำหนดค่า JSON Dead Loop จะเกิดขึ้น (และคุณสมบัติแบบหนึ่งต่อหลายต่อหลายคน)
4. @jsonignore กำลังแปลงเป็น JSON เพื่อเพิกเฉยต่อทรัพย์สินนี้ในขณะที่ @JSONIGNOREPROPERTIES (value = {"AcctUsers", "AcctAuthorities"}) ละเว้นคุณสมบัติของผู้ใช้งาน
6. สร้างเลเยอร์ Dao
6.1dao อินเทอร์เฟซ
เราต้องนำแนวคิดของการเขียนโปรแกรมอินเทอร์เฟซใบหน้าในชั้น DAO และชั้นบริการดังนั้นเราจึงกำหนดอินเทอร์เฟซ DAO ทั่วไปก่อนทั่วไป GenericDao.java
แพ็คเกจ org.andy.work.dao; นำเข้า java.io.serializable; นำเข้า java.util.list;/** * เวลาที่สร้างขึ้น: 2015-2-6 2:26:42 PM * * @author Andy * @version 2.2 * * Dao ทั่วไป t รับ (pk id); รายการ <t> findall (); โมฆะคงอยู่ (t เอนทิตี); PK Save (T เอนทิตี); เป็นโมฆะ saveorupdate (t เอนทิตี); เป็นโมฆะลบ (PK ID); เป็นโมฆะฟลัช ();}
กำหนดอินเทอร์เฟซ userdao.java เฉพาะ
แพ็คเกจ org.andy.work.dao; นำเข้า org.andy.work.entity.acctuser;/** * เวลาการสร้าง: 2015-2-6 2:43:50 PM * * @author Andy * @version 2.2 * * ผู้ใช้อินเทอร์เฟซ Dao */อินเตอร์เฟสสาธารณะ
6.2. คลาสการใช้งานเลเยอร์ DAO
เราจำเป็นต้องฉีดคลาสการใช้งานของชั้น DAO ลงในถั่วดังนั้นเราจึงต้องเพิ่มคำอธิบายประกอบ @Repository, UserDaoImpl มีดังนี้:
แพ็คเกจ org.andy.work.dao.impl; นำเข้า java.util.list; นำเข้า org.andy.work.dao.userdao; นำเข้า org.andy.work.entity.acctuser; นำเข้า org.hibernate.session; org.springframework.stereotype.repository;/** * เวลาการสร้าง: 2015-2-6 2:45:14 PM * * @author Andy * @version 2.2 */ @repository ("userdao") ชั้นเรียนสาธารณะ userdaoimpl เซสชั่นส่วนตัว getCurrentSession () {ส่งคืนสิ่งนี้ sessionFactory.getCurrentsession (); } @Override Public Acctuser Load (String ID) {return (acctuser) this.getCurrentsession (). load (acctuser.class, id); } @Override สาธารณะ acctuser รับ (string id) {return (acctuser) this.getCurrentsession (). get (acctuser.class, id); } @suppresswarnings ("ไม่ได้ตรวจสอบ") @Override List <Acctuser> findall () {list <Cctuser> acctusers = this.getCurrentsession () CreateQeerery ("จาก Acctuser"). setCacheable (จริง). คืนค่า acctusers; } @Override โมฆะสาธารณะคงอยู่ (acctuser entity) {this.getCurrentsession (). คงอยู่ (เอนทิตี); } @Override สตริงสาธารณะบันทึก (acctuser entity) {return (string) this.getCurrentsession (). บันทึก (เอนทิตี); } @Override โมฆะสาธารณะ saveOrUpdate (acctuser entity) {this.getCurrentsession (). saveOrUpdate (เอนทิตี); } @Override โมฆะสาธารณะลบ (รหัสสตริง) {acctuser entity = this.load (id); this.getCurrentSession (). ลบ (เอนทิตี); } @Override โมฆะสาธารณะฟลัช () {this.getCurrentsession (). flush (); -7. สร้างเลเยอร์บริการ
7.1. อินเทอร์เฟซเลเยอร์บริการ
แพ็คเกจ org.andy.work.service; นำเข้า java.util.list; นำเข้า org.andy.work.entity.acctuser;/** * เวลาการสร้าง: 2015-2-6 3:18:57 PM * * @author Andy * @version 2.2 * ผู้ใช้ Acctuser Get (String ID); รายการ <Cctuser> findall (); โมฆะคงอยู่ (เอนทิตีของผู้ใช้); สตริงบันทึก (เอนทิตี ACCTUSER); ถือเป็นโมฆะ saveorupdate (เอนทิตีของ Acctuser); เป็นโมฆะลบ (รหัสสตริง); เป็นโมฆะฟลัช ();}
7.2. คลาสการใช้งานชั้นบริการ
UserserViceImpl ต้องฉีดถั่วเลเยอร์ DAO ที่กำหนดไว้ข้างต้น
แพ็คเกจ org.andy.work.service.impl; นำเข้า java.util.list; นำเข้า org.andy.work.dao.userdao; นำเข้า org.andy.work.entity.acctuser; นำเข้า org.andy.work.service.service; org.springframework.stereotype.service;/** * เวลาการสร้าง: 2015-2-6 3:24:16 PM * * @author Andy * @version 2.2 การใช้งานผู้ใช้บริการ */ @บริการ ("ผู้ใช้") ผู้ใช้ชั้นเรียนสาธารณะ @Override Public Acctuser Load (String ID) {return userdao.load (id); } @Override Public Acctuser Get (String ID) {return userdao.get (id); } @Override รายการสาธารณะ <Acctuser> findall () {return userdao.findall (); } @Override โมฆะสาธารณะคงอยู่ (acctuser entity) {userdao.persist (เอนทิตี); } @Override สตริงสาธารณะบันทึก (acctuser entity) {return userdao.save (เอนทิตี); } @Override โมฆะสาธารณะ saveOrUpdate (เอนทิตี ACCTUSER) {userDao.SaveOrUpDate (เอนทิตี); } @Override โมฆะสาธารณะลบ (รหัสสตริง) {userdao.delete (id); } @Override โมฆะสาธารณะฟลัช () {userdao.flush (); -8. ทดสอบการรวมสปริงและไฮเบอร์เนต
เราสามารถเขียนคลาสทดสอบใน SRC/Test/Java เพื่อทดสอบการกำหนดค่าข้างต้น หากการทดสอบสำเร็จโดยทั่วไปจะเสร็จสิ้น
แพ็คเกจ org.andy.work.service; นำเข้า java.util.date; นำเข้า java.util.list; นำเข้า java.util.uuid; นำเข้า org.andy.work.entity.acctuser; นำเข้า org.apache.log4j.logger; org.springframework.beans.factory.annotation.autowired; นำเข้า org.springframework.test.context.contextconfiguration; นำเข้า org.springframework.test.context.junit4.springjunit4classrunner; 3:31:07 PM * * @author Andy * @version 2.2 */ @runwith (springjunit4classrunner.class) @contextconfiguration (ตำแหน่ง = {"classpath: spring.xml", "classpath: spring-hibernate.xml"} .getLogger (testuserservice.class); @AutoWired Userservice Userservice; @Test โมฆะสาธารณะบันทึก () {ACCTUSER ACCTUSER = ใหม่ ACCTUSER (); acctuser.setid (uuid.randomuuid (). toString ()); acctuser.setNickName ("Andy"); acctuser.setRegistertime (วันที่ใหม่ ()); Acctuser.Settelephone ("1302222111111111); string id = userservice.save (acctuser); logger.info (json.tojsonstring (id)); -9. แนะนำ SpringMVC
เพิ่มไฟล์ Spring-MVC.XML
<? xml version = "1.0" การเข้ารหัส = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: mvc = "http://ww.springframework xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: บริบท = "http:/ XSI: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframwork http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/scthema <!-การสแกนอัตโนมัติ @controller ฉีดเป็นถั่ว-> <บริบท: คอมโพเนนต์ scan base-package = "org.andy.work.controller" /> <!-ต่อไปนี้คือการกำหนดค่า SpringMvc-> <MVC: การลงทะเบียน-ไดรฟ์-ไดรฟ์> <! name = "supportedediatypes"> <slist> <dalue> text/html; charset = utf-8 </value> <value> application/json; charset = utf-8 </alues> </list> </porement> </ebean> ชื่อ-> <bean> <property name = "viewClass" value = "org.springframework.web.servlet.view.jstlview"/> <property name = "คำนำหน้า" value = "/web-inf/views"/>
ตัวควบคุมการสแกนแพ็คเกจ [อีเมลป้องกัน] ��และการกำหนดค่าเลเยอร์ดูได้รับการกำหนดค่าด้านบน
10. กำหนดค่าคอนเทนเนอร์ web.xml
เว็บคอนเทนเนอร์เป็นสมองของโครงการเว็บดังนั้นคอนเทนเนอร์เว็บจึงต้องแนะนำฤดูใบไม้ผลิให้ฤดูใบไม้ผลิจัดการกรอบต่าง ๆ และฉีดเข้าไปในถั่ว จากนั้นกำหนดค่าข้อมูลตัวกรองของเลเยอร์ควบคุม และ URL ที่สกัดกั้นโดย SpringMVC ได้รับการกำหนดค่าให้เป็นคำขอที่ลงท้ายด้วย. HMLS
ไฟล์ web.xml มีดังนี้:
<? xml version = "1.0" การเข้ารหัส = "utf-8"?> <web-app xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://java.sun.com/xml xmlns: web = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2_5_5.xsd" XSI: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "webapp_id" เวอร์ชัน = "2.5" <param-name> contextconfiglocation </param-name> <param-value> classpath: spring.xml, classpath: spring-hibernate.xml </param- value> <Tilter-class> org.springframework.web.filter.characterencodingFilter </filter-class> <init-Param> <param-name> การเข้ารหัส </param-name> <param-value> UTF-8 </param-value> <param-value> true </param-value> </itrin-Param> </filter> <filter-mapping> <scod-name> encodingFilter </filter-name> <url-pattern>/*</url-pattern> <Tilter-Name> OpenSessionInViewFilter </filter-Name> <filter-class> org.springframework.orm.hibernate4.support.opensessionInviewFilter </filter-class> <int-param> <param-name> <!-ฟัง ServletContext และเริ่มต้นข้อมูลการกำหนดค่าสปริงใน contextConfigLocation-> <ผู้ฟัง> <Sistener-Class> org.springFramework.web.context.context.contextloaderListener </listener-class> </listener> </Listener> <!-ป้องกันไม่ให้หน่วยความจำฤดูใบไม้ผลิ Overflow Listener-> <Listener> <Sistener-Lass> org.springframework.web.util.introspectorCleanupListener </listener-class> </listener> <servlet> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <init-param> <param-name> contextconfiglocation </param-name> <! <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name> rest </servlet-name> <url-pattern>*. htmls </url-pattern> <url-pattern>*. htmls </url-pattern> </ตัวกรอง-แมป> <!-กำหนดค่าการหมดเวลาเซสชันในไม่กี่นาที-> <เซสชัน-config> <session-timeout> 30 </session-timeout> </ession-config>
11. สร้างตัวควบคุมเลเยอร์ควบคุม
การควบคุมเลเยอร์ usercontroller
แพ็คเกจ org.andy.work.controller; นำเข้า java.util.list; นำเข้า org.andy.work.entity.acctuser; นำเข้า org.andy.work.service.userservice; นำเข้า org.apache.log4j.logger; org.springframework.stereotype.controller; นำเข้า org.springframework.ui.modelmap; นำเข้า org.springframework.web.bind.annotation.pathvarible; นำเข้า org.springframework.web.bind.bind. org.springframework.web.bind.annotation.responsebody;/** * เวลาการสร้าง: 2015-2-7 11:49:00 am * @author Andy * @version 2.2 * คำอธิบาย: ตัวควบคุมผู้ใช้ */ @controller @requestmapping ("/user") @AutoWired Userservice Userservice; @RequestMapping("/showInfo/{userId}") public String showUserInfo(ModelMap modelMap, @PathVariable String userId){ LOGGER.info("Query user: " + userId); AcctUser userInfo = userService.load(userId); modelMap.addAttribute("userInfo", userInfo); return "/user/showInfo"; } @RequestMapping("/showInfos") public @ResponseBody List<AcctUser> showUserInfos(){ LOGGER.info("Query all users of the user"); List<AcctUser> userInfos = userService.findAll(); return userInfos; -12、创建视图层
在src/main/webapp/WEB-INF/views下创建user/showInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" src="js/jquery-1.9.1.min.js"></script><title>userInfo</title></head><body> User information nickname: ${userInfo.nickName} User id: ${userInfo.id} User phone: ${userInfo.telephone } Registration time: <fmt:formatDate value="${userInfo.registerTime }" pattern="yyyy-MM-dd HH:mm:ss" /> Role: [ <c:forEach items="${ userInfo.acctRoles}" var="role"> ${role.name } Permissions[ <c:forEach items="${ role.acctAuthorities}" var="authority"> ${authority.name } </c:forEach> ] </c:forEach> ] <br /> ajax displays all user information: <div id="show_all_user"></div></body><script type="text/javascript"> $.ajax({ type : "get", url : "user/showInfos.htmls", dataType : "json", success : function(data) { $(data).each( function(i, user) { var p = "<p>Nickname:" + user.nickName + " Phone:" + user.telephone + " Registration time:" + user.registerTime + " id:" + user.id + "</p>"; $("#show_all_user").append(p); - }, async : true });</script></html>13、部署服务器测试
使用Maven打包部署:clean compile package
部署到tomcat,测试主要测试上面的http://localhost:8080/springmvc_hibernate_demo/user/showInfo/6e5afb1d-50e1-45fe-b6fe-b9e399415387.htmls
和http://localhost:8080/springmvc_hibernate_demo/user/showInfos.htmls (json数据返回)
上面视图层就包含了这两条url请求的测试:
ok,到此Spring+SpringMVC+Hibernate搭建完毕。
博客来源:http://blog.csdn.net/fengshizty?viewmode=list
项目源码:http://download.csdn.net/detail/fengshizty/8432647
I hope to help friends in need and continue to add relevant information in the future. ขอบคุณสำหรับการสนับสนุนเว็บไซต์นี้!