SSH框架CRUD+樹形菜單案例

今天結合了案例來寫ssh的增刪改查vue

表設計

t_ssh_treejava

t_vue_usernode

 

 bookmysql

 

核心配置文件

 struts-base.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.i18n.encoding" value="UTF-8" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.configuration.xml.reload" value="true" />
    <constant name="struts.i18n.reload" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <package name="base" extends="struts-default" abstract="true">
        <global-allowed-methods>regex:.*</global-allowed-methods>
    </package>
</struts>

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>
    <include file="struts-default.xml"></include>
    <include file="struts-base.xml"></include>
    <include file="struts-sy.xml"></include>
</struts>

spring-hibernate.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 一、註冊jdbc相關的配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 二、配置數據庫鏈接池C3P0 -->
    <!-- 註冊數據庫鏈接文件db.properties -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置c3p0鏈接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
        <property name="driverClass" value="${db.driverClass}"></property>
        <property name="jdbcUrl" value="${db.jdbcUrl}"></property>

        <!--初始化時獲取的鏈接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
        <property name="initialPoolSize" value="${db.initialPoolSize}"></property>
        <!--鏈接池中保留的最大鏈接數。Default: 15 -->
        <property name="maxPoolSize" value="${db.maxPoolSize}"></property>
        <!--鏈接池中保留的最小鏈接數。 -->
        <property name="minPoolSize" value="${db.minPoolSize}" />
        <!--最大空閒時間,60秒內未使用則鏈接被丟棄。若爲0則永不丟棄。Default: 0 -->
        <property name="maxIdleTime" value="${db.maxIdleTime}" />

        <!--當鏈接池中的鏈接耗盡的時候c3p0一次同時獲取的鏈接數。Default: 3 -->
        <property name="acquireIncrement" value="${db.acquireIncrement}" />

        <!--JDBC的標準參數,用以控制數據源內加載的PreparedStatements數量。但因爲預緩存的statements 屬於單個connection而不是整個鏈接池。 
            因此設置這個參數須要考慮到多方面的因素。若是maxStatements與maxStatementsPerConnection均爲0,則緩存被關閉。Default: 
            0 -->
        <property name="maxStatements" value="${db.maxStatements}" />

        <!--每60秒檢查全部鏈接池中的空閒鏈接。Default: 0 -->
        <property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}" />

        <!--定義在從數據庫獲取新鏈接失敗後重復嘗試的次數。Default: 30 -->
        <property name="acquireRetryAttempts" value="${db.acquireRetryAttempts}" />

        <!--獲取鏈接失敗將會引發全部等待鏈接池來獲取鏈接的線程拋出異常。可是數據源仍有效 保留,並在下次調用getConnection()的時候繼續嘗試獲取鏈接。 
            若是設爲true,那麼在嘗試 獲取鏈接失敗後該數據源將申明已斷開並永久關閉。Default: false -->
        <property name="breakAfterAcquireFailure" value="${db.breakAfterAcquireFailure}" />

        <!--因性能消耗大請只在須要的時候使用它。若是設爲true那麼在每一個connection提交的 時候都將校驗其有效性。建議使用idleConnectionTestPeriod 
            或automaticTestTable 等方法來提高鏈接測試的性能。Default: false -->
        <property name="testConnectionOnCheckout" value="${db.breakAfterAcquireFailure}" />
    </bean>

    <!-- 三、配置sessionfactory相關信息 -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 數據源 -->
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <!-- hibernate相關屬性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
                <!--spring與Hibernate集成沒法顯示sql語句問題,請見集成後hibernate沒法顯示sql語句.txt -->
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <!-- 實體映射文件 -->
        <property name="mappingResources">
            <list>
                <value>com/ht/vue/entity/Book.hbm.xml</value>
            </list>
        </property>
    </bean>

    <!-- 四、配置事務 -->
    <!--聲明式事務配置開始 -->
    <!-- 
        靜態代理:
            一個代理對象->一個目標對象
            BookProxy(BookBizImpl+myMethodBeforeAdvice)->bookBiz
            OrderProxy(OrderBizImpl+myMethodBeforeAdvice2)->    OrderBiz
        
        動態代理:
            一個代理對象->多個目標對象
     -->
    
    <!--1) 開啓自動代理 -->
    <aop:aspectj-autoproxy />

    <!--2) 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!--3) 定義事務特性 -->
    <!-- 下面定義了增刪改查的事物規則,意味着只有符合下面命名規則的方法,纔會獲取到session,以及提交事務 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />

            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />

            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />

            <tx:method name="load*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="select*" propagation="REQUIRED" read-only="true" />
            <tx:method name="query*" propagation="REQUIRED" read-only="true" />

            <tx:method name="do*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>

    <!--4) 定義切入點 -->
    <aop:config>
        <!-- pointcut屬性用來定義一個切入點,分紅四個部分理解 [* ][*..][*Biz][.*(..)] -->
        <!-- A: 返回類型,*表示返回類型不限 -->
        <!-- B: 包名,*..表示包名不限 -->
        <!-- C: 類或接口名,*Biz表示類或接口必須以Biz結尾 -->
        <!-- D: 方法名和參數,*(..)表示方法名不限,參數類型和個數不限 -->
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..*Biz.*(..))" />
    </aop:config>
    <!-- 聲明式事務配置結束 -->

    <!-- 五、配置HibernateTemplate session-->
    <bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 六、分模塊開發(只配置base模塊) -->
    <bean class="com.ht.base.entity.BaseEntity" abstract="true" id="baseEntity"></bean>
    <bean class="com.ht.base.dao.BaseDao" abstract="true" id="baseDao" >
        <property name="hibernateTemplate" ref="hibernateTemplate"></property>
    </bean>
    <bean class="com.ht.base.biz.BaseBiz" abstract="true" id="baseBiz"></bean>
    <bean class="com.ht.base.web.BaseAction" abstract="true" id="baseAction"></bean>
