以继承的思想写Spring mvc + spring + hibernate + maven 连接 mysql数据库

以继承的思想写Spring mvc + spring + hibernate 链接 mysql

在写ssh中发现有很多重复的代码,本人比较懒不愿写重复的方法。学习oop是为了省略代码量。两者结合就有了今天的代码。
原理
创建一个父类的表(虚拟表),实现一些重复的方法,用子类的调用父类的方法。
实际
父类:obj
子类:user

文件目录

在这里插入图片描述

  • pom.xml
  <!-- hibernate  start -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.11.Final</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <dependency>
      <groupId>javax.transaction</groupId>
      <artifactId>jta</artifactId>
      <version>1.1</version>
    </dependency>
    <!-- hibernate  end -->
    <!--数据源-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.18</version>
    </dependency>
    <!--数据库驱动包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!-- Spring start -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.8</version>
    </dependency>
    <!-- Spring end -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.21</version>
    </dependency>
    <!-- sturts2 start -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId>
      <version>2.3.24</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework </groupId>
          <artifactId>spring-beans</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework </groupId>
          <artifactId>spring-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework </groupId>
          <artifactId>spring-context</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.springframework </groupId>
          <artifactId>spring-web</artifactId>
        </exclusion>
        <exclusion>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.2</version>
    </dependency>
    <!-- sturts2 end -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <!--可以用c:if-->
    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  • db.properties数据库配置
#数据库驱动 如果不配置,系统会根据url自动识别 这里是druid包的原因
#driverClassName=com.mysql.jdbc.Driver
#URL
druid.url=jdbc:mysql://127.0.0.1:3306/ssh
#用户名
druid.username=root
#密码
druid.password=root
filters=stat
druid.initialSize=5
#最大连接池数量
druid.maxActive=300
#获取连接时最大等待时间,单位毫秒
druid.maxWait=60000
#Destroy线程会检测连接的间隔时间
druid.timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql,要求是一个查询语句
validationQuery=SELECT 1
#建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,
#如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
  • 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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.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
		http://www.springframework.org/schema/jee
		http://www.springframework.org/schema/jee/spring-jee.xsd">
    <!-- 引入外部资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 引入事务配置文件 -->
    <import resource="classpath:applicationContext-tx.xml"/>
    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.mokong"></context:component-scan>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 数据库连接地址 -->
        <property name="url" value="${druid.url}"></property>
        <!-- 用户名 -->
        <property name="username" value="${druid.username}"></property>
        <!-- 密码 -->
        <property name="password" value="${druid.password}"></property>
        <!-- 最大连接池数量 -->
        <property name="maxActive" value="${druid.maxActive}"></property>
        <!-- 初始化连接数 -->
        <property name="initialSize" value="${druid.initialSize}"></property>
        <!-- 获取连接时最大等待时间,单位毫秒 -->
        <property name="maxWait" value="${druid.maxWait}"></property>
        <!-- Destroy线程会检测连接的间隔时间 -->
        <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"></property>
    </bean>
    <!-- Session工厂配置 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 通过configLocations可以加载并读取hibernate的全局配置文件 -->
        <!-- <property name="configLocations" value="classpath:hibernate.cfg.xml"></property> -->
        <!-- hibernate相关配置 -->
        <property name="hibernateProperties">
            <props>
                <!-- 数据库方言 -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <!-- 是否显示sql -->
                <prop key="hibernate.show_sql">true</prop>
                <!--是否让sql格式化  -->
                <prop key="hibernate.format_sql">true</prop>
                <!-- 是否通过实体类自动生成数据库表 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <!-- 如果使用配置映射文件的方式 -->
        <!-- <property name="mappingResources">
            <list>
                <value>xxxx.hbm.xml</value>
            </list>
        </property> -->
        <!-- 扫描实体类注解所在包 -->
        <property name="packagesToScan" value="com.mokong.*.model"></property>
    </bean>
</beans>
  • applicationContext-tx.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: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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!--   事务管理器 -->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <!-- 管理数据源 -->
       <property name="dataSource" ref="dataSource"></property>
   </bean>
   <!-- 通知 -->
   <tx:advice id="txAdvice" transaction-manager="transactionManager">
       <!-- 事务的传播行为 -->
       <tx:attributes>
           <!-- 必须开启事务 -->
           <tx:method name="add*" propagation="REQUIRED"/>
           <tx:method name="save*" propagation="REQUIRED"/>
           <tx:method name="update*" propagation="REQUIRED"/>
           <tx:method name="modify*" propagation="REQUIRED"/>
           <tx:method name="delete*" propagation="REQUIRED"/>
           <tx:method name="remove*" propagation="REQUIRED"/>
           <!-- 只读事务 -->
           <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
           <tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
           <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
           <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
       </tx:attributes>
   </tx:advice>
   <!--   配置切面 -->
   <aop:config>
       <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.mokong.*.service..*.*(..))"/>
   </aop:config>
</beans>
  • log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  • struts.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <package name="user" namespace="/" extends="struts-default">
    <!--<package name="user" extends="struts-default" namespace="/">-->
        <action name="user-*" class="userWeb" method="{1}">
            <result name="error">/hint/error.jsp</result>
            <result name="save">/user/userList.jsp</result>
        </action>
    </package>

</struts>
  • web.xml
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--  加载Spring的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- spring监听 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- struts2前端控制器 -->
  <filter>
    <filter-name>struts</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>

  <!-- openSessionInView -->
  <filter>
    <filter-name>openSessionInView</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>openSessionInView</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
  • 父类Obj
package com.mokong.obj.model;

import javax.persistence.*;

/**
 * Created by Administrator on 2018/10/19.
 */
