一、基本軟件配置
1)MyEclipse 2014GA(JDK:1.7.0.u45)
2)apache-tomcat-7.0.64
3)mysql- 5.5.50
二、項目目的
整合使用Java三大框架(即Struts2、Spring4和Hibernate4),搭建項目架構原型。
三、SSH三大架構版本下載
Struts2.3.6:官網:http://struts.apache.org/
http://mirrors.cnnic.cn/apache/struts/binaries/struts-2.3.16.3-all.zip
Spring4.1.1:官網:http://spring.io/
Hibernate4.3.6:官網:http://hibernate.org/
四、項目目錄
五 、創建項目
1、創建一個 webweb 項目 ,設置 如下 :
2、導入jar包
需導入的jar包詳見下圖,有多個jar包沖突不能同時到導入。除了導入到classpath中,由於jar包沒放在\WEB-INF\lib目錄中,在使用MyEclipse等開發工具將項目部署到Tomcat等服務器時,開發工具並不會自動復制所有jar包,需要我們手動復制這些jar到\WEB-INF\lib中。
3、安裝Hibernate
項目雖導入hibernate的jar包,但不操作此步驟,無法添加反向工程。只需要安裝hibernate4以上的版本。
已手動添加jar包,且版本不一樣,此處不用再添加任何jar包
hibernate 數據庫connection配置,如果還沒配置driver可以 new一個。
添加反向工程
注意Hibernate主鍵生成策略,應根據自己模型設計選擇主鍵生成策略。
1、自動增長identity
適用於MySQL、DB2、MS SQL Server,采用數據庫生成的主鍵,用於為long、short、int類型生成唯一標識
使用SQL Server 和 MySQL 的自增字段,這個方法不能放到 Oracle 中,Oracle 不支持自增字段,要設定sequence(MySQL 和 SQL Server 中很常用)
數據庫中的語法如下:
MySQL:create table t_user(id int auto_increment primary key, name varchar(20));
SQL Server:create table t_user(id int identity(1,1) primary key, name varchar(20));
<id name="id" column="id" type="long">
<generator class="identity" />
</id>
2、sequence
DB2、Oracle均支持的序列,用於為long、short或int生成唯一標識
數據庫中的語法如下:
Oracle:create sequence seq_name increment by 1 start with 1;
需要主鍵值時可以調用seq_name.nextval或者seq_name.curval得到,數據庫會幫助我們維護這個sequence序列,保證每次取到的值唯一,如:
insert into tbl_name(id, name) values(seq_name.nextval, ‘Jimliu’);
<id name="id" column="id" type="long">
<generator class="sequence">
<param name="sequence">seq_name</param>
</generator>
</id>
3、assigned
由應用程序負責生成主鍵標識符,往往使用在數據庫中沒有代理主鍵,使用的主鍵與業務相關的情況,如:
<id name="id" column="id" type="string">
<generator class="assigned" />
</id>
這種主鍵的生成方式不建議使用,在數據庫表設計時就應該使用代理主鍵(surrogate key),不應使用自然主鍵(natural key具有業務含義),在沒有指定<generator>標簽時,默認就是assigned主鍵的生成方式
在插入數據的時候主鍵由用戶自己添加,hibernate也不管
六、相關配置
1、JDBC配置
####################### DB Connection Config ####################### ###----------------- DB Type ----------------- #the database of the application:mysql|sqlserver|oracle databaseType=mysql #databaseType=sqlserver #databaseType=oracle ###----------------- MySQL5+ ----------------- jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.1.1:3306/testdb?useUnicode=true&characterEncoding=utf-8 jdbc.username=test jdbc.password=test hibernate.dialect=org.hibernate.dialect.MySQLDialect ###----------------- SqlServer2005+ ----------------- #jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver #jdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=sampledb #jdbc.username=sa #jdbc.password=123456 #hibernate.dialect=org.hibernate.dialect.SQLServerDialect ###----------------- Oracle10g+ ----------------- #jdbc.driverClassName=oracle.jdbc.driver.OracleDriver #jdbc.url=jdbc:oracle:thin:@localhost:1521:orac10g #jdbc.username=scott #jdbc.password=scott123 #hibernate.dialect=org.hibernate.dialect.OracleDialect ###----------------- JNDI ----------------- #jndi.name=myjndi123 ###----------------- Hibernate ----------------- hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl.auto=update hibernate.jdbc.fetch_size=100 hibernate.jdbc.batch_size=20 hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.memcached.cacheTimeSeconds=10800 #Hibernate4 hibernate.cache.region.factory_class=org.hibernate.cache.EhCacheRegionFactory #Hibernate3 #hibernate.cache.region.factory_class=org.hibernate.cache.EhCacheProvider ###----------------- C3P0 ----------------- c3p0.maxPoolSize=50 c3p0.minPoolSize=1 c3p0.initialPoolSize=1 c3p0.maxIdleTime=20 ###----------------- DBCP ----------------- dbcp.maxActive=50 dbcp.maxIdle=50 dbcp.minIdle=1 dbcp.maxWait=10000 dbcp.initialSize=1
2、hibernate.cfg.xml配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 基本配置:JDBC方式 --> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="hibernate.connection.url"> jdbc:mysql://192.168.1.1:3306/testdb?useUnicode=true&characterEncoding=utf-8 </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"> abcd.1234 </property> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- 擴展配置 --> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.jdbc.fetch_size">100</property> <property name="hibernate.jdbc.batch_size">30</property> <!-- 配置二級緩存 --> <property name="hibernate.cache.use_second_level_cache"> true </property> <property name="hibernate.cache.use_query_cache">true</property> <!-- Hibernate4,這里和Hibernate3不一樣,要特別注意!!! --> <property name="hibernate.cache.region.factory_class"> org.hibernate.cache.EhCacheRegionFactory </property> <!-- Hibernate3 --> <!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> --> <!-- 配置C3P0 --> <property name="hibernate.connection.provider_class"> org.hibernate.connection.C3P0ConnectionProvider </property> <property name="hibernate.c3p0.max_size">10</property> <property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_statements">3</property> <property name="hibernate.c3p0.timeout">30</property> <property name="hibernate.c3p0.acquire_increment">1</property> <property name="hibernate.c3p0.idle_test_periodt">10</property> <!-- 領域對象:映射文件方式 --> <property name="myeclipse.connection.profile">testdb</property> <property name="connection.url">jdbc:mysql://192.168.1.1:3306/testdb</property> <property name="connection.username">test</property> <property name="connection.password">test</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 領域對象:Annotation注解方式 <mapping class="實體類全限定名" /> --> </session-factory> </hibernate-configuration>
3、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:p="http://www.springframework.org/schema/p" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 說明:下面有的Bean配置提供了多種方案,請根據需要采用某一種(別忘了注釋掉其他同類方案) --> <!-- 自動掃描Spring注解配置 --> <context:component-scan base-package="cases" /> <!-- 自動加載屬性配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置數據源:方法一,使用C3P0方式(推薦) --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}" /> <!-- 配置數據源:方法二,使用DBCP方式(不推薦) --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> --> <!-- 配置數據源:方法三,使用JNDI方式 --> <!-- <jee:jndi-lookup id="dataSource" jndi-name="${jndi.name}" /> --> <!-- 配置Hibernate的數據源代理工廠:方法一,使用p屬性通配符,按文件名搜索匹配的映射文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingLocations="classpath*:/cases/**/*.hbm.xml"> <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.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> </props> </property> </bean> <!-- 配置Hibernate的數據源代理工廠:方法二,使用list集合,按文件名搜索匹配的映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mappingLocations"> <list> <value>classpath*:/com/**/*.hbm.xml</value> </list> </property> <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.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> </props> </property> </bean> --> <!-- 配置Hibernate的數據源代理工廠:方法三,使用p屬性通配符,按目錄搜索映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingDirectoryLocations="classpath*:/com/**/domain"> <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.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> </props> </property> </bean> --> <!-- 配置Hibernate的數據源代理工廠:方法四,使用hibernate.cfg.xml --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:hibernate.cfg.xml"> </bean> --> <!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- 配置聲明式事務:方法一,在Service實現類或者public實現方法上使用注解@Transactional,則此類或方法就會啟用事務機制 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置聲明式事務:方法二,使用tx/aop命名空間的配置(其實還有方法三,由於快要過時不推薦使用了,這里就不給出方法三的配置了) --> <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="search*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mypointcut" expression="execution(* com.**.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut" /> </aop:config> --> <!-- 下面三個Bean的配置可有可無,但配置后用處更大,通常用於BaseDao類、其他Dao類或特殊工具類中 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate" p:sessionFactory-ref="sessionFactory" /> <bean id="hibernateDaoSupport" class="org.springframework.orm.hibernate4.support.HibernateDaoSupport" p:hibernateTemplate-ref="hibernateTemplate" abstract="true"/> <bean id="sessionFactoryUtils" class="org.springframework.orm.hibernate4.SessionFactoryUtils" abstract="true"/> </beans>
4、Struts.xml增加一些配置
<!-- 指定Web應用的默認編碼,相當於調用request的setCharacterEncoding方法 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 設置瀏覽器是否緩存靜態內容,默認值為true(生產環境下使用),開發階段最好關閉 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 當Struts2的配置文件修改后,系統是否自動重新加載配置文件,默認值為false(生產環境下使用),開發階段最好打開 --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 開發模式下使用,這樣可以打印出更詳細的日志信息 --> <constant name="struts.devMode" value="true" /> <!-- 默認的視圖主題 --> <constant name="struts.ui.theme" value="simple" /> <!-- 把Action對象交給Spring創建和管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- Struts2處理的請求后綴,默認值是action --> <constant name="struts.action.extension" value="do" />
七、通用基礎數據庫操作類(網上可以找到)
1.BaseDAO.java
package cases.dao; import java.io.Serializable; import java.util.List; /** * 基礎數據庫操作類 * * @author arthurmok * */ public interface BaseDAO<T> { /** * 保存一個對象 * * @param o * @return */ public Serializable save(T o); /** * 刪除一個對象 * * @param o */ public void delete(T o); /** * 更新一個對象 * * @param o */ public void update(T o); /** * 保存或更新對象 * * @param o */ public void saveOrUpdate(T o); /** * 查詢 * * @param hql * @return */ public List<T> find(String hql); /** * 查詢集合 * * @param hql * @param param * @return */ public List<T> find(String hql, Object[] param); /** * 查詢集合 * * @param hql * @param param * @return */ public List<T> find(String hql, List<Object> param); /** * 查詢集合(帶分頁) * * @param hql * @param param * @param page * 查詢第幾頁 * @param rows * 每頁顯示幾條記錄 * @return */ public List<T> find(String hql, Object[] param, Integer page, Integer rows); /** * 查詢集合(帶分頁) * * @param hql * @param param * @param page * @param rows * @return */ public List<T> find(String hql, List<Object> param, Integer page, Integer rows); /** * 獲得一個對象 * * @param c * 對象類型 * @param id * @return Object */ public T get(Class<T> c, Serializable id); /** * 獲得一個對象 * * @param hql * @param param * @return Object */ public T get(String hql, Object[] param); /** * 獲得一個對象 * * @param hql * @param param * @return */ public T get(String hql, List<Object> param); /** * select count(*) from 類 * * @param hql * @return */ public Long count(String hql); /** * select count(*) from 類 * * @param hql * @param param * @return */ public Long count(String hql, Object[] param); /** * select count(*) from 類 * * @param hql * @param param * @return */ public Long count(String hql, List<Object> param); /** * 執行HQL語句 * * @param hql * @return 響應數目 */ public Integer executeHql(String hql); /** * 執行HQL語句 * * @param hql * @param param * @return 響應數目 */ public Integer executeHql(String hql, Object[] param); /** * 執行HQL語句 * * @param hql * @param param * @return */ public Integer executeHql(String hql, List<Object> param); }
2
. BaseDAOImpl.java
package cases.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import cases.dao.BaseDAO; @Repository("baseDAO") @SuppressWarnings("all") public class BaseDAOImpl<T> implements BaseDAO<T> { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private Session getCurrentSession() { return sessionFactory.getCurrentSession(); } public Serializable save(T o) { return this.getCurrentSession().save(o); } public void delete(T o) { this.getCurrentSession().delete(o); } public void update(T o) { this.getCurrentSession().update(o); } public void saveOrUpdate(T o) { this.getCurrentSession().saveOrUpdate(o); } public List<T> find(String hql) { return this.getCurrentSession().createQuery(hql).list(); } public List<T> find(String hql, Object[] param) { Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.length > 0) { for (int i = 0; i < param.length; i++) { q.setParameter(i, param[i]); } } return q.list(); } public List<T> find(String hql, List<Object> param) { Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.size() > 0) { for (int i = 0; i < param.size(); i++) { q.setParameter(i, param.get(i)); } } return q.list(); } public List<T> find(String hql, Object[] param, Integer page, Integer rows) { if (page == null || page < 1) { page = 1; } if (rows == null || rows < 1) { rows = 10; } Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.length > 0) { for (int i = 0; i < param.length; i++) { q.setParameter(i, param[i]); } } return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list(); } public List<T> find(String hql, List<Object> param, Integer page, Integer rows) { if (page == null || page < 1) { page = 1; } if (rows == null || rows < 1) { rows = 10; } Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.size() > 0) { for (int i = 0; i < param.size(); i++) { q.setParameter(i, param.get(i)); } } return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list(); } public T get(Class<T> c, Serializable id) { return (T) this.getCurrentSession().get(c, id); } public T get(String hql, Object[] param) { List<T> l = this.find(hql, param); if (l != null && l.size() > 0) { return l.get(0); } else { return null; } } public T get(String hql, List<Object> param) { List<T> l = this.find(hql, param); if (l != null && l.size() > 0) { return l.get(0); } else { return null; } } public Long count(String hql) { return (Long) this.getCurrentSession().createQuery(hql).uniqueResult(); } public Long count(String hql, Object[] param) { Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.length > 0) { for (int i = 0; i < param.length; i++) { q.setParameter(i, param[i]); } } return (Long) q.uniqueResult(); } public Long count(String hql, List<Object> param) { Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.size() > 0) { for (int i = 0; i < param.size(); i++) { q.setParameter(i, param.get(i)); } } return (Long) q.uniqueResult(); } public Integer executeHql(String hql) { return this.getCurrentSession().createQuery(hql).executeUpdate(); } public Integer executeHql(String hql, Object[] param) { Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.length > 0) { for (int i = 0; i < param.length; i++) { q.setParameter(i, param[i]); } } return q.executeUpdate(); } public Integer executeHql(String hql, List<Object> param) { Query q = this.getCurrentSession().createQuery(hql); if (param != null && param.size() > 0) { for (int i = 0; i < param.size(); i++) { q.setParameter(i, param.get(i)); } } return q.executeUpdate(); } }
至此,項目原型搭建完成,可在此架構上做業務開發了。
由於自己項目業務邏輯不一樣,代碼不便貼出,可參考下面文章用戶登錄實現的例子。
http://blog.csdn.net/ycb1689/article/details/22928519