用Maven整合SpringMVC+Spring+Hibernate 框架,实现简单的插入数据库数据功能

一、搭建开始前的准备

1、我用的MyEclipse2014版,大家也可以用IDEA。

2、下载Tomcat(免安装解压包)、MySQL(zip包下载地址 免安装解压包,好处就是双击启动,最后我会把bat的启动发给大家)、用的Navicat for MySQL的MySQL的图形界面工具。

3、配置环境变量CATALINA_HOME(path中添加%CATALINA_HOME%\lib;%CATALINA_HOME%\bin;)、MySQL_HOME(path中添加%MySQL_HOME%\bin;)

4、启动mysql和Tomcat试试能否正常运行。

5、打开MyEclipse新建Maven项目。File>New>Other(或Ctrl+N)>Maven Project;然后我们用default Workspace就行了(注意Location的路径,区分目录名和项目名);然后再Filter中输入webapp,我们选择org.apache.maven.archetypes 下的maven-archetype-webapp;点击下一步,填入Group Id(公司名,一般为com.xxx),Artifact Id(项目名),包名(一般根据公司名和项目名生成),单机Finish就创建完一个Maven的Web项目了。注:创建出来后有时候会有错(具体是index.jsp)这是因为我们没有在pom.xml中添加servlet的原因,自己加上就OK了。

6、一般创建出来的项目,只有src/main/resources,然后我们加上其他的三项(必须是新建Source Folder!src/main/java; src/test/resources; src/test/java),有时候会提示你该文件夹已经存在,我们稍改一下名,等创建完了后再用F2改回正确的就OK了(例如src/main/java创建失败,我们把java改为javas,最后再改为java即可。)

最终创建出来的目录如图:

7、万事具备只欠搭建,好吧下面才开始进入正文。

二、搭建

1、我习惯先建立一些package包名(src/main/java),例如:xxx.xxx.dao;xxx.xxx.dao.impl;xxx.xxx.model;xxx.xxx.service;xxx.xxx.service.impl;xxx.xxx.controller;具体的包应该放什么,起什么作用,大家可以百度。

2、配置资源文件,也就是所谓的src/main/resources下的文件。

(1.)config.properties

#\u5C5E\u6027\u6587\u4EF6

#Oracle \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl
#jdbc_username=
#jdbc_password=

#SQLServer \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=
#jdbc_password=

#Derby \u7684\u914D\u7F6E
#hibernate.dialect=org.hibernate.dialect.DerbyDialect
#driverClassName=org.apache.derby.jdbc.EmbeddedDriver
#validationQuery=SELECT 1
#jdbc_url=jdbc:derby:sy;create=true
#jdbc_username=
#jdbc_password=

#MySQL \u7684\u914D\u7F6E
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/sshf?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=

hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false

sessionInfoName=sessionInfo

uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached

注意:?useUnicode=true&characterEncoding=utf-8这句话,是UTF8的编码。注释的部分是其他数据库的编写形式。
(2.)log4j.properties

log4j.rootLogger=INFO,A1,R

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=sshf.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.Threshold=ALL
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

注意:sshf.log就是输出日志文件的文件名
(3.)spring.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" xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

    <!-- 引入属性文件 -->
    <context:property-placeholder location="classpath:config.properties" />

    <!-- 自动扫描dao和service包(自动注入) -->
    <context:component-scan base-package="com.jesus.sshframework.dao,com.jesus.sshframework.service" />

</beans>

没什么可说的,要说的也在注释里了。
(4.)spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context-3.1.xsd  
      http://www.springframework.org/schema/mvc  
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- 注解扫描包 -->
    <context:component-scan base-package="com.jesus.sshframework.controller" />
    <!-- 开启mvc注解 -->
    <mvc:annotation-driven />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans> 

(5.)spring-hibernate.xml(我喜欢这样写,这样能知道具体用的什么持久层框架,如果用myBatis,则spring-mybatis.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-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

    <!-- JNDI(通过Tomcat)方式配置数据源 -->
    <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->


    <!-- 配置数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}" />
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />

        <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />

        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />

        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- 配置hibernate session工厂 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            </props>
        </property>

        <!-- 自动扫描注解方式配置的hibernate类文件 -->
        <property name="packagesToScan">
            <list>
                <value>com.jesus.sshframework.model</value>
            </list>
        </property>
    </bean>

    <!-- 配置事务管理器 -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 注解方式配置事物 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" />
            <tx:method name="save*" />
            <tx:method name="update*" />
            <tx:method name="modify*" />
            <tx:method name="edit*" />
            <tx:method name="delete*" />
            <tx:method name="remove*" />
            <tx:method name="repair" />
            <tx:method name="deleteAndRepair" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.jesus.sshframework.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>


