话不多说,直接切入正题!
1、点击File,新建一个Module
2、点击选择Spring,然后依次勾选右边的Spring(勾选Spring时,下面会提示是否创建spring-config.xml,这里我们为了方便起见,勾选上),Web Application,Struts2
接下来下拉,选择Hibernate(Hibernate要和Spring整合一起,所以不用勾选配置文件)
3、接下来就是一路next,自己输入项目名称,最后Finish。Finish之后可能要等几分钟,Idea会自动帮你下载所需要的核心jar包。下图是最初的项目结构:
4、然后进行数据库的配置,Idea右侧点击Database,然后点击绿色的加号,选择Data Source,选择数据库(博主用的是MySQL)
5、在web.xml中进行如下配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- Spring框架核心监听器配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.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.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
6、在src目录下,新建jdbc.properties配置文件,内容如下(按照自己的数据库配置)
jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/yourdatabasename
jdbc.username = yourusername
jdbc.password = yourpassword
7、配置spring-config.xml,Spring整合Hibernate
<!-- 引入外部的属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置Hibernate相关属性 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 注入连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 加载Hibernate中的映射文件 -->
<property name="mappingResources">
<list>
<value></value>
</list>
</property>
</bean>