Wu Yuxiong - a natural framework for the development of natural JAVA SPRING study notes: Test SSH authentication transaction integration and hierarchical framework is valid

Layered integrated testing framework 
HibernateTemplate and HibernateDaoSupport, these two classes are two tools for the integration of Spring Hibernate3 provided. 
HibernateTemplate is one of Spring's template tools, it only needs to get a SessionFactory can perform persistence operations. Spring HibernateDaoSupport is to achieve a tool provided by the DAO component, which mainly provides two ways to simplify the implementation of the DAO, as follows. 
Public Final HibernateTemplate the getHibernateTemplate () 
public Final  void setSessionFactory (the SessionFactory the sessionFactory) 
wherein, the getHibernateTemplate () method returns a HibernateTemplate objects, once obtained HibernateTemplate object remaining to achieve DAO completed by the object, and setSessionFactory () method can be used Spring receiving the dependency injection.
The following step by step to explain the integration process between the Service and the DAO layer.
1 . Realize the DAO
 1 ) Create Interface PersonDao 
create a name in the src is com.mengma.ssh.dao package PersonDao create a name for the interface, the interface defines a save method in the packet, the code follows shows. 
Package com.mengma.ssh.dao;
 Import com.mengma.ssh.domain.Person;
 public  interface the PersonDao {
     public  void Save (the Person Person); 
}
2 ) Create PersonDaoImpl interface class 
to create a name for the package under the src com.mengma.ssh.dao.impl, create a class that implements interface PersonDaoImpl PersonDao in the packet, implements the class methods PersonDao interface. Its code shown below. 
Package com.mengma.ssh.dao.impl;
 Import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 Import com.mengma.ssh.dao.PersonDao;
 Import com.mengma.ssh.domain.Person;
 public  class PersonDaoImpl the extends HibernateDaoSupport the implements the PersonDao { 
    @Override 
    public  void Save (the Person Person) {
         the this .getHibernateTemplate () Save (Person);. 
        System.out.println ("Save PersonDao ..." ); 
    } 
} 
In the above code, inherited HibernateDaoSupport, and implements the interface PersonDao, the save () method, called HibernateTemplate the save () method to save the person object, and using the output statement console output "personDao save ..." message.
2 . Realize Service
 . 1 ) prepared by the method Service layer interface 
in PersonService interface, create a save () method, which method code is as follows: 
public  void Save (the Person Person);
 2 ) the preparation of Service layer interface class method 
in class PersonServiceImpl , the realization of the save method PersonService interface, then declare PersonDao property, and to prepare its getter and setter methods. The main code is as follows: 
Private the PersonDao PersonDao; // declare the PersonDao 
public the PersonDao getPersonDao () {
     return PersonDao; 
} 
public  void setPersonDao (the PersonDao PersonDao) {
     the this .personDao = PersonDao; 
} 
@Override 
public  void save(Person person) {
    this.personDao.save(person);
}
3 Adding Spring configuration information
 1 ) was added Bean instance 
created in applicationContext_person.xml PersonDao Bean instance, and the injection personService personDao example, the main code is as follows:
 <-! DAO -> 
<the bean ID = " PersonDao " class =" com.mengma.ssh.dao.impl.PersonDaoImpl "> 
    <Property name =" the sessionFactory "REF =" the sessionFactory "/> 
</ the bean> 
<-!-Service -> 
<the bean ID =" PersonService " class =" com.mengma.ssh.service.impl.PersonServiceImpl "> 
    <-! personService examples of injection of the PersonDao -> 
    <Property name =" PersonDao "REF =" PersonDao "/> 
</ the bean>
2 ) add a configuration transaction 
configuration information in the transaction to add the applicationContext.xml, add code as follows:
 <- transaction manager, depending on the data source -!>
<bean the above mentioned id = "txManager" = "org.springframework.orm.hibernate3.HibernateTransactionManager"> 
    <Property name = "sessionFactory" ref = "sessionFactory" /> 
</ bean> 
<-! Registration Organizer drive -> 
< tx: transaction-Driven-Annotation Manager = "txManager" /> 
<bean the above mentioned id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 
    ! <- notification: enhanced Services -> 
    <tx: advice = the above mentioned id "txAdvice" Transaction-Manager = "txManager"> 
        <tx: the Attributes> 
            ! <- if not to save update delete all configuration, these operations will be invalid -> 
            <tx: name = Method, "the Save *" propagation = "REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
     class
    
            <tx: Method, name = "* the Delete" propagation = "REQUIRED" />tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" />
        </ TX: Attributes> 
    </ TX: the advice> 
    <AOP: config> 
        <-! entry point -> 
        <AOP: = the pointcut expression The "Execution (com.mengma.service * * * (..)..) " 
            ID =" txPointCut "/> 
        <- Advisor special cut (an entry point and a notification) ->! 
        <AOP: Advisor-REF = the pointcut" txPointCut "the advice-REF =" txAdvice "/> 
    </ AOP : config> 
    <- 1.1 file location determining ->! 
    <Property name = "the configLocation" value = "CLASSPATH: Hibernate / the hibernate.cfg.xml" /> 
    ! <- 1.2 hbm.xml mapping configuration file, mappingDirectoryLocationd represents local directory mapping file -> 
    <Property name = "mappingDirectoryLocations" value = "the CLASSPATH:com/mengma/*/domain" />
