Spring video learning (11) Integrated hibernate3.2

Source: Internet
Author: User
1. Integrated jar package

Spring2.5 + hibernate3.3 + struts1.3 Integrated Development

Under the hibernate core installation package:
Lib \ required \ *. Jar
Lib \ optional \ ehcache-1.2.3.jar
Lib \ test \ slf4j-log4j12.jar
Under the spring installation package
Dist \ spring. Jar
Dist \ modules \ spring-webmvc-struts.jar
Lib \ Jakarta-commons \ commons-logging.jar, commons-dbcp.jar, commons-pool.jar
Lib \ aspectj \ aspectjweaver. jar, aspectjrt. Jar
Lib \ cglib \ cglib-nodep-2.1_3.jar
Lib \ J2EE \ common-annotations.jar
Lib \ log4j \ log4j-1.2.15.jar
Download struts-1.3.8-lib.zip, you need to use all the jar files under the decompressed directory, it is recommended to replace the jstl-1.0.2.jar and standard-1.0.2.jar with version 1.1. A antlr-2.7.6.jar already exists in spring, so remove the antlr-2.7.2.jar in struts to avoid jar conflicts.
Database driver jar

Integrate spring and hibernate first, and then integrate Struts after testing.

2. Create a project

Configure the XML file of spring, manage sessionfactory by spring, and configure spring to manage transactions of hiberante:

<? XML version = "1.0" encoding = "UTF-8"?> <Beansxmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: AOP = "http://www.springframework.org/schema/aop" xmlns: Tx = "http://www.springframework.org/schema/tx" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5. Xsdhttp: // your http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <! -- Configure the data source --> <bean id = "datasource" class = "org. apache. commons. DBCP. basicdatasource "Destroy-method =" close "> <property name =" driverclassname "value =" com. mySQL. JDBC. driver "/> <property name =" url "value =" JDBC: mysql: // localhost: 3306/test? Useunicode = true & amp; characterencoding = UTF-8 "/> <property name =" username "value =" root "/> <property name =" password "value =" "/> <! -- Initial value when the connection pool starts --> <property name = "initialsize" value = "1"/> <! -- Maximum value of the connection pool --> <property name = "maxactive" value = "500"/> <! -- Maximum idle value. after a peak time, the connection pool can slowly release a portion of connections that are no longer in use, until maxidle --> <property name = "maxidle" value = "2"/> <! -- Minimum idle value. when the number of idle connections is less than the threshold value, the connection pool will pre-apply for some connections, so that you do not have time to apply when the peak traffic arrives --> <property name = "minidle" value = "1"/> </bean> <! -- Configure sessionfactory of hibernate --> <bean id = "sessionfactory" class = "org. springframework. orm. hibernate3.localsessionfactorybean "> <property name =" datasource "> <ref bean =" datasource "/> </property> <property name =" mappingresources "> <list> <value> COM/ persia/model/person. HBM. XML </value> </List> </property> <property name = "hibernateproperties"> <value> hibernate. dialect = org. hibernate. dialect. mysql5dialect H Ib.pdf. hbm2ddl. auto = Update hibernate. show_ SQL = false hibernate. format_ SQL = false hibernate. cache. use_second_level_cache = true hibernate. cache. use_query_cache = false hibernate. cache. provider_class = org. hibernate. cache. ehcacheprovider </value> </property> </bean> <! -- Configure the spring Transaction Manager for hibernate --> <bean id = "txmanager" class = "org. springframework. orm. hibernate3.hibernatetransactionmanager "> <property name =" sessionfactory "ref =" sessionfactory "/> </bean> <! -- Configure transactions using annotations --> <TX: annotation-driven transaction-Manager = "txmanager"/> <! -- Inject bean using the annotation method configured manually --> <context: annotation-config> </Context: annotation-config> <! -- Define the business bean to be injected --> <bean id = "personservice" class = "com. Persia. Service. impl. personserviceimpl"> </bean> </beans>

The Hibernate configuration file of person is as follows:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">3. Compile the business Bean:
Import Java. util. list; import javax. annotation. resource; import Org. hibernate. sessionfactory; import Org. springframework. transaction. annotation. propagation; import Org. springframework. transaction. annotation. transactional; import COM. persia. model. person; import COM. persia. service. ipersonservice; @ transactionalpublic class personserviceimpl implements ipersonservice {@ resourceprivate sessionfactory sessionf Acloud; Public void save (person) {// get the session managed by the spring container. Open the transaction before the method is executed and close the transaction at the end. Sessionfactory. getcurrentsession (). persist (person);} public void Update (person) {// used to synchronize a free update to the database sessionfactory. getcurrentsession (). merge (person);} public void Delete (integer ID) {sessionfactory. getcurrentsession (). delete (// No need to load data, high efficiency sessionfactory. getcurrentsession (). load (person. class, ID) ;}@ transactional (propagation = propagation. not_supported, readonly = true) public person getperson (integer ID) {return (person) sessionfactory. getcurrentsession (). get (person. class, ID) ;}@ suppresswarnings ("unchecked") @ transactional (propagation = propagation. not_supported, readonly = true) public list <person> getpersons () {return sessionfactory. getcurrentsession (). createquery ("from person "). list ();}}

Configure transactions with annotations and configure spring dependency injection with annotations.

No transaction is required for the read operation configuration and the configuration level is read-only.

4. Perform JUnit testing on the service Bean:
package junit.test;import static org.junit.Assert.*;import java.util.List;import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.persia.model.Person;import com.persia.service.IPersonService;public class IPersonServiceTest {private static IPersonService ps;@BeforeClasspublic static void setUpBeforeClass() throws Exception {  try {ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");  ps=(IPersonService) ctx.getBean("personService");    } catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();    }}//@Testpublic void testSave() {ps.save(new Person("hello"));}//@Testpublic void testUpdate() {Person p=ps.getPerson(5);p.setName("linda");ps.update(p);}//@Testpublic void testGetPerson() {System.out.println(ps.getPerson(5).getName());}@Testpublic void testDelete() {ps.delete(5);}//@Testpublic void testGetPersons() {List<Person> ls=ps.getPersons();for(Person p:ls){System.out.println(p.getName());}}}
So far, the integration of spring and hiberante has been completed.

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.