@MappedSuperclass
public class Obj {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    public Obj() {

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

}
  • 父类Dao层接口ObjDaoI
package com.mokong.obj.dao;

import java.util.*;

/**
 * Created by Administrator on 2018/10/19.
 */
public interface ObjDaoI<T> {
    public List<T> findAllByCondition(String hql, Map<String, Object> map);
    public T findTById(T t, Integer id);
    public List<T> findAll(String hql);
    public void deleteT(T t);
    public void updateT(T t);
    public Integer saveT(T t);
    public Integer count(String hql);
}
  • 父类Dao层接口实现类ObjDao
package com.mokong.obj.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/19.
 */
@Repository
public class ObjDao<T>{
    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public Session getCurrentSession(){
        if(sessionFactory!=null){
            return sessionFactory.getCurrentSession();
        }
        return null;
    }

    /**
     * 公共的添加方法
     * @param t
     * @return
     */
    public Integer saveT(T t){
        Serializable num = getCurrentSession().save(t);
        Integer n= (Integer) num;
        return n;
    }
    /**
     * 公共的添加方法
     * @param t
     * @return
     */
    public void updateT(T t){
        getCurrentSession().update(t);
    }
    /**
     * 公共的删除方法
     * @param t
     * @return
     */
    public void deleteT(T t){
        getCurrentSession().delete(t);
    }

    /**
     * 公共的查询方法
     */
    public List<T> findAll(String hql){
        List<T> list = getCurrentSession().createQuery(hql).list();
        return list;
    }
    /**
     * 公共的查询方法带条件的查询
     */
    public List<T> findAllByCondition(String hql,Map<String,Object> map){
        List<T> list = getCurrentSession().createQuery(hql).setProperties(map).list();
        return list;
    }
    /**
     * 公共的查询方法通过Id查询
     */
    public T findTById(T t,Integer id){
        T t2= (T) getCurrentSession().get(t.getClass(),id);
        return t;
    }

    /**
     * 查询count
     */
    public Integer count(String hql){
        Long l = (Long) getCurrentSession().createQuery(hql).uniqueResult();
        return  l.intValue();
    }
}
  • 父类service层接口ObjServiceI
package com.mokong.obj.service;

import java.util.*;

/**
 * Created by Administrator on 2018/10/19.
 */
public interface ObjServiceI<T> {
    public List<T> findAllByCondition(String hql, Map<String,Object> map);
    public T findTById(T t,Integer id);
    public List<T> findAll(String hql);
    public String deleteT(T t);
    public String updateT(T t);
    public String saveT(T t);
}
  • 父类service层接口实现类
package com.mokong.obj.service;

import com.mokong.obj.dao.ObjDaoI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/19.
 */

public class ObjService<T> {
    @Autowired
    private ObjDaoI<T> objDao;
//    public List<T> findAllByCondition(String hql, Map<String,Object> map);
    public List<T> findAllByCondition(String hql, Map<String,Object> map){
        return objDao.findAllByCondition(hql,map);
    }
//    public T findTById(T t,Integer id);
    public T findTById(T t,Integer id){
       return objDao.findTById(t,id);
    }
//    public List<T> findAll(String hql);
    public List<T> findAll(String hql){
        return objDao.findAll(hql);
    }
//    public String deleteT(T t);
    public String deleteT(T t){
        objDao.deleteT(t);
        return "chenggong";
    }
//    public String updateT(T t);
    public String updateT(T t){
        objDao.updateT(t);
        return "chenggong";
    }
//    public String saveT(T t);
    public String saveT(T t){
        Integer i = objDao.saveT(t);
        return i>0?"chenggong":"shibai";
    }
}
  • 子类User 对应的数据库表是t_user
package com.mokong.user.model;

import com.mokong.obj.model.Obj;

import javax.persistence.*;

/**
 * Created by Administrator on 2018/10/19.
 */
@Entity
@Table(name = "t_user")
public class User extends Obj {
    @Column
    private String userName;
    @Column
    private String password;

    public User() {
    }

    public User(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }


    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
  • 子类Dao层接口UserDaoI
package com.mokong.user.dao;

import com.mokong.obj.dao.ObjDaoI;

/**
 * Created by Administrator on 2018/10/19.
 */
public interface UserDaoI<T> extends ObjDaoI<T> {
}
  • 子类Dao层接口实现类UserDao
package com.mokong.user.dao;
import com.mokong.obj.dao.ObjDao;
import com.mokong.user.model.User;
import org.springframework.stereotype.Repository;

/**
 * Created by Administrator on 2018/10/19.
 */
@Repository
public class UserDao extends ObjDao<User> implements UserDaoI<User>{
}
  • 子类Service层接口UserServiceI
package com.mokong.user.service;

import com.mokong.obj.service.ObjServiceI;

/**
 * Created by Administrator on 2018/10/19.
 */
public interface UserServiceI<T> extends ObjServiceI<T> {
}
  • 子类Service层接口实现类UserService
package com.mokong.user.service;

import com.mokong.obj.service.ObjService;
import com.mokong.user.model.User;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2018/10/19.
 */
@Service
public class UserService extends ObjService<User> implements UserServiceI<User>{
}
  • 子类Controller层 UserWeb
package com.mokong.user.web;

import com.mokong.user.model.User;
import com.mokong.user.service.UserServiceI;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * Created by Administrator on 2018/10/19.
 */
@Controller
public class UserWeb extends ActionSupport implements ModelDriven<User>{
    private User user = new User();
    @Override
    public User getModel() {
        return user;
    }

    @Autowired
    private UserServiceI<User> userService;

    public String saveT(){
        String s = userService.saveT(user);
        if (s.equals("chenggong"))
            return "save";
        return "error";
    }
}

现在就可以根据struts2里面设置的路径可以访问到后台了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值