</beans>

spring-context.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
     <import resource="spring-hibernate.xml"/>
    <import resource="spring-vue.xml"/>
 </beans>

db.properties(鏈接數據庫)

db.username=root
db.password=root
db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://127.0.0.1:3306/ht?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
db.initialPoolSize=10
db.maxPoolSize=20
db.minPoolSize=5
db.maxIdleTime=60
db.acquireIncrement=5
db.maxStatements=0
db.idleConnectionTestPeriod=60
db.acquireRetryAttempts=30
db.breakAfterAcquireFailure=true
db.testConnectionOnCheckout=false

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- status : 指定log4j自己的打印日誌的級別.ALL< Trace < DEBUG < INFO < WARN < ERROR 
    < FATAL < OFF。 monitorInterval : 用於指定log4j自動從新配置的監測間隔時間,單位是s,最小是5s. -->
<Configuration status="WARN" monitorInterval="30">
    <Properties>
        <!-- 配置日誌文件輸出目錄 ${sys:user.home} -->
        <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
        <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
        <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
    </Properties>

    <Appenders>
        <!--這個輸出控制檯的配置 -->
        <Console name="Console" target="SYSTEM_OUT">
            <!-- 控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch) -->
            <ThresholdFilter level="trace" onMatch="ACCEPT"
                onMismatch="DENY" />
            <!-- 輸出日誌的格式 -->
            <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日誌生產時間 %p : 日誌輸出格式 %c : logger的名稱 
                %m : 日誌內容,即 logger.info("message") %n : 換行符 %C : Java類名 %L : 日誌輸出所在行數 %M 
                : 日誌輸出所在方法名 hostName : 本地機器名 hostAddress : 本地ip地址 -->
            <PatternLayout pattern="${PATTERN}" />
        </Console>

        <!--文件會打印出全部信息,這個log每次運行程序會自動清空,由append屬性決定,這個也挺有用的,適合臨時測試用 -->
        <!--append爲TRUE表示消息增長到指定文件中,false表示消息覆蓋指定的文件內容,默認值是true -->
        <File name="log" fileName="logs/test.log" append="false">
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
        <!-- 這個會打印出全部的info及如下級別的信息,每次大小超過size, 則這size大小的日誌會自動存入按年份-月份創建的文件夾下面並進行壓縮,做爲存檔 -->
        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
            filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制檯只輸出level及以上級別的信息(onMatch),其餘的直接拒絕(onMismatch) -->
            <ThresholdFilter level="info" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- 基於時間的滾動策略,interval屬性用來指定多久滾動一次,默認是1 hour。 modulate=true用來調整時間:好比如今是早上3am,interval是4,那麼第一次滾動是在4am,接着是8am,12am...而不是7am. -->
                <!-- 關鍵點在於 filePattern後的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精確到哪一位,interval也精確到哪個單位 -->
                <!-- log4j2的按天分日誌文件 : info-%d{yyyy-MM-dd}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- SizeBasedTriggeringPolicy:Policies子節點, 基於指定文件大小的滾動策略,size屬性用來定義每一個日誌文件的大小. -->
                <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
            </Policies>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
            filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="2 kB" />
            </Policies>
            <!-- DefaultRolloverStrategy屬性如不設置,則默認爲最多同一文件夾下7個文件,這裏設置了20 -->
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
            filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT"
                onMismatch="DENY" />
            <PatternLayout
                pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <!-- log4j2的按分鐘 分日誌文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
                <TimeBasedTriggeringPolicy interval="1"
                    modulate="true" />
                <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
            </Policies>
        </RollingFile>

    </Appenders>

    <!--而後定義logger,只有定義了logger並引入的appender,appender纔會生效 -->
    <Loggers>
        <!--過濾掉spring和mybatis的一些無用的DEBUG信息 -->
        <logger name="org.springframework" level="INFO"></logger>
        <logger name="org.mybatis" level="INFO"></logger>

        <!-- 第三方日誌系統 -->
        <logger name="org.springframework" level="ERROR" />
        <logger name="org.hibernate" level="ERROR" />
        <logger name="org.apache.struts2" level="ERROR" />
        <logger name="com.opensymphony.xwork2" level="ERROR" />
        <logger name="org.jboss" level="ERROR" />


        <!-- 配置日誌的根節點 -->
        <root level="all">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        </root>

    </Loggers>

