تكامل إطار SSH
المقدمة: يقول بعض الناس أن الإطار السائد لا يزال يتمتع بشعبية الآن ، وقد خرج SSM لفترة طويلة ، ناهيك عن SSH. أنا لا أعتقد ذلك. في الوقت الحاضر ، لا تزال العديد من الشركات تستخدم SSH ، وإذا تغيرت إلى الأطر السائدة ، فسوف يكلف ذلك. على سبيل المثال ، في حقل تكنولوجيا المعلومات المالي ، يوصى باستخدام السبات في طبقة قاعدة البيانات لأنه يمكن تطويره بسرعة ، ما لم يكن الإنترنت. نظرًا لأنه يتضمن تزامنًا كبيرًا ، فإن طبقة قاعدة البيانات تستخدم MyBatis ، والتي لديها كفاءة تفاعل أسرع للبيانات. لذلك ، لا يمكن تجاهل SSH.
1. ما هو SSH
SSH هو إطار متكامل لـ Struts+Spring+Hibernate ، وهو حاليًا إطار شهير مفتوح المصدر لتطبيقات الويب.
ينقسم النظام الذي يدمج إطار SSH إلى أربع طبقات من حيث المسؤوليات: طبقة العرض ، طبقة منطق الأعمال ، طبقة ثبات البيانات وطبقة وحدة المجال لمساعدة المطورين على بناء تطبيقات الويب بهيكل واضح ، إعادة استخدام جيدة وصيانة مريحة على المدى القصير. من بينها ، يتم استخدام الدعامات كبنية تحتية إجمالية للنظام ، المسؤولة عن الفصل بين MVC ، وفي الجزء النموذجي من إطار الدعامات ، والتحكم في القفزات التجارية ، باستخدام إطار السبات لتوفير الدعم لطبقة الثبات ، يدير Spring SPRING ، الاكتئاب. النهج المحدد هو: استخدام طرق التحليل الموجهة للكائنات لاقتراح بعض النماذج وفقًا للاحتياجات ، وتنفيذ هذه النماذج ككائنات JAVA أساسية ، ثم اكتب واجهة DAO (كائنات الوصول إلى البيانات) الأساسية ، وإعطاء تنفيذ DAO من السبات. يتم استخدام فئة DAO التي تنفذها بنية السبات لتحقيق التحويل والوصول بين فئات Java وقواعد البيانات. أخيرًا ، يدير الربيع ويدير الدعامات وسبرات.
---------- Baidu Encyclopedia
2. الأجزاء المشاركة في SSH
3. النشر السريع للبيئة
هنا نستخدم عرضًا تجريبيًا صغيرًا لإنقاذ العملاء لإظهار تكامل SSH
1. استيراد حزمة الجرة المطلوبة
1). STRUTS2 الإطار
* Struts-2.3.24/Apps/Struts2-Lank/Web-Inf/lib/*. JAR-جميع حزم الجرة المطلوبة بواسطة Struts2
* Struts2-spring-plugin-2.3.24.jar --- Struts2 يدمج حزمة الإضافات الربيع
2). إطار السبات
* hibernate-release-5.0.7.final/lib/required/*.
* SLF4J-API-1.6.1.JAR-واجهة السجل
* SLF4J-LOG4J12-1.7.2.JAR-تطبيق السجل
* mysql-connector-java-5.1.7-bin.jar-mysql package
3). إطار الربيع
* حزمة IOC الأساسية
* حزمة AOP الأساسية
* قوالب JDBC وحزم المعاملات الأساسية
* Spring يدمج حزمة اختبار Junit
* Spring يدمج حزمة السبات الأساسية
* Spring يدمج الحزمة الأساسية Struts2
2. تكوين رمز الربيع والدعامات في web.xml
1) تكوين مرشح STRUTS2 الأساسي
يتم تعريف هذا على أنه اعتراض الجميع
<!-تكوين Core Filter-> <ilter> <filter-name> Struts2 </filter-name> <lipter-class> org.apache.struts2 <Url-pattern>/*</url-pattern> </filter-mapping>
2) تكوين مستمع الربيع
عند بدء الخدمة ، سيتم تحميل ملف تكوين الربيع أولاً
<!-قم بتكوين المستمع لـ Spring Framework Integrating Web-> <Stexer> <Canker-Class> org.springframework.web.context.contextloaderListener </stanterer-class> </nistener>
3) تكوين مسار التحميل الافتراضي
<!-يقوم المستمع بتحميل ملف Web-Inf افتراضيًا. تحتاج إلى تكوين المعلمات لتحميل الملف المحدد-> <context-param> <Param-name> contextConfigLocation </param-name> <param-value> classpath: applicationContext.xml </param-value> </sontext-param>
ملخص: جميع رموز web.xml
<!-قم بتكوين المستمع الذي يدمج الويب في إطار الربيع-> <Stexer> <stanker-class> org.springframework.web.context.contextLoaderListener </stanker-class> <//leader> <! <Param-name> contextConfigLocation </param-name> <Param-value> classpath: applicationContext.xml </parm-value> </sontext-param> <!-تكوين المرشحات الأساسية-> <filter> <Filter-Class> org.apache.struts2.dispatcher.ng.filter.strutspreparexecutefilter </filter-class> </filter> <filter mapping> <filter-name> struts2 </filter-name>
2. اكتب ملفات التكوين ذات الصلة ضمن SRC
1) الربيع: ApplicationContext.xml
استيراد القيود ذات الصلة
<؟ xmlns: context = "http://www.springframework.org/schema/context" XSI: Schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/sctxt http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> </beans>
2) Hibernate: hibernate.cfg.xml
استيراد القيود ذات الصلة وتكوين قاعدة البيانات
<؟ <Session-Factory> <!-يجب تكوين-> <property name = "hibernate.connection.driver_class"> com.mysql.jdbc.driver </splany> <property name = "hibernate.connection.url"> jdbc: mysql: //192.168.174.130: name = "hibernate.connection.username"> الجذر </property> <property name = "hibernate.connection.password"> الجذر </property name = "hibernate.dialect" name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Configure connection pool for C3P0 --> <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!-- Cannot configure operations that bind the current thread -> <!-ملف التعيين-> <mapping resource = "com/clj/domain/customer.hbm.xml"/> </session-factory> </hibernate-configuration>
3) تكوين log4j.properties
### رسائل السجل المباشر إلى stdout ### log4j.appender.stdout = org.apache.log4j.consoleAppenderLog4j.appender.stdout.target = system.errlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender.layout.layout.conversion ٪ C {1}: ٪ l - ٪ m ٪ n ### الرسائل المباشرة لتقديم mylog.log ### log4j.appender.file = org.apache.log4j.fileAppenderLog4j.appender.file = c/: mylog.loglog4j.appender.file.layout = org.apache.log4j.patternlayoutlog4j.appender.file.layout.layout ٪ C {1}: ٪ l - ٪ m ٪ n ### تعيين مستويات السجل - لمزيد من التسجيل المطوّل تغيير "المعلومات" إلى "debug" ### log4j.rotlogger = info ، stdout4) Struts2: Struts.xml
استيراد القيود ذات الصلة
<؟
ملخص: يتم عرض ملف التكوين المطلوب بواسطة SRC في الشكل
3. تكوين طبقة DAO
تحديد واجهة وفئة التنفيذ الخاصة بها
الواجهة العامة CustomerDao {public void save (عميل العميل) ؛} الطبقة العامة customerdaoimpl تنفذ customerdao {public void save (عميل العميل) {}}4. تحديد واجهة طبقة العمل وفئة التنفيذ
Package com.clj.service ؛ import com.clj.domain.customer ؛ public interface customervice {public void save (customer) ؛} package com.clj.service ؛ استيراد org.springframework.transaction.annotation.transactional ؛ استيراد com.clj.dao.customerdao ؛ استيراد com.clj.domain.customer ؛/** * طبقة عمل العميل * @Author Administrator * */public class plustomerviceimplpling {// ed {ed ender }}5. تحديد فئة Pojo
تقوم Hibernate بتشغيل جداول قاعدة البيانات عن طريق تشغيل فئات POJO لتحقيق تعيين الكائنات العلمية
Package com.clj.domain ؛ عميل الطبقة العامة {private long cust_id ؛ سلسلة خاصة cust_name ؛ خاص طويل cust_user_id ؛ خاص طويل cust_create_id ؛ سلسلة خاصة cust_source ؛ سلسلة خاصة cust_industry ؛ سلسلة خاصة cust_level ؛ سلسلة خاصة cust_linkman ؛ سلسلة خاصة cust_phone ؛ سلسلة خاصة cust_mobile ؛ Public GetCust_id () {return cust_id ؛ } public void setcust_id (long cust_id) {this.cust_id = cust_id ؛ } السلسلة العامة getCust_Name () {return cust_name ؛ } public void setCust_Name (String Cust_name) {this.cust_name = cust_name ؛ } public getCust_User_id () {return cust_user_id ؛ } public void setcust_user_id (long cust_user_id) {this.cust_user_id = cust_user_id ؛ } public getCust_Create_ID () {return cust_create_id ؛ } public void setcust_create_id (long cust_create_id) {this.cust_create_id = cust_create_id ؛ } السلسلة العامة getCust_Source () {return cust_source ؛ } public void setCust_Source (String Cust_source) {this.cust_source = cust_source ؛ } السلسلة العامة getCust_Industry () {return cust_industry ؛ } public void setcust_industry (String Cust_industry) {this.cust_industry = cust_industry ؛ } السلسلة العامة getCust_level () {return cust_level ؛ } public void setCust_Level (String cust_level) {this.cust_level = cust_level ؛ } السلسلة العامة getCust_Linkman () {return cust_linkman ؛ } public void setCust_Linkman (String Cust_Linkman) {this.cust_linkman = cust_linkman ؛ } السلسلة العامة getCust_Phone () {return cust_phone ؛ } public void setCust_Phone (string cust_phone) {this.cust_phone = cust_phone ؛ } السلسلة العامة getCust_Mobile () {return cust_mobile ؛ } public void setCust_Mobile (String Cust_Mobile) {this.cust_mobile = cust_mobile ؛ } Override public string toString () {return "custome [cust_id =" + cust_id + "، cust_name =" + cust_name + "، cust_user_id =" + cupt_user_id + " CUST_LEVEL = " + CUST_LEVEL +" ، cust_linkman = " + cust_linkman +" ، cust_phone = " + cust_phone +" ، cust_mobile = " + cust_mobile +"] ؛ }}6. تعريف customer.hbm.xml
يرتبط ملف التكوين هذا بفئة PoJO العميل. يجب وضع هذا الملف ضمن نفس الحزمة مثل فئة Pojo العميل
<؟ name = "com.clj.domain.customer" table = "cst_customer"> <id name = "cust_id" column = "cust_id"> <generator/> </id> <property name = "cust_name" column = "cust_name"/> <property name = "cust_id" colup = "cust_id"/> column = "cust_create_id"/> <property name = "cust_source" column = "cust_source"/> <property name = "cust_industry" column = "cust_industry"/> <property name = "cust_level" cOUNTION = "cust_level"/> <property name = name = "cust_phone" column = "cust_phone"/> <property name = "cust_mobile" colun
مخطط بناء المشروع
4. عرض أولي للتوضيح للحفاظ على العملاء
هنا نحدد أولاً طبقة الثبات إلى Heibernate ، وطبقة العمل إلى Struts2 ، ومثال الإنشاء إلى الربيع
1. تحديد واجهة لإنقاذ العملاء واستخدام نماذج النماذج لتقديم البيانات
وفقًا لاسم المجال ، يمكننا أن نرى أن طريقة STRUTS2 Wildcard تستخدم للوصول.
<form id = form1 name = form1 action = "$ {pageContext.request.contextpath} /customer_add.action" method = post> <!-جدول الجدول المحذوف-> </form>2. تكوين طلبات قبول في struts.xml ، انقلب إلى الإجراء المحدد وفقًا لاسم وطريقة الإجراء ، وتنفيذ الطريقة المحددة
يدمج Spring Struts2 الطريقة الأولى: يتم إدارة الإجراء بواسطة إطار عمل Struts2
* نظرًا لأن حزمة Struts2-spring-plugin-2.3.24.jar تأتي مع struts-plugin.xml ، تم تضمين الرمز التالي في ملف التكوين
* <name constant = "structs.objectFactory" value = "Spring" /> قم بتشغيل ثابت. إذا تم تشغيل الثابت ، يمكن استخدام الثابت التالي
* struts.objectfactory.spring.autowire = الاسم ، هذا الثابت هو فئة تسمح للإجراء بتجميع كائنات الفاصوليا تلقائيًا!
<؟ تمديد = "struts-default" اسم اسم الاسم = "/"> <!-تكوين إجراءات العميل-> <!-الطريقة 1: يتم إدارة aciton بواسطة STRUTS2 Framework-> <Action name = "customer_*" method = "{1}"/> </package> </struts>3. تكوين الفاصوليا المقابلة والمعاملات في Spring ApplicationContext.xml
هنا ، باستخدام ميزة IOC (تحكم) في الربيع ، يتم تسليم مهمة إنشاء مثيل إلى إدارة إطار الربيع
<bean id = "customerervice"> <property name = "customerdao" ref = "customerdao"> </property> </bean> <bean id = "customerdao"> <property name = "hibernatetemplate" ref = "hibernateTemplate"/> </bean id = "hibernatetemplate"> </bean> </bans>
4. اكتب فئة تنفيذ طبقة الثبات الكود المرتبط
هنا ، يتم استخدام فئة القالب التي توفرها السبات لإحاطة الجلسة داخليًا ، بحيث يمكن استدعاء الطريقة في الجلسة.
/** * طبقة الثبات * * Author Administrator * */clusterdaoimpl من الفئة العامة ، يقوم CustomerDao {// بحفظ البيانات إلى قاعدة البيانات (فئة قالب الاتصال (المقدمة من السبات ، الجلسة المغلفة داخليًا))) HibernateTemplate الخاصة ؛ public void sethibernateTemplate (hibernatetemplate hibernatetemplate) {this.hibernatetemplate = hibernatetemplate ؛ } / *** حفظ العميل* / public void حفظ (عميل العميل) {system.out.println ("الطبقة الدائمة: حفظ العميل") ؛ hibernatetemplate (). حفظ (عميل) ؛ }}5. اكتب رمز فئة تنفيذ طبقة الأعمال التجارية
package com.clj.service ؛ import org.springframework.transaction.annotation.transactional ؛ import com.clj.dao.customerdao ؛ import com.clj.domain.customer ؛/** * طبقة عمل العميل * @Author * */ @strappubling classerviceimpl cupertyo. public void setCustomerDao (customerdao customerdao) {this.customerdao = customerDao ؛ } // المستخدمة لحفظ الفراغ العام للعميل (عميل العميل) {system.out.println ("طبقة الأعمال ، حفظ العميل") ؛ customerdao.save (عميل) ؛ }}6. اكتب الكود المتعلق بالإجراءات
هنا فئة القالب من دعامات 2
package com.clj.web.action ؛ import org.apache.struts2 com.clj.service.customerService ؛ استيراد com.opensymphony.xwork2.actionsupport ؛ استيراد com.opensymphony.xwork2.modeldriven ؛/** * طبقة التحكم العميل * @Autherator Administrator * */ClientAction العامة يمتد Actionupport Displuments <sperny> العميل العام getModel () {return customer ؛ } // توفير سمات أعضاء الخدمة وتوفير طريقة مجموعة Privateervice ProbernaRvice ؛ public void setCustomerService (customerervice cornervice) {this.customerservice = customerervice ؛ } / *** حفظ العميل* regurn* / public string add () {system.out.println ("web layer ، حفظ العميل") ؛ // الطريقة 1: إنشاء مصنع الويب (يتم إنشاء الإجراء بواسطة Struts2) WebApplicationContext Context = WebApplicationContextUtIls.getWebPlicationContext (servletactionContext.getServletContext ()) ؛ Customerervice CS = (Customerervice) Context.getBean ("customerervice") ؛ // طريقة الاتصال Cs.Save (عميل) ؛ لا شيء }}5. دمج تحسين المشروع
1.
ضع ملف تكوين فئة الإجراء المحدد ApplicatonContext.xml في ملف التكوين ، ولكن ملاحظة: يجب تعديل Struts.xml
<struts> <!-تكوين بنية الحزمة-> <package name = "crm" تمتد = "struts-default" namepace = "/"> <!-تكوين إجراء العميل-> <!-الطريقة 1: يتم إدارة aciton بواسطة struts2 إطار عمل <action_ "customer_*" meth حبة التكوين مطلوبة على علامة الفئة-> <Action name = "customer_*" method = "{1}"2. تكوين فئة الإجراء في ApplicationContext.xml
ملاحظة: 1) يقوم إطار عمل الربيع بإنشاء عمل العميل بشكل افتراضي ، في حين أن إطار STRUTS2 متعدد. لذلك تحتاج إلى تكوين Scope = "النموذج الأولي"
2) لا يوجد تجميع تلقائي من Struts2 في هذا الوقت. في العمل ، تحتاج إلى تكوين خاصية خدمة العملاء يدويًا وإنشاء طريقة المجموعة في فئة العمل.
<!-تكوين وحدة العميل-> <!-التأكيد: يجب أن يكون Aciton المكوّن متعدد العمود-> <Bean id = "CustomerAction" Scope = "Orgetytor" <!-ملاحظة: عندما تقوم الدعامات بإدارة الإجراءات ، استنادًا إلى حزمة struts-plugin ، والتي تغير sTruts.Objectore.spring.spring.seary = الاسم المليء بالجائزة ، ويمكنها أن تكون تلقائيًا. تحتاج فقط إلى توفير طريقة محددة. ومع ذلك ، تتم إدارة الإجراء بحلول الربيع ، والتجميع التلقائي غير صالح ، لذلك تحتاج إلى إجراء حقن التكوين يدويًا-> <property name = "customerervice" ref = "customerervice"> </property>
3. تكوين المعاملات
يدمج Spring طريقة Hibernate On: (ملف التكوين مع hibernate.cfg.xml. التأكيد: لا يمكن إضافة التكوين الذي يربط مؤشر الترابط الحالي)
في الماضي ، عند لعب Hibernate ، تمت إدارة hibernate.cfg.xml بواسطة إطار السبات. يمكن أن ينشئ ملف التكوين الخاص به SessionFactory. تقوم طبقة الثبات بتحميل ملف التكوين هذا للحصول على SessionFactory ، وبالتالي إنشاء جلسة تم إنشاؤها في المصنع ، وإضافة وحذف وتغيير البيانات إلى. في هذا الوقت ، يجب تسليم ملف التكوين الخاص به إلى إدارة الربيع ، مع الاستفادة الكاملة من خصائص IOC في Spring.
يوفر إطار الربيع فئة أدوات levernatedaoSupport ، والتي يمكن أن تكون ورثها في المستقبل من قبل DAO! ! قبل إدخال ملف التكوين الأساسي لـ Hibernate ، يجب أن ترث طبقة DAO فئة أوليلية من الفئة الوالدية heibernatedaoSupport ، والتي تغلف قالب المعاملة داخليًا.
انظر رمز المصدر:
1) تعديل فئة تنفيذ طبقة الثبات المقابلة واتركها ترث heibernatedaoSupport
package com.clj.dao ؛ استيراد org.springframework.orm.hibernate5.hibernateTemplate ؛ import org.springframework.orm.hibernate5 داخليًا * Author Administrator * * /public clientdaoimpl يمتد HibernatedAoSupport يطرف CustomerDao {// حفظ البيانات إلى قاعدة البيانات (استدعاء فئة القالب (المقدمة من Hibernate ، جلسة مغلفة)) / * private hibernatetmethendate ؛ public void sethibernateTemplate (hibernatetemplate hibernatetemplate) {this.hibernatetemplate = hibernatetemplate ؛ }*// ***حفظ العميل*/ public void save (عميل العميل) {system.out.println ("الطبقة الدائمة: حفظ العميل") ؛ this.gethibernateTemplate (). حفظ (عميل) ؛ }}2) تعديل طبقة العمل وتمكين تعليقات المعاملات
package com.clj.service ؛ import org.springframework.transaction.annotation.transactional ؛ import com.clj.dao.customerdao ؛ import com.clj.domain.customer ؛/** * طبقة عمل العميل * @Author * */ @strappubling classerviceimpl cupertyo. public void setCustomerDao (customerdao customerdao) {this.customerdao = customerDao ؛ } // المستخدمة لحفظ الفراغ العام للعميل (عميل العميل) {system.out.println ("طبقة الأعمال ، حفظ العميل") ؛ customerdao.save (عميل) ؛ }}3) تعديل ملف ApplicationContext.xml
تقديم ملف تكوين السبات أولاً
<!-اكتب الفاصوليا ، يتم إصلاح الأسماء ، مقدمة حسب الربيع ، تستخدم لتحميل ملف التكوين لـ hibernate.cfg.xml-> <bean id = "sessionfactory"> <!-مسار التكوين: عند بدء تشغيل الخادم ، سيتم إنشاء الكائن ، value = "classpath: hibernate.cfg.xml"/> </bean>
تكوين إدارة معاملات النظام الأساسي: تستخدم لإدارة المعاملات. لاحظ الآن أن إطار عمل السبات يستخدم الآن ، لذلك هناك حاجة إلى مدير المعاملات في إطار السبات.
<!-قم بتكوين مدير معاملات النظام الأساسي أولاً-> <bean id = "TransactionManager"> <!-حقن المعاملات ، يمكن للجلسة إدارة المعاملات ، ويمكن للمصنع إنشاء جلسة-> <propertyfactory "ref =" sessionfactory "/> </bean>
تعليق معاملة مفتوحة
<!-التعليق التوضيحي لتمكين المعاملة-> <TX: ماناجر المعاملات التي تعتمد على التعليقات التوضيحية = "TransactionManager"/>
قم بإزالة تكوين فئة القالب وتكوين SessionFactory لطبقة الثبات
<!-في المستقبل ، يحتاج DAO إلى أن يرث hibernatedaoSupport وحقن SessionFactory-> <bean id = "customerdao"> <!-<property name = "hibernatetemplate" ref = "hibernatetemplate"/> <! Ref = "SessionFactory"/> </bean>
جميع الرموز هي كما يلي
<؟ xmlns: context = "http://www.springframework.org/schema/context" XSI: Schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/sctxt http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframeword <!-مسار التكوين: عند بدء تشغيل الخادم ، سيتم إنشاء الكائن ، وبالتالي تحميل ملف hibernate.cfg.xml ، وبالتالي إنشاء كائن SessionFactory-> <property name = "configlocation" value = "classpath يمكن للجلسة إدارة المعاملات ، ويمكن للمصنع إنشاء جلسة-> <property name = "SessionFactory" ref = "SessionFactory"/> </bean> <!-التعليق التوضيحي لتمكين المعاملات-> <tx: تعويضات معاملة تعليمية-acit-يجب أن تكون acit- id = "custome custome" scope = "النموذج الأولي"> <!-ملاحظة: عندما تدير الدعامات الإجراءات ، استنادًا إلى حزمة جرة مع struts-plugin ، struts.ObjectFactory.Spring.Autowire = تم تغيير الاسم لتشغيله ، ويمكن تجميعه تلقائيًا. تحتاج فقط إلى توفير طريقة محددة. ومع ذلك ، تتم إدارة الإجراء بحلول الربيع ، والتجميع التلقائي غير صالح ، لذلك تحتاج إلى إجراء حقن التكوين يدويًا-> <property name = "customerervice" ref = "customerervice"> </property> </bean> <bean id = "customerervice"> <property name = "customerdao" ref = "property" </spertar name = "hibernateTemplate" ref = "hibernateTemplate"/>-> <!-لا يتم حقن فئة القالب هنا ، ولكن sessionfactory ، لأن القالب يحتاج إلى جلسة (جلسة مغلفة)-> <property namefactory = sessionfactory "ref =" sessionfactory "/> </bean> <! ترث طبقة الثبات heibernatedaoSupport ، ليست هناك حاجة لتكوين-> <!-<bean id = "hibernatetemplate"> enjective sessionfactory <property name = "sessionfactory"/> </bean>-> </bans>
4) تعديل فئة الإجراء
نظرًا لأن فئة تنفيذ طبقة العمل قد تم حقنها ، يمكن استدعاء طريقة طبقة العمل مباشرة في هذا الوقت دون تحميل الفول
package com.clj.web.action ؛ import org.apache.struts2 com.clj.service.customerService ؛ استيراد com.opensymphony.xwork2.actionsupport ؛ استيراد com.opensymphony.xwork2.modeldriven ؛/** * طبقة التحكم العميل * @Autherator Administrator * */ClientAction العامة يمتد Actionupport Displuments <sperny> العميل العام getModel () {return customer ؛ } // توفير سمات أعضاء الخدمة وتوفير طريقة مجموعة Privateervice ProbernaRvice ؛ public void setCustomerService (customerervice cornervice) {this.customerservice = customerervice ؛ } / *** حفظ العميل* regurn* / public string add () {system.out.println ("web layer ، حفظ العميل") ؛ // الطريقة 1: إنشاء مصنع الويب (يتم إنشاء الإجراء بواسطة Struts2) /*webapplicationContext context = webapplicationContextutils.getWebPlicationContext (servletactionContext.getServletContext ()) ؛ Customerervice CS = (Customerervice) Context.getBean ("customerervice") ؛ // طريقة الاتصال Cs.Save (عميل) ؛ */ customerervice.save (عميل) ؛ لا شيء }}طريقة تكامل الربيع - طريقة yibernate اثنين: (ملف التكوين بدون hibernate.cfg.xml)
سنقوم هنا بحذف ملف التكوين الأساسي لـ Hibernate. قبل الحذف ، تحتاج إلى تكوين المحتوى ذي الصلة في ملف التكوين الخاص به إلى ملف ApplicationInconText.xml من Spring.
1. تحقق من المحتوى ذي الصلة في ملف hibernate.cfg.xml
* المعلمات الأساسية لاتصال قاعدة البيانات (4 معلمات رئيسية)
* الخصائص المتعلقة بالإسبنات
* تجمع الاتصال
* ملفات الخريطة
2. إدخال التكوين
إدخال تجمع الاتصال
<!-قم بتكوين تجمع الاتصال لـ C3P0 أولاً-> <bean id = "datasource"> <property name = "driverclass" value = "com.mysql.jdbc.driver"/> <property name = "jdbcurl" value = "jdbc: mysql: //192.168.174.130: 3306/ <property name = "password" value = "root"/> </bean>
تعديل SessionFactory المقابل: نظرًا لعدم وجود ملف تكوين لـ hibernate.cfg.xml ، تحتاج إلى تعديل التكوين وحقن تجمع الاتصال.
قم بتعيين ملف تعيين الكائن: نظرًا لأن ملف التكوين الخاص بـ hibernate.cfg.xml لم يعد مسحًا ضوئيًا ، ويجب حقن ملف التكوين.
<!-اكتب الفاصوليا ، يتم إصلاح الأسماء ، ويتم توفيرها بحلول الربيع لتحميل ملف التكوين الخاص بـ hibernate.cfg.xml-> <bean id = "sessionfactory"> <!-تحميل تجمع الاتصال أولاً-> <name name = "dataSource" ref = "datasource"/> <! key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <prop key = "hibernate.show_sql"> true </prop> <prop> key = "hibernate.format_sql"> true </prop> <propernate.hbm2ddl <!-تقديم ملفات تكوين التعيين-> <property name = "MapPingResources"> <list> <value> com/clj/domain/customer.hbm.xml </value> </list> </sprement> </ban>
الآن: رمز ApplicationContext.xml كما يلي
<؟ xmlns: context = "http://www.springframework.org/schema/context" XSI: Schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/sctxt http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-تكوين مجموعة الاتصال لـ c3p0 first-> <quarcours value = "com.mysql.jdbc.driver"/> <property name = "jdbcurl" value = "jdbc: mysql: //192.168.174.130: 3306/ssh"/> <property name = "user" value = "root"/> <property name = "value" قم بتحميل ملف التكوين الخاص بـ hibernate.cfg.xml-> <bean id = "sessionfactory"> <!-قم بتحميل تجمع الاتصال أولاً-> <property name = "datasource" ref = "datasource key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <prop key = "hibernate.show_sql"> true </prop> <prop> key = "hibernate.format_sql"> true </prop> <propernate.hbm2ddl <!-قم بحقن ملف تكوين التعيين-> <name property = "MapPingResources"> <list> <value> com/clj/domain/customer.hbm.xml </value> </list> </property> </bean> <!-تكوين إدارة المعاملات أولاً- name = "sessionfactory" ref = "sessionfactory"/> </bean> <!-التعليق التوضيحي لفتح معاملة-ماناجير = "TransactionManager"/> <!-تكوين وحدة العميل-> <!-التأكيد: يجب أن تكون Aciton المكوّنة Multi-Column-> <bean id = "scope =" protypole ". Struts-plugin ، struts.ObjectFactory.Spring.Autowire = تم تشغيل الاسم ويمكن تجميعه تلقائيًا. تحتاج فقط إلى توفير طريقة المجموعة. However, the action is managed by spring and the automatic assembly is invalid, so you need to manually perform configuration injection--> <property name="customerService" ref="customerService"></property> </bean> <bean id="customerService"> <property name="customerDao" ref="customerDao"></property> </bean> <!-- In the future, Dao needs to inherit HibernateDaoSupport and inject sessionFactory --> <bean id="customerDao"> <!--<property name="hibernateTemplate" ref="hibernateTemplate"/> -> <!-- The template class is not injected here, but sessionFactory, because the template needs session (encapsulated session)--> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- Configure the template class (provided by the hibernate framework, encapsulated session) and is handed over to spring management at this time. If the persistence layer inherits HibernateDaoSupport, there is no need to configure --> <!-- <bean id="hibernateTemplate"> Inject sessionFactory <property name="sessionFactory"/> </bean>--></beans>
此时可以安心的删除hibernate.cfg.xml文件了
这样SSH整合完毕
六、Hibernate模板常用方法
注意:以下代码省略了接口中的演示(偷了个懒,相信初学者不会看不懂)
1)插入:
持久层
package com.clj.dao;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.springframework.orm.hibernate5.HibernateTemplate;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.clj.domain.Customer;/** * Persistence layer* Inherits HibernateDaoSupport and encapsulates HibernateTemplate internally * @author Administrator * */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { @Override public void update(Customer customer) { // TODO Auto-generated method stub this.getHibernateTemplate().update(customer); }}业务层
package com.clj.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * Customer's business layer* @author Administrator * */@Transactionalpublic class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } @Override public void update(Customer customer) { // TODO Auto-generated method stub customerDao.update(customer); }}测试类
package com.clj.test;import java.util.List;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.clj.domain.Customer;import com.clj.service.CustomerService;/** * Simple way to test Hiberante template class* @author Administrator * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="customerService") private CustomerService customerService; /** * Test insert*/ @Test public void run1(){ Customer customer=new Customer(); customer.setCust_id(1L); customer.setCust_name("test"); customerService.update(customer); }}2)以下为指定查询、查询所有、离线查询代码
持久层
package com.clj.dao;import java.util.List;import org.hibernate.criterion.DetachedCriteria;import org.springframework.orm.hibernate5.HibernateTemplate;import org.springframework.orm.hibernate5.support.HibernateDaoSupport;import com.clj.domain.Customer;/** * Persistence layer* Inherits HibernateDaoSupport and encapsulates HibernateTemplate internally * @author Administrator * */public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao { //Save data to the database (call template class (provided by hibernate, encapsulated session)) /*private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; }*/ /** * Save customer*/ public void save(Customer customer) { System.out.println("Permanent layer: save customer"); this.getHibernateTemplate().save(customer); } @Override public void update(Customer customer) { // TODO Auto-generated method stub this.getHibernateTemplate().update(customer); } /** * Query by primary key*/ public Customer getById(Long id) { return this.getHibernateTemplate().get(Customer.class, id); } /** * Query all*/ @Override public List<Customer> findAll() { String sql="from Customer"; List<Customer> list=(List<Customer>) this.getHibernateTemplate().find(sql); return list; } /** * QBC offline query*/ @Override public List<Customer> findAllByQBC() { DetachedCriteria criteria=DetachedCriteria.forClass(Customer.class); List<Customer> list=(List<Customer>) this.getHibernateTemplate().findByCriteria(criteria); return list; }}业务层
package com.clj.service;import java.util.List;import org.springframework.transaction.annotation.Transactional;import com.clj.dao.CustomerDao;import com.clj.domain.Customer;/** * Customer's business layer* @author Administrator * */@Transactionalpublic class CustomerServiceImpl implements CustomerService{ private CustomerDao customerDao; public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } // Used to save customers public void save(Customer customer) { System.out.println("Business layer, save customer"); customerDao.save(customer); } @Override public void update(Customer customer) { // TODO Auto-generated method stub customerDao.update(customer); } @Override public Customer getById(Long id) { // TODO Auto-generated method stub return customerDao.getById(id); } @Override public List<Customer> findAll() { return customerDao.findAll(); } @Override public List<Customer> findAllByQBC() { // TODO Auto-generated method stub return customerDao.findAllByQBC(); }}测试类
package com.clj.test;import java.util.List;import javax.annotation.Resource;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.clj.domain.Customer;import com.clj.service.CustomerService;/** * Simple way to test Hiberante template class* @author Administrator * */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext.xml")public class Demo1 { @Resource(name="customerService") private CustomerService customerService; /** * Test insert*/ @Test public void run1(){ Customer customer=new Customer(); customer.setCust_id(1L); customer.setCust_name("test"); customerService.update(customer); } /** * Test query the specified customer*/ @Test public void run2(){ Customer customer=customerService.getById(2L); System.out.println(customer); } /** * Query all customers*/ @Test public void run3(){ List<Customer> list=customerService.findAll(); System.out.println(list); } /** * QBC(offline query) */ @Test public void run4(){ List<Customer> list=customerService.findAllByQBC(); System.out.println(list); }}七、关于SSH延迟加载问题
1. 使用延迟加载的时候,再WEB层查询对象的时候程序会抛出异常!
* 原因是延迟加载还没有发生SQL语句,在业务层session对象就已经销毁了,所以查询到的JavaBean对象已经变成了托管态对象!
* 注意:一定要先删除javassist-3.11.0.GA.jar包(jar包冲突了)
2. 解决办法
Spring框架提供了一个过滤器,让session对象在WEB层就创建,在WEB层销毁。只需要配置该过滤器即可
* 但是:要注意需要在struts2的核心过滤器之前进行,spring监听器之后配置
<!-- 解决延迟加载的问题--> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3、演示延迟加载
持久层:调用load方法,此方法时延迟加载的
/** * Lazy load*/ @Override public Customer loadById(long id) { // TODO Auto-generated method stub return this.getHibernateTemplate().load(Customer.class, id); }业务层
@Override public Customer loadById(long id) { // TODO Auto-generated method stub return customerDao.loadById(id); }测试类
@Test public void run5(){ Customer customer=customerService.loadById(2L); System.out.println(customer); }ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.