Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to combine Spring, Hibernate and Struts under MyEclipse

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to combine Spring, Hibernate and Struts under MyEclipse. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Database preparation:

Database name: AT_SMS

Table name: admin

The fields are as follows:

Sid bigint automatically increases from 1, with a step size of 1, and acts as the primary key name varchar (50) of the table alone.

Password varchar (50)

Software development preparation: Eclipse 3.1

MyEclipse Enterprise Workbench v4.1.1 GA

JDK1.4.2

Spring1.2 [included with MyEclipse]

Hibernate3.0 [included with MyEclipse]

Steps:

1. Set your own Workspace [D: Eclipse3.1MyWorkspace]

2. Establish an ordinary Java project [not a MyEclipse Web project] MyProject [D:Eclipse3.1MyWorkspaceMyProject]

2A. Configure database connection backup. Things are under Window- > Open Perspective- > My Eclipse Database Explore. Right click on the left blank box to select New, after the pop-up box, fill in the Profile name:MyTestDB; driver point Configure database driver to configure, the rest look at the fill, do not want to see so the database in the second step to select Display the selected schemas, click the button Add will automatically connect to the database to display all the data, choose what you want to see, here we choose AT_SMS, click finish to complete.

3. Add something related to Spring [Click menu MyEclipse- > Add SPring Capabilities...] [note: pause the cursor in the project root directory to add it, otherwise it will be gray]; pop-up window to select Spring1.2 Core package by default, select Spring1.2 ORM/DAO/Hibernate3, select all Spring1.2 AOP,Spring1.2 Testing (to avoid importing jar when you can't find it during testing), next, and create a src directory to store configuration files, finish.

4. Add something related to Hibernate, notice that the root Spring is associated, and select the previously created MyTestDB for database connection. Dialect defaults to Sysbase, and I use Sql Server, so I need to change it. The bean ID of Hibernate is set to the same as that of Spring, and the result configuration file indicates that ID is not unique. Haha, then clear things related to Hiebernate first, which is also troublesome. First, you have to switch to MyEclipseJ2EE Development [if there is no such project in your workspace, create a MyEclipseJ2EE project], then switch the project view from PackageExplorer to Navigator, delete the file with the word Hibernate in the file name, and open the .project file. Delete a buildCommand about Hibernate and a nature.Ok, and you can add things related to Hibernate. [note: SessionFactory is the ID that Spring uses to associate Hibernate. I fill in SessionFactory, the BeanID when filling in database parameters is the name of the data source, and I fill in dataSource]

5. Next, generate Hibernate mapping, switch the view to MyEclipse Database Explorer, right-click to open the connection, and select the table in which you want to generate Java code. We select admin here, and the pop-up window will find that some parameters will be brought out by default. Because this DB connection is not a global thing belonging to a single project, the default parameters may not be what you want, no matter how much you choose Java src folder to the src directory of your current project. This is associated with your project, and the parameters are changed. Set Java package to com.kama.hibernate and select to generate Spring DAO. By default, the primary key generation of the table should be set, select the table name, and select native; in ID Generator.

6. Let Spring manage database transactions and add content to the configuration file applicationContext.xml:

PROPAGATION_REQUIRED,readOnly

PROPAGATION_REQUIRED,readOnly

PROPAGATION_REQUIRED,readOnly

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

BaseTransactionProxy

* DAO

7. In a transaction, it must be an interface call. For the specific reason, please see other materials. Now we add the interface: AdoInterface, in which we define the method: public void save (Object transientInstance). [using Object as the parameter type is to make this interface common to all DAO classes]

8. Add the implementation interface AdoInterface to AdminDAO, modify the declaration of its save method, public void save (Object transientInstance)

9. Test method 1, write the following code to test:

ApplicationContext ctx = new ClassPathXmlApplicationContext (

"applicationContext.xml")

AdoInterface dao = (AdoInterface) ctx.getBean ("AdminDAO")

System.out.println (dao.toString ())

Admin admin = new Admin ()

Admin.setName ("Kama")

Admin.setPassword ("123456")

Dao.save (admin)

System.out.println ("--Test completed--")

See the inserted record!

10. Test method 2: set import D:MyEclipseeclipsepluginscom.genuitec.eclipse.springframework_4.1.1data1.2libspring-mock.jar in JAVA Builder path- > Libraries of project properties

Generate the test class to inherit the org.springframework.test.AbstractTransactionalSpringContextTests; modification:

Protected String [] getConfigLocations () {

Return new String []

{"/ applicationContext.xml"}

}

Add:

Private AdoInterface adminDAO

Public void setAdminDAO (AdoInterface adminDAO)

{

This.adminDAO = adminDAO

}

Public void testSave ()

{

This.setComplete (); / / keep this if you want to insert the data into the database. If you don't want to insert the database, removing this Junit test will automatically roll back.

Admin admin = new Admin ()

Admin.setName ("KamaSupport")

Admin.setPassword ("123456")

This.adminDAO.save (admin)

}

Run the test program as Junit. The great task has been completed!

Appendix A:applicationContext.xml

Net.sourceforge.jtds.jdbc.Driver

Jdbc:jtds:sqlserver://127.0.0.1:3344/AT_SMS;SelectMethod=cursor

Sa

123456

PROPAGATION_REQUIRED,readOnly

PROPAGATION_REQUIRED,readOnly

PROPAGATION_REQUIRED,readOnly

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

PROPAGATION_REQUIRED

BaseTransactionProxy

* DAO

Org.hibernate.dialect.SQLServerDialect

Com/kama/hibernate/Admin.hbm.xml

Appendix B:log4j.properties

Log4j.rootLogger=INFO,default

Log4j.logger.org=ERROR

Log4j.logger.com.comp=ERROR

Log4j.logger.net.sf.hibernate=ERROR

Log4j.logger.net.sf.hibernate.SQL=ERROR

Log4j.logger.net.sf.hibernate.type=ERROR

Log4j.logger.net.sf.ehcache=ERROR

Log4j.logger.org.springframework=ERROR

Log4j.appender.stdout=org.apache.log4j.ConsoleAppender

Log4j.appender.Threshold=DEBUG

Log4j.appender.stdout.Target=System.out

Log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

Log4j.appender.stdout.layout.ConversionPattern=%d {yyyy-MM-dd HH:mm:ss,SSS}: [% p] [% t]% r% l% m% n

Log4j.appender.default=org.apache.log4j.RollingFileAppender

Log4j.appender.default.Threshold=DEBUG

Log4j.appender.default.File=kama.log

Log4j.appender.default.Append=true

Log4j.appender.default.MaxFileSize=1000KB

Log4j.appender.default.MaxBackupIndex=3

Log4j.appender.default.layout=org.apache.log4j.PatternLayout

Log4j.appender.default.layout.ConversionPattern=%d {yyyy-MM-dd HH:mm:ss,SSS}: [% p] [% t]% r% l% m% n

[@ more@] 1. Add to struts-config.xml:

2. Modify the Action mapping of Struts:

Attribute= "addAdminForm"

Input= "/ form/addAdmin.jsp"

Name= "addAdminForm"

Path= "/ addAdmin"

Scope= "request"

Type= "org.springframework.web.struts.DelegatingActionProxy" >

It is to change type to the proxy class of Spring, and the original Action class should be configured in the configuration file of Spring.

Struts configuration file has been modified!

3. Configure the bean corresponding to path= "/ addAdmin" in the Spring configuration file

ActionBean of class:Struts

Property: the DAO generated by Spring, this property is defined in com.kama.struts.action.AddAdminAction, and the Setter method is defined.

4. Use DAO in Action:

4.1Definitions DAO attributes:

Private AdoInterface dao

4.2: define the Setter,Getter method:

Public AdoInterface getDao ()

{

Return dao

}

Public void setDao (AdoInterface dao)

{

This.dao = dao

}

4.3: call DAO:

Public ActionForward execute (

ActionMapping mapping

ActionForm form

HttpServletRequest request

HttpServletResponse response) {

AddAdminForm addAdminForm = (AddAdminForm) form

Admin id = new Admin ()

Id.setName (addAdminForm.getName ())

Id.setPassword (addAdminForm.getPassword ())

Dao.save (id)

Return mapping.findForward ("success")

}

OK, it's done!

Note: when deploying, deploy the spring-web.jar package to the lib directory, otherwise the Class just added in the Struts configuration file can not be found, there will be an inexplicable error!

Thank you for reading! This is the end of the article on "how to combine Spring, Hibernate and Struts under MyEclipse". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report