hibernate + spring + springmvc + maven (hibernate自动建表功能)
1.新建maven项目:
2.导入相关依赖的jar包
<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> <groupId>com.xuzhiwen</groupId> <artifactId>spring-hibernate-springmvc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring-hibernate-springmvc Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <springVersion>4.3.1.RELEASE</springVersion> <hibernateVersion>4.3.5.Final</hibernateVersion> <jstlVersion>1.2</jstlVersion> <taglibVersion>1.1.2</taglibVersion> <servletVersion>3.0-alpha-1</servletVersion> <jsonVersion>1.9.13</jsonVersion> <jacksonVersion>2.5.0</jacksonVersion> <mysqlVersion>5.1.6</mysqlVersion> <c3p0Version>0.9.1.2</c3p0Version> <log4jVersion>1.2.17</log4jVersion> <fileuploadVersion>1.3.1</fileuploadVersion> <lombokVersion>1.16.10</lombokVersion> </properties> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springVersion}</version> </dependency> <!-- spring web + spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <!-- hibernate配置 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- hibernate 缓存, 视情况添加 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- jsp页面使用的jstl支持 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstlVersion}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibVersion}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servletVersion}</version> <scope>provided</scope> </dependency> <!-- DataBase数据库连接 mysql包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0Version}</version> </dependency> <!-- json数据 使springMVC可以返回json值 ,视情况添加 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jsonVersion}</version> </dependency> <!-- Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jacksonVersion}</version> </dependency> <!-- log4j配置, 视情况添加 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4jVersion}</version> </dependency> <!--文件 上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileuploadVersion}</version> </dependency> <!-- lombok插件导包 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombokVersion}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>spring-hibernate-springmvc</finalName> </build> </project>
3.编辑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:applicationContext2.xml</param-value> </context-param> <!--spring listener--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--spring mvc--> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此处指向的的是SpringMVC的配置文件 --> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!--配置容器在启动的时候就加载这个servlet并实例化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4.新建页面:index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a href="../index">点我</a> </body> </html>
5.新建后台controllor
package com.xuzhiwen.controllor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping(value="/index") public String index(Model model,HttpServletRequest request,HttpServletResponse response){ System.out.println("index..."); return "index"; } }
6.新建
applicationContext1.xml
applicationContext2.xml
spring-mvc.xml
内容如下:
spring-mvc.xml
<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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <mvc:annotation-driven /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <context:component-scan base-package="com.xuzhiwen" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="views/" /> <!-- 前缀 --> <property name="suffix" value=".html" /> <!-- 后缀 --> </bean> <!--这里是对静态资源的映射--> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/img/**" location="/img/" /> <mvc:resources mapping="/views/**" location="/views/" /> </beans>
applicationContext1.xml
<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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!--扫描配置文件(这里指向的是之前配置的那个config.properties)--> <context:property-placeholder location="classpath:/config.properties" /> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <!--数据库连接驱动--> <property name="jdbcUrl" value="${jdbc.url}" /> <!--数据库地址--> <property name="user" value="${jdbc.username}" /> <!--用户名--> <property name="password" value="${jdbc.password}" /> <!--密码--> <property name="maxPoolSize" value="40" /> <!--最大连接数--> <property name="minPoolSize" value="1" /> <!--最小连接数--> <property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接--> <property name="maxIdleTime" value="20" /> <!--最大空闲时间--> </bean> <!--配置session工厂--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.xuzhiwen.entity" /> <property name="hibernateProperties"> <props> <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> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property> </bean> </beans>
applicationContext2.xml
<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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 --> <array> <value>classpath:database.properties</value> <value>classpath:hibernate.properties</value> <value>classpath:druid.properties</value> </array> </property> </bean> <!--配置数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${con.driver}" /> <property name="url" value="${con.url}" /> <property name="username" value="${con.username}" /> <property name="password" value="${con.password}" /> <property name="initialSize" value="${druid.initialSize}" /> <property name="maxIdle" value="${druid.maxIdle}" /> <property name="minIdle" value="${druid.minIdle}" /> <property name="maxActive" value="${druid.maxActive}" /> <property name="maxWait" value="${druid.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${druid.validationQuery}" /> <property name="testWhileIdle" value="${druid.testWhileIdle}" /> <property name="testOnBorrow" value="${druid.testOnBorrow}" /> <property name="testOnReturn" value="${druid.testOnReturn}" /> <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" /> <property name="filters" value="${druid.filters}" /> </bean> <!--配置session工厂--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.xuzhiwen.entity" /> <property name="hibernateProperties"> <props> <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> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop> <prop key="hibernate.jdbc.fetch_size">50</prop> <prop key="hibernate.jdbc.batch_size">50</prop> <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop> <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop> <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop> <prop key="hibernate.enable_lazy_load_no_trans">${hibernate.enable_lazy_load_no_trans}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}"</prop> </props> </property> </bean> </beans>
7.运行项目,进入index.html
点击链接结果如下:
说明: spring + springmvc 搭建成功。
7.新建配置文件:
config.properties
database.properties
druid.properties
hibernate.properties
8.新建实体类:
AA01.java
package com.xuzhiwen.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="AA01") public class AA01 { @Id @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid", strategy = "uuid.hex") private String id; @Column(name = "AAA001", length = 30) private String AAA001; @Column(name = "AAA002", length = 30) private String AAA002; @Column(name = "AAA003", length = 30) private String AAA003; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAAA001() { return AAA001; } public void setAAA001(String aAA001) { AAA001 = aAA001; } public String getAAA002() { return AAA002; } public void setAAA002(String aAA002) { AAA002 = aAA002; } public String getAAA003() { return AAA003; } public void setAAA003(String aAA003) { AAA003 = aAA003; } }
注意:红色字体为生成主键的方式,缺少的话,能运行成功,但无法创建表
9.运行项目,结果如下:
这样,表就自动生成了
10. 添加事务,配置如下:
<!-- 配置事务容器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- 定义事务规则 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="reset*" propagation="REQUIRED" /> <tx:method name="on*" propagation="REQUIRED" /> <tx:method name="off*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="execute*" propagation="REQUIRED" /> <tx:method name="after*" propagation="REQUIRED" /> <tx:method name="clear*" propagation="REQUIRED" /> <tx:method name="init*" propagation="REQUIRED" /> <tx:method name="run*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 定义事务入口 --> <aop:config> <aop:pointcut id="txPointcut" expression="execution(* com.xuzhiwen.dao.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config>
且web.xml里面需添加代码:
<filter> <filter-name>SpringOpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>SpringOpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这样才能保证不报错