</Configuration>

webx.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- 
      spring與web整合須要監聽器         spring  ioc        spring-web.jar
      整合struts框架,配置strutsPrepareAndExecuteFilter
      要處理jsp傳遞到後臺的中文亂碼問題    配置過濾器    spring的過濾器
      防止內存溢出的配置
   -->
   <!-- 一、整合spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context.xml</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <!-- 二、整合struts2 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

    <!-- 三、添加過濾器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

SSH的CRUD

  • 用戶登錄註冊模塊

實體類

User

package com.ht.user.entity;

public class User {

    private String uname;
    private String pwd;
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User [uname=" + uname + ", pwd=" + pwd + "]";
    }
    
}

對應映射文件 user.hbm.xml

<?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>
    <class table="t_vue_user" name="com.ht.user.entity.User">
        
        <id name="uname" type="java.lang.String" column="uname">
            <generator class="assigned"></generator>
        </id>
        <property name="pwd" type="java.lang.String" column="pwd"></property>
    </class>
</hibernate-mapping>

Biz層(接口的實現)

userbiz

package com.ht.user.biz;

import com.ht.user.entity.User;

public interface UserBiz {

    /**
     * 登陸
     * @param user
     * @return
     */
    public User login(User user);
    
    /**
     * 註冊
     * @param user
     * @return
     */
    public int addUser(User user);
}

userbizipml(實現類)

package com.ht.user.biz.ipml;

import com.ht.user.biz.UserBiz;
import com.ht.user.dao.UserDao;
import com.ht.user.entity.User;

public class UserBizImpl implements UserBiz{
    
    private UserDao userDao;
    

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User login(User user) {
        return userDao.login(user);
    }

    @Override
    public int addUser(User user) {
        return userDao.addUser(user);
    }
}

dao層

Userdao

package com.ht.user.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.ht.base.dao.BaseDao;
import com.ht.user.entity.User;

public class UserDao extends BaseDao{

    private static final long serialVersionUID = 3670806315799801488L;

    /**
     * 登陸
     * @param user
     * @return
     */
    public User login(User user) {
        return this.getHibernateTemplate().execute(new HibernateCallback<User>() {

            @Override
            public User doInHibernate(Session session) throws HibernateException {
                return (User) session.createQuery("from User where uname= '"+user.getUname()+"' and pwd= "+user.getPwd()).list();
            }
        });
    }
    /**
     * 註冊
     * @param user
     * @return
     */
    public int addUser(User user) {
        return (int) this.getHibernateTemplate().save(user);
    }
    
}

web層(控制層)

package com.ht.user.web;