</beans>

注:我用的是阿里巴巴温少写的Druid的,具体介绍
3、贴一下pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><!--maven2.0必须是这样写,现在是maven2唯一支持的版本 -->
    <!-- The Basics -->
    <groupId>com.jesus</groupId><!--指定组名,例如:org.apache.maven -->
    <artifactId>SSHframework</artifactId><!--指定工程名例如:app -->
    <packaging>war</packaging><!--The current core packaging values are: pom, 
        jar, maven-plugin, ejb, war, ear, rar, par -->
    <version>0.0.1-SNAPSHOT</version><!--指定版本号 -->
    <name>SSHframework</name><!--一些无关太重要的东西,用户描述你的项目的名字,可选的 -->
    <url>http://maven.apache.org</url><!--暂时不知何物,貌似无关重要,只是写明开发团队的网站,可选的 -->
    <description></description> <!-- project的描述 -->
    <inceptionYear></inceptionYear><!-- 工程的初始时间 -->
    <licenses></licenses><!--列出本工程直接的licenses,而不要列出dependencies的licenses -->


    <!-- 指定maven仓库 -->
    <repositories><!-- 发现依赖和扩展的远程资源库 -->
        <!-- maven自己官方仓库 -->
        <repository>
            <id>maven</id>
            <name>Maven Repository Switchboard</name>
            <layout>default</layout>
            <url>http://repo1.maven.org/maven2</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <!-- 阿里巴巴发布版本仓库 -->
        <repository>
            <id>alibaba-opensource</id>
            <name>alibaba-opensource</name>
            <url>http://code.alibabatech.com/mvn/releases/</url>
            <layout>default</layout>
        </repository>
        <!-- 阿里巴巴快照版本仓库 -->
        <repository>
            <id>alibaba-opensource-snapshot</id>
            <name>alibaba-opensource-snapshot</name>
            <url>http://code.alibabatech.com/mvn/snapshots/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!-- maven打成war包放到tomcat目录下,即可运行 -->
    <build>
        <finalName>SSHframework</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies><!-- 这个元素描述了所有与当前项目相关的依赖 -->
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
            <scope>provided</scope>
        </dependency>

        <!-- log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
            <scope>provided</scope>
        </dependency>

        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>

        <!-- fastJson json数组有关的 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.26</version>
        </dependency>

        <!-- 使用 Jackson 把 Java 对象转换成 JSON 字串 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.11</version>
        </dependency>

        <!-- mysql数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>0.2.9</version>
        </dependency>

        <!-- aspectjweaver.jar这是Spring AOP所要用到的包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.7.1</version>
        </dependency>

        <!-- hibernate4 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.5.Final</version>
        </dependency>       
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>4.2.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>

        <!-- spring mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>

        <!-- spring3 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>       
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.2.0.RELEASE</version>
        </dependency>

    </dependencies>

</project>

注:会使用的注意下版本更新就是了,有的可能会有jar包交叉,注意就行了。
3、我习惯建立接口,这样对整个项目感觉更合理。
(1.)建立IBaseService(业务逻辑层,有的习惯写成BaseServiceI)都可以,都是标注接口的,我只是简单的贴下代码

package com.jesus.sshframework.service;

import java.io.Serializable;

public interface IBaseService<T, PK extends Serializable> {

    /**
     * 根据ID获取实体对象.
     * @param id
     *            记录ID
     * @return 实体对象
     */
    public T get(PK id);

    /**
     * 保存实体对象.
     * 
     * @param entity
     *            对象
     * @return ID
     */
    public PK save(T entity);
}

PS.贴出来应该就知道为什么这么写了吧。T 泛型,可以少些很多的代码,我们这个接口一般放很多业务逻辑都能用到的方法。
(2.)实现上面的接口BaseServiceImpl(这个大家一般都这么写吧),当然也是基础类。

package com.jesus.sshframework.service.impl;

import java.io.Serializable;

import com.jesus.sshframework.dao.IBaseDao;
import com.jesus.sshframework.service.IBaseService;

public class BaseServiceImpl<T, PK extends Serializable> implements IBaseService<T, PK>{

    private IBaseDao<T, PK> baseDao;

