Configure hibernate + spring in myeclipse (FAST)

Source: Internet
Author: User

 

Configure hibernate + spring in myeclipse (FAST)

Keywords: Configure hibernate + spring in myeclipse

Popular Development Mode: Spring + hibernate + Struts. Here I will introduce the combination of spring + hibernate. It is very easy to add struts presentation layer. Let's start now:

Database preparation:
Database Name: at_sms
Table Name: Admin
The fields are as follows:
Sid bigint is automatically increased from 1. The step size is 1 and the table's primary key is created separately.
Name varchar (50)
Password varchar (50)

Prepare for software development:
Eclipse 3.1
Myeclipse enterprise workbench v4.1.1 ga
Jdk1.4.2
Spring1.2 [comes with myeclipse]
Hibernate3.0 [included in myeclipse]

Steps:
1. Set your workspace [D:/eclipse3.1/myworkspace];

2. Create a common Java project [not a myeclipse web project] myproject [D:/eclipse3.1/myworkspace/myproject;

2a. Configure database connection backup. Dongdong is under window-> open perspective-> my eclipse database example E. In the left-side blank box, right-click and select new. In the pop-up box, enter profile name: mytestdb; Driver: Configure database driver for configuration. Other parameters are as follows, if you do not want to see it, select "display the selected schemas" in the second step. When you click "add", all the data will be automatically connected to the database, and select "at_sms, click Finish.

3. Add spring related items. [click "myeclipse"> "add spring capabilities"...] [Note: The cursor can be added only when it is stopped in the project root directory, otherwise it is gray.] In the pop-up window, the spring1.2 core package is selected by default, and spring1.2 ORM/Dao/hibernate3 is selected, spring1.2 testing all selected [saving test time when jar cannot be found before importing], next, create a src directory to store the configuration file, finish.

4. Add hibernate-related things. Pay attention to link the root spring. Select mytestdb created before the database connection. dialect is sysbase by default. I use SQL Server, so I need to change it; the bean ID of Hibernate is set to the same as that of spring. The result configuration file prompts that the ID is not unique. Haha, clear hiebernate-related things first, which is a little troublesome, first, switch to myeclipse J2EE development [if not, it may be that your workspace does not have such a project. Create a myeclipsej2ee project], and then switch the project view from packageexplorer to navigator, delete the file with the hibernate file name and open it. project File, delete a buildcommand about Hibernate and a nature. OK. You can add hibernate-related items again. [Note: sessionfactory is the bean ID that spring uses to associate with hibernate. I fill in sessionfactory. The beanid in the database parameter is the data source name, And I fill in datasource]

5. Next, generate a hibernate ing, switch the view to myeclipse Database Explorer, right-click to open the connection, and select the table where you want to generate the Java code. Here, select Admin, the pop-up window will show some parameters by default. Because the DB connection does not belong to a single project, it is a global parameter, and the default parameter may not be what you want, no matter how many times you select Java SRC folder to the src directory of your current project, this will be associated with your project, and the parameters will change accordingly. The Java package is set to com. kama. hibernate: select and generate spring Dao. By default, you must set some primary keys for the table. Select the table name and select native in ID generator.

6. Let spring manage database transactions and add the following content to the configuration file applicationcontext. xml:

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory">            <ref bean="SessionFactory"/>        </property>    </bean> <bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionInterceptor">        <property name="transactionManager">            <ref bean="transactionManager"/>        </property>        <property name="transactionAttributes">            <props>                <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>                <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop>                <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>                <prop key="add*">PROPAGATION_REQUIRED</prop>                <prop key="create*">PROPAGATION_REQUIRED</prop>                <prop key="update*">PROPAGATION_REQUIRED</prop>                <prop key="delete*">PROPAGATION_REQUIRED</prop>                <prop key="save*">PROPAGATION_REQUIRED</prop>                <prop key="regedit*">PROPAGATION_REQUIRED</prop>                 <prop key="remove*">PROPAGATION_REQUIRED</prop>                <prop key="do*">PROPAGATION_REQUIRED</prop>            </props>        </property> </bean>    <bean id="autoProxyCreator"          class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">        <property name="interceptorNames">            <list>                <value>baseTransactionProxy</value>            </list>        </property>        <property name="beanNames">            <value>*DAO</value>        </property>    </bean> 

7. The transaction must be called by the interface. For details, refer to other materials. Now we add the interface: adointerface, in which the definition method is public void save (Object transientinstance ); [The object parameter type is used to allow all DaO classes to share this interface];

8. Add the implementation interface adointerface in admindao and modify the declaration of its save method. Public void save (Object transientinstance)

9. Test Method 1 by writing the following code:

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 importing D:/myeclipse/Eclipse/plugins/COM in Java builder path> libraries of the Project attribute. genuitec. eclipse. springframework_4.1.1/data/1.2/lib/spring-mock.jar
The generated test class inherits org. springframework. Test. abstracttransactionalspringcontexttests. Modify:
Protected string [] getconfiglocations (){
Return New String []
{"/Applicationcontext. xml "};
}
Added:

Private adointerface admindao; Public void setadmindao (adointerface admindao) {This. admindao = admindao;} public void testsave () {This. setcomplete (); // if you want to insert the data into the database, you can retain it. If you do not want to insert the data into the database, the JUnit test will automatically roll back. Admin admin = new admin (); Admin. setname ("kamasupport"); Admin. setpassword ("123456"); this. admindao. Save (Admin );}

Run the test program in JUnit format. Success!

Appendix A: applicationcontext. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype beans public "-// spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd">

<Beans>

<Bean id = "datasource" class = "org. Apache. commons. DBCP. basicdatasource">
<Property name = "driverclassname">
<Value> net. SourceForge. jtds. JDBC. Driver </value>
</Property>
<Property name = "url">
<Value> JDBC: jtds: sqlserver: // 127.0.0.1: 3344/at_sms; selectmethod = cursor </value>
</Property>
<Property name = "username">
<Value> SA </value>
</Property>
<Property name = "password">
<Value> 123456 </value>
</Property>
</Bean>

<Bean id = "transactionmanager" class = "org. springframework. Orm. hibernate3.hibernatetransactionmanager">
<Property name = "sessionfactory">
<Ref bean = "sessionfactory"/>
</Property>
</Bean>

<Bean id = "basetransactionproxy" class = "org. springframework. transaction. Interceptor. transactioninterceptor">
<Property name = "transactionmanager">
<Ref bean = "transactionmanager"/>
</Property>
<Property name = "transactionattributes">
<Props>
<Prop key = "load *"> propagation_required, readonly </prop>
<Prop key = "list *"> propagation_required, readonly </prop>
<Prop key = "find *"> propagation_required, readonly </prop>
<Prop key = "add *"> propagation_required </prop>
<Prop key = "create *"> propagation_required </prop>
<Prop key = "Update *"> propagation_required </prop>
<Prop key = "delete *"> propagation_required </prop>
<Prop key = "Save *"> propagation_required </prop>
<Prop key = "Regedit *"> propagation_required </prop>
<Prop key = "Remove *"> propagation_required </prop>
<Prop key = "do *"> propagation_required </prop>
</Props>
</Property>
</Bean>

<Bean id = "autoproxycreator"
Class = "org. springframework. AOP. Framework. autoproxy. beannameautoproxycreator">
<Property name = "interceptornames">
<List>
<Value> basetransactionproxy </value>
</List>
</Property>
<Property name = "beannames">
<Value> * Dao </value>
</Property>
</Bean>

<Bean id = "sessionfactory" class = "org. springframework. Orm. hibernate3.localsessionfactorybean">
<Property name = "datasource">
<Ref bean = "datasource"/>
</Property>
<Property name = "hibernateproperties">
<Props>
<Prop key = "hibernate. dialect"> org. hibernate. dialect. sqlserverdialect </prop>
</Props>
</Property>
<Property name = "mappingresources">
<List>
<Value> COM/Kama/hibernate/admin. HBM. xml </value>
</List>
</Property>
</Bean>
<Bean id = "admindao" class = "com. Kama. hibernate. admindao">
<Property name = "sessionfactory">
<Ref bean = "sessionfactory"/>
</Property>
</Bean>
</Beans>

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. leleappender
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

If exceptions occur during Tomcat startup, check whether the spring and hibernate packages conflict with each other when you add them. Basically, the asm-2.2.3.jar under the lib directory is deleted, so there should be no problem starting tomcat!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.