SSH integration: Spring 5.2.2 + struts 2.5.22 + Hibernate 5.8

Posted by landonmkelsey on Sun, 12 Jan 2020 15:46:14 +0100

SSH integration: Spring 5.2.2 + struts 2.5.22 + Hibernate 5.8

1, Environment construction

Database: MySQL 8
JDK: 13

jar package

  • Spring
  • Struts
  • Hibernate
  • Spring integrates Hibernate
  • Struts integrates Spring
  • -C3p0
  • Connect to database
  • Using Hibernate above JDK8 requires importing

2, Spring integrates Hibernate with case writing of hibernate.cfg.xml

1. Create tables, create mapping classes, and configure mapping class profiles

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!--When the table name and class name are the same, table It can be omitted when the property name and field name are the same column It can be omitted.-->
    <class name="Full class name with package of mapping class" table="The name of the table in the database corresponding to the class">
        <id name="id" column="Field name">
            <generator class="native"></generator>
        </id>
        <property name="General attribute" column="Field name"></property>
    </class>
</hibernate-mapping>

2. dao level

public class UserDaoImpl implements UserDao {
	//Using the HibernateTemplate template
    private HibernateTemplate hibernateTemplate;
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }
    @Override
    public void save(User user) {
        this.hibernateTemplate.save(user);
    }
}

3.Service level

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public void save(User user) {
        userDao.save(user);
    }
}

4.Hibernate configuration file hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--Configure database dialect-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!--Configuration printing SQL Sentence-->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <!--Load the configuration file for the mapping class-->
        <mapping resource="spring_hibernate/User.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

5.Spring configuration file applicationContext.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!--To configure C3P0 Database connection pool-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo?useSSL=false&amp;serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123"></property>
    </bean>
    <!--HibernateTemplate Bottom use Hibernate Session,Hibernate Session From SessionFactory From,
    //SessionFactory is the configuration file that the database has obtained from hibernate.cfg.xml -- >
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:spring_hibernate/hibernate.cfg.xml"></property>
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--To configure UserDaoImpl Of bean-->
    <bean id="userDao" class="spring_hibernate.dao.impl.UserDaoImpl">
        <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>
    <!--To configure UserDaoService Of bean-->
    <bean id="userService" class="spring_hibernate.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <!--Configure transaction manager HibernateTransactionManager-->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <!--Transaction manager needs transaction, transaction gets from connection-->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--Configure transaction notification, transaction manager is required for transaction notification-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--Configure transaction notification details-->
        <tx:attributes>
            <tx:method name="save"/>
        </tx:attributes>
    </tx:advice>
    <!--Configuration entry point-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* spring_hibernate.service..*.*(..))"></aop:advisor>
    </aop:config>
</beans>

6. test class

//Spring integrates JUnit
@RunWith(SpringJUnit4ClassRunner.class)
//Load applicationContext.xml
@ContextConfiguration(locations = "classpath:spring_hibernate/applicationContext.xml")
public class testApp {
    @Autowired
    private UserService userService;
    @Test
    public void test(){
        User user = new User();
        user.setUsername("Jack");
        user.setPassword("123");
        user.setAge(12);
        userService.save(user);
    }
}

3, Spring integrates Hibernate without hibernate.cfg.xml and the case writing of dao layer inheriting HibernateDaoSupport

1. Modify dao layer

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
    @Override
    public void save(User user) {
        //Get HibernateTemplate from the parent class HibernateDaoSupport
        this.getHibernateTemplate().save(user);
    }
}

2. Delete hibernate.cfg.xml and configure some configuration of hibernate to applicationContext.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--To configure c3p0 Database connection pool-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo?useSSL=false&amp;serverTimezone=UTC"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123"></property>
    </bean>
    <!--sessionFactory Used to create Hibernate Session object-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!--Database connection required-->
        <property name="dataSource" ref="dataSource"></property>
        <!--Configuration in the past hibernate.cfg.xml Some other properties in-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <!--The location of the configuration mapping class profile, mappingLocation Wildcards are supported*-->
        <property name="mappingLocations" value="classpath:spring_hibernate/*/User.hbm.xml"></property>
    </bean>
    <!--To configure UserDaoImpl Of bean-->
    <!--because UserDaoImpl Inherited HibernateDaoSupport,Bottom needs sessionFactory-->
    <bean id="userDao" class="spring_hibernate.dao.impl.UserDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--To configure UserDaoService Of bean-->
    <bean id="userService" class="spring_hibernate.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <!--Configure transaction manager HibernateTransactionManager-->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <!--Transaction manager needs transaction, transaction gets from connection-->
        <!--<property name="dataSource" ref="dataSource"></property>-->
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--Configure transaction notification, transaction manager is required for transaction notification-->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!--Configure transaction notification details-->
        <tx:attributes>
            <tx:method name="save"/>
        </tx:attributes>
    </tx:advice>
    <!--Configuration entry point-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* spring_hibernate.service..*.*(..))"></aop:advisor>
    </aop:config>
</beans>

4, Struts integrates Spring

1. Create Action

public class UserAction extends ActionSupport implements ModelDriven<User> {
	//Model driven encapsulation data
    User user = new User();
    @Override
    public User getModel() {
        return user;
    }
	//Spring dynamic injection userService
    private UserService userService;
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    
    public String save(){
        userService.save(user);
        return "success";
    }
}

2. Configure Action bean in applicationContext

<bean id="userAction" class="spring_hibernate.action.UserAction">
        <property name="userService" ref="userService"></property>
</bean>

3. Configure struts.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <!--<constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>-->
    <package name="default" namespace="/" extends="struts-default">
       	<!--struts2.5 Using wildcard access action This property must be configured-->
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <!--Because in applicationContext.xml Middle configuration Action Of bean therefore class Just direct reference-->
        <action name="userAction_*" class="userAction" method="{1}">
            <result>/success.jsp</result>
        </action>
    </package>
</struts>

Note: if the id of userservice in applicationContext.xml has the same name as the attribute of userservice in action, step 2 can be omitted. Change the class of action in step 3 to the fully qualified class name

So modify struts.xml

4. Write index.jsp

<form action="${pageContext.request.contextPath}/userAction_save.action" method="post">
      Name: < input type = "text" name = "username" / >
      Password: < input type = "password" name = "password" / >
      Age: < input type = "text" name = "age" / >
      < input type = "submit" value = "submit" / >
</form>
Published 13 original articles, won praise 0, visited 2070
Private letter follow

Topics: Hibernate xml Spring Struts