import com.ht.base.web.BaseAction;
import com.ht.user.biz.UserBiz;
import com.ht.user.entity.User;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends BaseAction implements ModelDriven<User> {

    private static final long serialVersionUID = 4244808665377509950L;

    private UserBiz userBiz;
    private User user = new User();

    public UserBiz getUserBiz() {
        return userBiz;
    }

    public void setUserBiz(UserBiz userBiz) {
        this.userBiz = userBiz;
    }

    /**
     * 登陸
     * @return
     */
    public String login() {
        userBiz.login(user);
        return null;
    }

    /**
     * 註冊
     * @return
     */
    public String addUser() {
        userBiz.addUser(user);
        return null;
    }

    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }

}
  • 樹形菜單的實現模塊

實體類

TreeNode

package com.ht.tree.entity;

import java.util.HashSet;
import java.util.Set;

public class TreeNode {
        private Integer nodeId;
        private String nodeName;
        private Integer treeNodeType;
        private Integer position;
        private String url;
        //關聯父節點
        private TreeNode parent;
        //關聯子節點
        private Set<TreeNode> children = new HashSet<TreeNode>();
        //加載方式(1強制加載關聯,0懶加載)
        private Integer initChildren = 0;
     
        public Integer getNodeId() {
            return nodeId;
        }

        public void setNodeId(Integer nodeId) {
            this.nodeId = nodeId;
        }

        public String getNodeName() {
            return nodeName;
        }

        public void setNodeName(String nodeName) {
            this.nodeName = nodeName;
        }

        public Integer getTreeNodeType() {
            return treeNodeType;
        }

        public void setTreeNodeType(Integer treeNodeType) {
            this.treeNodeType = treeNodeType;
        }

        public Integer getPosition() {
            return position;
        }

        public void setPosition(Integer position) {
            this.position = position;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public TreeNode getParent() {
            return parent;
        }

        public void setParent(TreeNode parent) {
            this.parent = parent;
        }

        public Set<TreeNode> getChildren() {
            return children;
        }

        public void setChildren(Set<TreeNode> children) {
            this.children = children;
        }

        public Integer getInitChildren() {
            return initChildren;
        }

        public void setInitChildren(Integer initChildren) {
            this.initChildren = initChildren;
        }
     
        
}

對應映射文件 TreeNode.hbm.xml

<?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>
    <class table="t_ssh_tree" name="com.ht.tree.entity.TreeNode">
         <id name="nodeId" type="java.lang.Integer" column="tree_node_id">
            <generator class="increment" />
        </id>
        <property name="nodeName" type="java.lang.String"
                  column="tree_node_name">
        </property>
        <property name="treeNodeType" type="java.lang.Integer"
                  column="tree_node_type">
        </property>
        <property name="position" type="java.lang.Integer"
                  column="position">
        </property>
        <property name="url" type="java.lang.String"
                  column="url">
        </property>
        <!--
            parent定義了管理樹形
            column中指定了經過那個列段來關聯 對應的是當前表的主鍵
         -->
        <many-to-one name="parent" class="com.ht.tree.entity.TreeNode" column="parent_node_id"/>

        <!--
            這是定義子節點關聯
         -->
        <set name="children" cascade="save-update" inverse="true">
            <!--凡是parent_node_id是當前節點的tree_node_id的就通通加入集合-->
            <key column="parent_node_id"></key>
            <one-to-many class="com.ht.tree.entity.TreeNode"/>
        </set>

    </class>
</hibernate-mapping>

接口層

treenodeBiz

package com.ht.tree.biz;

import java.util.List;

import com.ht.tree.entity.TreeNode;

public interface TreeNodeBiz {

    /**
     * 加載樹
     * @return
     */
    public List<TreeNode> list();
}

treenodeBizipml(實現接口)

package com.ht.tree.biz.ipml;

import java.util.List;

import com.ht.tree.biz.TreeNodeBiz;
import com.ht.tree.dao.TreeNodeDao;
import com.ht.tree.entity.TreeNode;

public class TreeNodBizImpl implements TreeNodeBiz{
    
    private TreeNodeDao treeNodeDao;
    

    public TreeNodeDao getTreeNodeDao() {
        return treeNodeDao;
    }


    public void setTreeNodeDao(TreeNodeDao treeNodeDao) {
        this.treeNodeDao = treeNodeDao;
    }


