先从persistence.xml开始:
<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”2.1″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd”><persistence-unit name=”mysqldb”><provider>org.hibernate.ejb.HibernatePersistence</provider><properties><property name=”hibernate.dialect” value=”org.hibernate.dialect.MySQL5Dialect” />
<property name=”hibernate.connection.driver_class” value=”com.mysql.jdbc.Driver” /><property name=”hibernate.connection.username” value=”root” /><property name=”hibernate.connection.password” value=”123456″ /><property name=”hibernate.connection.url” value=”jdbc:mysql://localhost:3306/twq?useUnicode=true&characterEncoding=UTF-8″ /><!–设置外连接抓取树的最大深度 –>
<property name=”hibernate.max_fetch_depth” value=”3″ /><!–自动输出schema创建DDL语句 –><property name=”hibernate.hbm2ddl.auto” value=”update” /><!– <property name=”hibernate.show_sql” value=”true” /><property name=”hibernate.format_sql” value=”true” /> –><property name=”javax.persistence.validation.mode” value=”none”/></properties></persistence-unit><persistence-unit name=”sqlserverdb”><provider>org.hibernate.ejb.HibernatePersistence</provider><properties><property name=”hibernate.dialect” value=”org.hibernate.dialect.SQLServerDialect” />
<property name=”hibernate.connection.driver_class” value=”com.microsoft.sqlserver.jdbc.SQLServerDriver” /><property name=”hibernate.connection.username” value=”sa” /><property name=”hibernate.connection.password” value=”123abc” /><property name=”hibernate.connection.url” value=”jdbc:sqlserver://192.168.130.10:1433;DatabaseName=unionman” /><!–设置外连接抓取树的最大深度 –>
<property name=”hibernate.max_fetch_depth” value=”3″ /><!–自动输出schema创建DDL语句<property name=”hibernate.hbm2ddl.auto” value=”update” /> –><!– <property name=”hibernate.show_sql” value=”true” /><property name=”hibernate.format_sql” value=”true” /> –><property name=”javax.persistence.validation.mode” value=”none”/></properties></persistence-unit></persistence>
这里定义两个:<persistence-unit> 注意name值区分。
2.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:aop=”http://www.springframework.org/schema/aop”xmlns:context=”http://www.springframework.org/schema/context”xmlns:jpa=”http://www.springframework.org/schema/data/jpa”xmlns:mvc=”http://www.springframework.org/schema/mvc”xmlns:tx=”http://www.springframework.org/schema/tx”xmlns:util=”http://www.springframework.org/schema/util”xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd”><context:annotation-config/>
<context:component-scan base-package=”com.tw”/><bean id=”defaultPersistenceUnitManager” class=”org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager”><property name=”persistenceXmlLocation” value=”classpath:META-INF/persistence.xml”/><!– comment dataSourceLooup to use jndi –><property name=”dataSourceLookup”><bean class=”org.springframework.jdbc.datasource.lookup.BeanFactoryDataSourceLookup” /></property></bean><!– 整合mysqljpa –>
<bean id=”mysqlEntityManagerFactory” class=”org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”><property name=”persistenceUnitManager” ref=”defaultPersistenceUnitManager”></property><property name=”persistenceUnitName” value=”mysqldb”></property><property name=”jpaVendorAdapter”><bean class=”org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”><property name=”showSql” value=”true”></property><property name=”database” value=”MYSQL”></property></bean></property></bean><bean id=”mysqltransactionManager” class=”org.springframework.orm.jpa.JpaTransactionManager”><property name=”entityManagerFactory” ref=”mysqlEntityManagerFactory” /><qualifier value=”mysqlEM”/></bean><tx:annotation-driven transaction-manager=”mysqltransactionManager” proxy-target-class=”false”/><!– 整合sqlserverjpa –>
<bean id=”sqlserverEntityManagerFactory” class=”org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”><property name=”persistenceUnitManager” ref=”defaultPersistenceUnitManager”></property><property name=”persistenceUnitName” value=”sqlserverdb”></property><property name=”jpaVendorAdapter”><bean class=”org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”><property name=”showSql” value=”true”></property><property name=”database” value=”SQL_SERVER”></property></bean></property></bean><bean id=”sqlservertransactionManager” class=”org.springframework.orm.jpa.JpaTransactionManager”><property name=”entityManagerFactory” ref=”sqlserverEntityManagerFactory” /><qualifier value=”sqlserverEM”/></bean><tx:annotation-driven transaction-manager=”sqlservertransactionManager” proxy-target-class=”false”/></beans>
注意我标注为红色的地方。
3.tw-servlet.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:mvc=”http://www.springframework.org/schema/mvc”xsi:schemaLocation=”http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd”><context:component-scan base-package=”com.tw.controller” /><!– 避免IE执行AJAX时,返回JSON出现下载文件 –>
<bean id=”fastJsonHttpMessageConverter”class=”com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter”><property name=”supportedMediaTypes”><list><value>application/json</value></list></property></bean><!– 启动Spring MVC的注解功能,完成请求和注解POJO的映射 –>
<beanclass=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”><property name=”messageConverters”><list><ref bean=”fastJsonHttpMessageConverter” /></list></property></bean><!– 对模型视图名称的解析,即在模型视图名称添加前后缀 –><beanclass=”org.springframework.web.servlet.view.InternalResourceViewResolver”><property name=”viewClass”value=”org.springframework.web.servlet.view.JstlView” /><property name=”prefix” value=”/”></property><property name=”suffix” value=”.jsp”></property></bean><!– 支持上传文件 –>
<bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/><mvc:interceptors>
<mvc:interceptor><mvc:mapping path=”/**”/><bean class=”com.tw.interceptor.PermissionAnnotationInterceptor”><property name=”excludeUrls”><list><value>/menu/init</value><value>/menu/tree</value><value>/user/login</value><value>/user/logout</value><value>/user/add</value></list></property></bean></mvc:interceptor></mvc:interceptors></beans>这个没什么解释的。
4.web.xml:
<?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” id=”WebApp_ID” version=”3.0″><display-name>twc</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!– <filter><filter-name>OpenEntityManagerInViewFilter</filter-name><filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class><init-param><param-name>entityManagerFactoryBeanName</param-name><param-value>entityManagerFactory</param-value></init-param><init-param><param-name>persistenceUnitName</param-name><param-value>tw</param-value></init-param></filter><filter-mapping><filter-name>OpenEntityManagerInViewFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping> –><servlet><servlet-name>tw</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:tw-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>tw</servlet-name><url-pattern>/</url-pattern></servlet-mapping><servlet-mapping>
<servlet-name>default</servlet-name><url-pattern>*.css</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.js</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.json</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.gif</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.png</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.jpg</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.ico</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.doc</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.xls</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.docx</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.xlsx</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.txt</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.swf</url-pattern></servlet-mapping><filter><filter-name>Spring character encoding filter</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><filter-mapping><filter-name>Spring character encoding filter</filter-name><url-pattern>/*</url-pattern></filter-mapping><session-config><session-timeout>30</session-timeout></session-config><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>
看到我在web.xml中标注的红色没有,如果你想用多数据源就把这个干掉,也就是说hibernate的延迟加载功能就不要用了。
其实在项目中最好不要用延迟加载,你懂的。
配置基本完成。
下面是代码了:
dao:
@Repository
@Transactional(value=”mysqlEM”)public class BaseDAOSupport<T> implements BaseDAO<T> { @SuppressWarnings(“unchecked”)private Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());@PersistenceContext(unitName=”mysqldb”)protected EntityManager em;
@Repository
@Transactional(value=”sqlserverEM”)public class BaseDAOSqlServer<T> implements BaseDAO<T> { @SuppressWarnings(“unchecked”)private Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());@PersistenceContext(unitName=”sqlserverdb”)protected EntityManager em;
看明白什么意思了吧,不解释。
service:
@Service(“menuService”)
public class MenuServiceImpl extends BaseDAOSupport<Tmenu> implements MenuService{
@Service(“umUserService”)
public class UmUserServiceImpl extends BaseDAOSqlServer<UmMrpUser> implements UmUserService{
就这么简单。
controller:
@Controller
@RequestMapping(“/user”)public class UserController {@Autowired
private UserService userService;@Autowiredprivate UmUserService umUserService;
在一个控制类里面可以同时调用不同的数据库内容。
表现层我就不写了。这个方案可以实现各自事务的提交。
更深入的测试还没发现什么问题,over!
接上一个博文,没有数据库连接池,纯粹用jpa的官方链接。
所以这次要加上连接池本文用Druid连接池来实现多数据源的配置。
persistence.xml 这个文件可以省略了,全部配置在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:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:jpa="http://www.springframework.org/schema/data/jpa"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:util="http://www.springframework.org/schema/util"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
- http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
- <context:annotation-config/>
- <context:component-scan base-package="com.tw"/>
- <!-- mysql数据源配置 -->
- <bean id="mysqlDataSource" class="com.alibaba.druid.pool.DruidDataSource"
- init-method="init" destroy-method="close">
- <!-- 驱动名称 -->
- <property name="DriverClassName" value="com.mysql.jdbc.Driver" />
- <!-- JDBC连接串 -->
- <property name="url"
- value="jdbc:mysql://192.168.132.1:3306/twq?useUnicode=true&characterEncoding=UTF-8" />
- <!-- 数据库用户名称 -->
- <property name="username" value="ws" />
- <!-- 数据库密码 -->
- <property name="password" value="unionmanws" />
- <!-- 连接池最大使用连接数量 -->
- <property name="maxActive" value="20" />
- <!-- 初始化大小 -->
- <property name="initialSize" value="5" />
- <!-- 获取连接最大等待时间 -->
- <property name="maxWait" value="60000" />
- <!-- 连接池最小空闲 -->
- <property name="minIdle" value="2" />
- <!-- 逐出连接的检测时间间隔 -->
- <property name="timeBetweenEvictionRunsMillis" value="3000" />
- <!-- 最小逐出时间 -->
- <property name="minEvictableIdleTimeMillis" value="300000" />
- <!-- 测试有效用的SQL Query -->
- <property name="validationQuery" value="SELECT 'x'" />
- <!-- 连接空闲时测试是否有效 -->
- <property name="testWhileIdle" value="true" />
- <!-- 获取连接时测试是否有效 -->
- <property name="testOnBorrow" value="false" />
- <!-- 归还连接时是否测试有效 -->
- <property name="testOnReturn" value="false" />
- </bean>
- <!-- 整合mysqljpa -->
- <bean id="mysqlEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
- <property name="dataSource" ref="mysqlDataSource"></property>
- <property name="packagesToScan" value="com.tw.entity.sys"></property>
- <property name="persistenceUnitName" value="mysqldb"></property>
- <property name="jpaVendorAdapter">
- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="showSql" value="true"></property>
- </bean>
- </property>
- <property name="jpaProperties">
- <props>
- <!--设置外连接抓取树的最大深度 -->
- <prop key="hibernate.max_fetch_depth">3</prop>
- <prop key="hibernate.jdbc.fetch_size">18</prop>
- <prop key="hibernate.jdbc.batch_size">10</prop>
- <!-- 自动建表类型 validate|create|create-drop|update -->
- <!-- <prop key="hibernate.hbm2ddl.auto">validate</prop> -->
- <!-- 是否显示SQL -->
- <prop key="hibernate.show_sql">false</prop>
- <!-- 显示SQL是否格式化 -->
- <prop key="hibernate.format_sql">false</prop>
- <!-- 关闭二级缓存 -->
- <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
- <!-- 关闭实体字段映射校验 -->
- <prop key="javax.persistence.validation.mode">none</prop>
- </props>
- </property>
- </bean>
- <bean id="mysqltransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="mysqlEntityManagerFactory" />
- <qualifier value="mysqlEM"/>
- </bean>
- <tx:annotation-driven transaction-manager="mysqltransactionManager" proxy-target-class="false"/>
- <!-- sqlserver数据源配置 -->
- <bean id="sqlserverDataSource" class="com.alibaba.druid.pool.DruidDataSource"
- init-method="init" destroy-method="close">
- <!-- 驱动名称 -->
- <property name="DriverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
- <!-- JDBC连接串 -->
- <property name="url"
- value="jdbc:sqlserver://192.168.130.10:1433;DatabaseName=unionman" />
- <!-- 数据库用户名称 -->
- <property name="username" value="sa" />
- <!-- 数据库密码 -->
- <property name="password" value="123abc" />
- <!-- 连接池最大使用连接数量 -->
- <property name="maxActive" value="20" />
- <!-- 初始化大小 -->
- <property name="initialSize" value="5" />
- <!-- 获取连接最大等待时间 -->
- <property name="maxWait" value="60000" />
- <!-- 连接池最小空闲 -->
- <property name="minIdle" value="2" />
- <!-- 逐出连接的检测时间间隔 -->
- <property name="timeBetweenEvictionRunsMillis" value="3000" />
- <!-- 最小逐出时间 -->
- <property name="minEvictableIdleTimeMillis" value="300000" />
- <!-- 测试有效用的SQL Query -->
- <property name="validationQuery" value="SELECT 'x'" />
- <!-- 连接空闲时测试是否有效 -->
- <property name="testWhileIdle" value="true" />
- <!-- 获取连接时测试是否有效 -->
- <property name="testOnBorrow" value="false" />
- <!-- 归还连接时是否测试有效 -->
- <property name="testOnReturn" value="false" />
- </bean>
- <!-- 整合sqlserverjpa -->
- <bean id="sqlserverEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
- <property name="dataSource" ref="sqlserverDataSource"></property>
- <property name="packagesToScan" value="com.tw.entity.plan"></property>
- <property name="persistenceUnitName" value="sqlserverdb"></property>
- <property name="jpaVendorAdapter">
- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
- <property name="showSql" value="true"></property>
- </bean>
- </property>
- <property name="jpaProperties">
- <props>
- <!--设置外连接抓取树的最大深度 -->
- <prop key="hibernate.max_fetch_depth">3</prop>
- <prop key="hibernate.jdbc.fetch_size">18</prop>
- <prop key="hibernate.jdbc.batch_size">10</prop>
- <!-- 自动建表类型 validate|create|create-drop|update -->
- <!-- <prop key="hibernate.hbm2ddl.auto">validate</prop> -->
- <!-- 是否显示SQL -->
- <prop key="hibernate.show_sql">false</prop>
- <!-- 显示SQL是否格式化 -->
- <prop key="hibernate.format_sql">false</prop>
- <!-- 关闭二级缓存 -->
- <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
- <!-- 关闭实体字段映射校验 -->
- <prop key="javax.persistence.validation.mode">none</prop>
- </props>
- </property>
- </bean>
- <bean id="sqlservertransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
- <property name="entityManagerFactory" ref="sqlserverEntityManagerFactory" />
- <qualifier value="sqlserverEM"/>
- </bean>
- <tx:annotation-driven transaction-manager="sqlservertransactionManager" proxy-target-class="false"/>
- </beans>
文章转载自:http://www.loveweir.com/