    public IBaseDao<T, PK> getBaseDao() {
        return baseDao;
    }

    public void setBaseDao(IBaseDao<T, PK> baseDao) {
        this.baseDao = baseDao;
    }

    public T get(PK id) {
        return baseDao.get(id);
    }

    public PK save(T entity) {
        return baseDao.save(entity);
    }

}

PS.大家看到了新的IBaseDao,我马上说说他。
(3.)Dao这个是数据访问接口,数据持久层,用来具体操作DB,完成增删改查。我照样也是用接口。

package com.jesus.sshframework.dao;

import java.io.Serializable;

/**
 * Dao接口 - Dao基接口
 */

public interface IBaseDao<T, PK extends Serializable> {

    /**
     * 根据ID获取实体对象.
     * 
     * @param id
     *            记录ID
     * @return 实体对象
     */
    public T get(PK id);

    /**
     * 保存实体对象.
     * 
     * @param entity
     *            对象
     * @return ID
     */
    public PK save(T entity);
}

PS.仍然是泛型,当然实现是impl,
(4.)BaseDaoImpl 我们因为用的是泛型,所以得确定具体的类,然后操作Serrion.

package com.jesus.sshframework.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.jesus.sshframework.dao.IBaseDao;

@Repository
public class BaseDaoImpl<T, PK extends Serializable> implements IBaseDao<T, PK>{

    private Class<T> entityClass;
    protected SessionFactory sessionFactory;

    public BaseDaoImpl() {
        this.entityClass = null;
        Class<?> c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizedType[0];
        }
    }

    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public T get(PK id) {
        Assert.notNull(id, "id is required");
        return (T) getSession().get(entityClass, id);
    }

    public PK save(T entity) {
        Assert.notNull(entity, "entity is required");
        return (PK) getSession().save(entity);
    }

}

(5.)实体bean,我们也要用Base的哦。

package com.jesus.sshframework.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import org.hibernate.annotations.GenericGenerator;

/**
 * 实体类 - 基类
 */
@MappedSuperclass
public class BaseEntity implements Serializable{

    /**
     * ID
     */
    private String id;
    /**
     * 创建日期
     */
    private Date createDate;
    /**
     * 修改日期
     */
    private Date modifyDate;

    @Id
    @Column(length = 32, nullable = true)
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    public String getId() {
        return id;
    }

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

    @Column(updatable = false)
    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    @Override
    public int hashCode() {
        return id == null ? System.identityHashCode(this) : id.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass().getPackage() != obj.getClass().getPackage()) {
            return false;
        }
        final BaseEntity other = (BaseEntity) obj;
        if (id == null) {
            if (other.getId() != null) {
                return false;
            }
        } else if (!id.equals(other.getId())) {
            return false;
        }
        return true;
    }
}

最基本的代码我们贴到这基本就完成了。以后的东西都是建立在这几个类(接口)上面的。我想大家应该都会写了。
4、最后贴一下web.xml(用了Maven后经常忘了改他。%>_<%)

<?xml version="1.0" encoding="UTF-8"?>
<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_0.xsd"
    version="3.0">
    <display-name></display-name>
    <!-- spring hibernate -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:spring-hibernate.xml</param-value>
    </context-param>
    <!-- openSessionInView配置 -->
    <filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <!--spring mvc 配置 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- encodeing -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <!-- encoding filter for jsp page -->
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

三、小结
1、数据库建完后,表都不用管,自动创建。
2、配置好pom.xml,妈妈再也不用担心我一个个的下jar包了,有时候jar包会下载失败,建议稍修改,或加个换行重新下载一次,推荐大家在配置pom.xml的时候可以多加几个maven远程库,缓存下来后就不再担心了。
PS.maven自动缓存在C盘,大家可以一开始改一下缓存路径,Windows>Preferences>搜索User Settings(我的是MyEclipse2014),其他的自己找,肯定有.

福利:给大家几个Maven库,打开都挺慢的。
http://search.maven.org/
http://mvnrepository.com/
http://repository.sonatype.org/content/groups/public/
3、注意代码规范就好,这点对刚毕业的小伙伴们很重要哦。

(未测)文章源码:http://download.csdn.net/detail/js931178805/7985985

(亲测)本人源码:http://download.csdn.net/detail/liu1220356497/9011349
配置:myeclipse10.6+maven3+spring+springmvc+hibernate4+mysql5.5

转载:http://blog.csdn.net/js931178805/article/details/39642743

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值