1.spring的配置文件java
1)配置數據源,2)使用ioc配置orm ,3)事務的管理,4)掃描哪些包mysql
<?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:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--掃描的包--> <context:component-scan base-package="cn.crud"> <!--排除的註解--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"></context:exclude-filter> </context:component-scan> <!--添加資源--> <context:property-placeholder location="classpath:datasouce-config.properties"></context:property-placeholder> <!--c3p0數據源--> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <!-- 其餘的一些配置.... --> </bean> <!--mybatis--> <bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="comboPooledDataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!--mapper接口的加入到適配器中--> <bean id="configurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.crud.dao"></property> </bean> <!--mapper批量處理,使用批量的sqlsession的getmapper方法,獲取的mapper而後進行sql操做,整個mapper是一個批量操做的--> <bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sessionFactoryBean"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> <!--事務--> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="comboPooledDataSource"></property> </bean> <!--基於註解的方式--> <!--<tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>--> <!--基於配置的方式的事物--> <aop:config> <aop:pointcut id="pointcut" expression="execution(* cn.crud.service.*.*(..))"></aop:pointcut> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor> </aop:config> <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"> <tx:attributes> <tx:method name="*"/> <tx:method name="get*" read-only="true"></tx:method> </tx:attributes> </tx:advice> </beans>
2.springmvcweb
1)掃描哪些註解,2)配置InternalResourceViewResolver,3)頁面的處理spring
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="cn.crud.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"></context:include-filter> </context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" ></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:annotation-driven></mvc:annotation-driven> </beans>
3.mybatis的配置sql
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <typeAliases> <package name="com.crud.bean"/> </typeAliases> </configuration>
4.generator的逆向配置數據庫
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--跟自定義的不要緊--> <!--<classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />--> <context id="DB2Tables" targetRuntime="MyBatis3"> <!--忽略註釋--> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--鏈接數據庫--> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
&characterSetResults=utf8&useSSL=false&verifyServerCertificate=false&autoReconnct=true&autoReconnectForPools=true
&allowMultiQueries=true&serverTimezone=GMT%2B8" userId="root" password="cgz12345678"> </jdbcConnection> <!--number是否轉換爲BigDecimal類型--> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--指定bean生成的位置--> <javaModelGenerator targetPackage="cn.crud.bean" targetProject="./MavenWebTest/src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--指定mapper文件生成的位置--> <sqlMapGenerator targetPackage="mapper" targetProject="./MavenWebTest/src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!--指定mapper接口生成的位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.crud.dao" targetProject="./MavenWebTest/src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!--<table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" > <property name="useActualColumnNames" value="true"/> <generatedKey column="ID" sqlStatement="DB2" identity="true" /> <columnOverride column="DATE_FIELD" property="startDate" /> 忽略字段 <ignoreColumn column="FRED" /> 從新取字段名 <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> </table>--> <!--生成表--> <table tableName="tab_emp" domainObjectName="Employee"></table> <table tableName="tab_dept" domainObjectName="Department"></table> </context> </generatorConfiguration>
5.ehcache配置//配置文件放在類路徑下自動加載express
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <!-- 磁盤保存路徑 --> <diskStore path="D:\ss\ehcache" /> <defaultCache maxElementsInMemory="10000" maxElementsOnDisk="10000000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache> <!-- 屬性說明: l diskStore:指定數據在磁盤中的存儲位置。 l defaultCache:當藉助CacheManager.add("demoCache")建立Cache時,EhCache便會採用<defalutCache/>指定的的管理策略 如下屬性是必須的: l maxElementsInMemory - 在內存中緩存的element的最大數目 l maxElementsOnDisk - 在磁盤上緩存的element的最大數目,如果0表示無窮大 l eternal - 設定緩存的elements是否永遠不過時。若是爲true,則緩存的數據始終有效,若是爲false那麼還要根據timeToIdleSeconds,timeToLiveSeconds判斷 l overflowToDisk - 設定當內存緩存溢出的時候是否將過時的element緩存到磁盤上 如下屬性是可選的: l timeToIdleSeconds - 當緩存在EhCache中的數據先後兩次訪問的時間超過timeToIdleSeconds的屬性取值時,這些數據便會刪除,默認值是0,也就是可閒置時間無窮大 l timeToLiveSeconds - 緩存element的有效生命期,默認是0.,也就是element存活時間無窮大 diskSpoolBufferSizeMB 這個參數設置DiskStore(磁盤緩存)的緩存區大小.默認是30MB.每一個Cache都應該有本身的一個緩衝區. l diskPersistent - 在VM重啓的時候是否啓用磁盤保存EhCache中的數據,默認是false。 l diskExpiryThreadIntervalSeconds - 磁盤緩存的清理線程運行間隔,默認是120秒。每一個120s,相應的線程會進行一次EhCache中數據的清理工做 l memoryStoreEvictionPolicy - 當內存緩存達到最大,有新的element加入的時候, 移除緩存中element的策略。默認是LRU(最近最少使用),可選的有LFU(最不常使用)和FIFO(先進先出) -->
6.測試文件apache
import cn.crud.bean.Employee; import cn.crud.bean.EmployeeExample; import cn.crud.dao.EmployeeMapper; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:springcontext.xml"}) public class SSMTest { @Autowired EmployeeMapper employeeMapper; @Test public void JdbcTest() throws Exception { String str = "/springcontext.xml"; ClassPathXmlApplicationContext cpxac = new ClassPathXmlApplicationContext(str); Object comboPooledDataSource = cpxac.getBean(ComboPooledDataSource.class); Connection connection = ((ComboPooledDataSource) comboPooledDataSource).getConnection(); System.out.println(connection); connection.close(); } @Test public void TestMBG() throws Exception { String str = "MavenWebTest\\src\\main\\resources\\mbg.xml"; List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File(str); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } @Test public void TestMBGMybatis() throws Exception { //添加條件 EmployeeExample employeeExample = new EmployeeExample(); EmployeeExample.Criteria criteria = employeeExample.createCriteria(); criteria.andEmpIdEqualTo(1); List<Employee> employees = employeeMapper.selectByExample(employeeExample); for (Employee employee : employees) { System.out.println(employee); } } }