    @Override
    public List<TreeNode> list() {
        // TODO Auto-generated method stub
        return treeNodeDao.list();
    }

}

dao層

treenodedao

package com.ht.tree.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Session;

import com.ht.base.dao.BaseDao;
import com.ht.tree.entity.TreeNode;
public class TreeNodeDao extends BaseDao{

    private static final long serialVersionUID = 1747719616550054042L;

    public List<TreeNode> list(){
        Session session = this.getHibernateTemplate().getSessionFactory().openSession();
        session.beginTransaction();
        //這是最好的作法  使用 hql語句進行查詢
        List<TreeNode> treeNodes =  super.executeQuery(session, "from TreeNode where treeNodeType = 1", null,null);
        //進行強子加載子節點
        if (treeNodes != null && treeNodes.size() > 0) {
            for (TreeNode t : treeNodes) {
                //強制加載子節點
                Hibernate.initialize(t.getChildren());
            }
        }
        return treeNodes;
    }
}

web層

treenodeaction

package com.ht.tree.web;

import java.util.List;

import com.ht.base.web.BaseAction;
import com.ht.tree.biz.TreeNodeBiz;
import com.ht.tree.entity.TreeNode;

public class TreeNodeAction extends BaseAction {
    private static final long serialVersionUID = -2131750933479280540L;
    private TreeNodeBiz treeNodeBiz;

    public TreeNodeBiz getTreeNodeBiz() {
        return treeNodeBiz;
    }

    public void setTreeNodeBiz(TreeNodeBiz treeNodeBiz) {
        this.treeNodeBiz = treeNodeBiz;
    }

    public String list() {
        List<TreeNode> list = treeNodeBiz.list();
        System.out.println("我是長度" + list.size());
        TreeNode node = list.get(0);
        System.out.println(node);
        System.out.println(node.getChildren());
        for (TreeNode n : node.getChildren()) {
            System.out.println("我是子節點:" + n.getNodeName());
        }
        return null;
    }
}
  • 書本管理crud模塊

實體類

book

package com.ht.vue.entity;

import com.ht.base.entity.BaseEntity;

public class Book extends BaseEntity{
    private static final long serialVersionUID = 4560750691234829021L;

    private Integer bid;
    private String bname;
    private float price;
    public Integer getBid() {
        return bid;
    }
    public void setBid(Integer bid) {
        this.bid = bid;
    }
    public String getBname() {
        return bname;
    }
    public void setBname(String bname) {
        this.bname = bname;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public Book(Integer bid, String bname, float price) {
        this.bid = bid;
        this.bname = bname;
        this.price = price;
    }
    public Book() {
        super();
    }
    @Override
    public String toString() {
        return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
    }
    
}

對應映射文件book.hbm.xml

<?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>
    <class table="book" name="com.ht.book.entity.Book">
        <id name="bid" type="java.lang.Integer" column="bookId">
            <generator class="increment"></generator>
        </id>
        
        <property name="bname" type="java.lang.String" column="bookName"></property>
        <property name="price" type="java.lang.Float" column="price"></property>
    </class>
</hibernate-mapping>

接口層

bookbiz

package com.ht.vue.biz;

import java.util.List;

import com.ht.base.util.PageBean;
import com.ht.vue.entity.Book;

public interface BookBiz {
    /**
     * 新增
     * @param book
     * @return
     */
    public int add(Book book);
    
    /**
     * 修改
     * @param book
     */
    public void update(Book book);
    /**
     * 刪除
     * @param book
     */
    public void del(Book book);
    /**
     * 查詢
     * @return
     */
    public List<Book> list(Book book,PageBean paBean);
}

實現接口bookbizipml

package com.ht.vue.biz.ipml;

import java.util.List;

import com.ht.base.util.PageBean;
import com.ht.vue.biz.BookBiz;
import com.ht.vue.dao.BookDao;
import com.ht.vue.entity.Book;

public class BookBizipml implements BookBiz {
    private BookDao bookDao;

    public BookDao getBookDao() {
        return bookDao;
    }

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public int add(Book book) {
        return bookDao.add(book);
    }

    @Override
    public void update(Book book) {
        // TODO Auto-generated method stub

    }

    @Override
    public void del(Book book) {
        // TODO Auto-generated method stub

    }