</bean>
In the above code, the transaction manager arranged first, and then configure the transaction notification information, and finally through the pointcut expression specifying transaction classes are to be controlled. It should be noted that the above code entry point for expressions of expression content, expressed interception at the end of the service of Bean.
4 . Writing Test Methods 
In the test class TestMerge, create a name for the method PersonServiceAndDao, integration and testing Dao Service layer, which code is as follows: 
@Test 
public  void PersonServiceAndDao () { 
    PersonService TS = (PersonService) CTX. the getBean ( "PersonService" ); 
    ts.save ( new new the Person ( "user 2" )); 
} 
in the above code, the first acquired PersonService instance, then the instance to call the save () method to save a name is "user 2" Object. After the successful operation of the above methods using JUnit, data queries of the database person table, results are shown 
which illustrate the integration between the Service and the Dao success. So far, the integration between Hibernate, Struts2 and Spring have been fully completed.

 

 

Verify that the transaction into effect 
the integration of the three framework has been completed, but in order to ensure that the project can run properly, usually before the formal development, but also need to be tested for Spring-managed transactions.
Read-only transaction test methods 
in Spring's transaction management configuration information, only the Find * methods are read-only, read-only method to verify that the transaction is in effect, you can write a findById () method in Dao and in the Service and Service saving increased Person object. If the transaction control is successful, the save operation fails. Here's a read-only follow this way test transaction.
1 . Realize Dao
 1 ) prepared Dao layer interfacing method 
in PersonDao interface, according to a method of increasing the findById query data id (), which method code as follows: 
// The query id 
public the Person the findById (String id);
 2 ) the method of preparation of the DAO implementation class 
implement the method of its implementation class PersonDaoImpl, its code is shown below. 
public the Person the findById (String ID) {
     return the getHibernateTemplate () GET (the Person.. class , ID); 
}
2 . Realize Service
 . 1 ) prepared by the method Service Interface layer 
interface PersonService, create a name for findById method, which methods are as follows: 
// ID queries based 
public the Person findById (String ID);
 2 ) the preparation of Service layer implementation class the method of 
achieving the findById () method implementation class PersonServiceImpl PersonService in which code is as follows: 
public the Person the findById (String ID) { 
    Save ( new new the Person ( "Test" ));
     return personDao.findById (ID); 
} 
in the above method code, save and create a name for the object test, and then returns PersonDao used findById () method to query the information.
3 . The method of preparation of the test run and see the results 
in the test class TestMerge, create a name for testReadOnlyTransaction method using the read-only transaction operation test method, which code is as follows: 
@Test 
public  void testReadOnlyTransaction () { 
    PersonService TS = ( PersonService) ctx.getBean ( "PersonService" );
     // read-only method, a new operation, the control transaction if successful, the failure to add 
    the Person ts.findById P = ( "2028b1816bb607e8016bb60731990000" ); 
    System.err.println ( "person name:" + p.getName ()); 
}  
in the above code, after obtaining the PersonService example, the findById call instance () method (id value method is acquired from the database), in this method, deliberately added a person object, that write data, read-only transactions if the onset, then the transaction will be reported abnormal, the new person will also fail.
using the method described above can be seen running JUnit, testReadOnlyTransaction () method is not executed successfully, and prompted not in read-only mode in the first row in the error message the information write operation. At this time, data query database person table, still two previously saved data.
Test transaction rollback 
test transaction rollback operation is very simple, just like in the save PersonServiceImpl () added last code means " int I =. 1/0 ;", so that, when performing operations to add, to this program runs when the line of code will error. If the transaction control is successful, the new information will be rolled back, otherwise the information will be stored in a database table. Here tested in accordance with the rollback of the transaction in this way. 
First, the code was added in the last save PersonServiceImpl class () method " int I =. 1/0 ;." Then, a test class to create a name for TestMerge testRollbackTransaction method, the code edited as follows: 
@Test 
public  void testRollbackTransaction () { 
    PersonService TS = (PersonService) ctx.getBean ( "PersonService" );
     // in new by methods, intentional errors, if the control transaction is successful, the new information will be rolled back 
    ts.save ( new new the Person ( "user 3" )); 
}
In the above-described method code, the first acquired personService instance object, and then calls the instance object save () method of the new user. After running testRollbackTransaction using JUnit () method, as shown console output 
console dividing the reported abnormal information 0. At this time in person and then query the database data table, you will find data sheets are still two data. This indicates that Spring's transaction manager successfully project transaction operations were controlled.

 

Guess you like

Origin www.cnblogs.com/tszr/p/12151786.html