    @Override
    public List<Book> list(Book book, PageBean paBean) {
        // TODO Auto-generated method stub
        return null;
    }

}

dao層

bookdao

package com.ht.vue.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.ht.base.dao.BaseDao;
import com.ht.base.util.PageBean;
import com.ht.vue.entity.Book;


public class BookDao extends BaseDao{
    private static final long serialVersionUID = 3690986491850123494L;
    /**
     * 新增
     * @param book
     * @return
     */
    public int add(Book book) {
     return    (int) this.getHibernateTemplate().save(book);
    }

    /**
     * 查詢
     * @return
     */
    public List<Book> list(Book book, PageBean pageBean){
        Session session = this.getHibernateTemplate().getSessionFactory().openSession();
        session.beginTransaction();
        //這是最好的作法 使用 hql語句進行查詢
        return super.executeQuery(session, "from Book", null,pageBean);
     }    

    /**
     * 修改
     * @param articles
     */
    public void update(Book book) {
        this.getHibernateTemplate().update(book);
    }
    /**
     * 
     * 刪除
     * @param articles
     */
    public void del(Book book) {
        this.getHibernateTemplate().delete(book);
    }
    
}

web層

bookaction

package com.ht.vue.web;

import java.util.List;

import com.ht.base.web.BaseAction;
import com.ht.vue.biz.BookBiz;
import com.ht.vue.entity.Book;
import com.opensymphony.xwork2.ModelDriven;

public class BookAction extends BaseAction implements ModelDriven<Book>{
    private static final long serialVersionUID = -5631093170850951408L;

    private Book book=new Book();
    private BookBiz bookBiz;

    public BookBiz getBookBiz() {
        return bookBiz;
    }

    public void setBookBiz(BookBiz bookBiz) {
        this.bookBiz = bookBiz;
    }
    
    /**
     * 新增
     * @return
     */
    public String add() {
        this.bookBiz.add(book);
        return null;
    }

    /**
     * 修改
     * @return
     */
    public String update() {
        bookBiz.update(book);
        return null;        
    }
    
    /**
     * 查詢
     * @return
     */
    public String list() {
        System.out.println(bookBiz.list(book, null));
        return null;
    }
    /**
     * 刪除
     */
    public void del() {
        bookBiz.del(book);
    }
    @Override
    public Book getModel() {
        // TODO Auto-generated method stub
        return book;
    }
    
}

 

注意:配置文件很重要,寫完一個模塊要配置相對應的文件

spring-vue.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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!-- user -->
    <bean id="userDao" class="com.ht.user.dao.UserDao" parent="baseDao"></bean>
    <bean id="userBiz" class="com.ht.user.biz.ipml.UserBizImpl" parent="baseBiz">
        <property name="userDao" ref="userDao"></property>
    </bean>
    <bean id="userAction" class="com.ht.user.web.UserAction"  parent="baseAction">
        <property name="userBiz" ref="userBiz"></property>
    </bean>
    <!--TreeNode-->
    <bean id="treeNodeDao" class="com.ht.tree.dao.TreeNodeDao" parent="baseDao"></bean>
    <bean id="treeNodeBiz" class="com.ht.tree.biz.ipml.TreeNodBizImpl" parent="baseBiz">
        <property name="treeNodeDao" ref="treeNodeDao"></property>
    </bean>
    <bean id="treeNodeAction" class="com.ht.tree.web.TreeNodeAction" parent="baseAction">
        <property name="treeNodeBiz" ref="treeNodeBiz"></property>
    </bean>
    <!-- book -->
    <bean id="bookDao" class="com.ht.vue.dao.BookDao" parent="baseDao"></bean>    
        <bean id="bookBiz" class="com.ht.vue.biz.ipml.BookBizipml" parent="baseBiz">
            <property name="bookDao" ref="bookDao"></property>
        </bean>
        <bean id="bookAction" class="com.ht.tree.web.TreeNodeAction" parent="baseAction">
            <property name="bookBiz" ref="bookBiz"></property>
        </bean>
</beans>

struts-sy.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>
    <package name="sy" extends="base" namespace="/sy">
    <!-- 這裏的class再也不是全路徑名了,而是spring所管理的Bean的id -->
        <action name="/user_*" class="userAction" method="{1}"></action>
        <action name="/treeNode_*" class="treeNodeAction" method="{1}"></action>
        <action name="/book_*" class="bookAction" method="{1}"></action>
    </package>
</struts>

 

謝謝觀看!

相關文章
相關標籤/搜索