标签:
一、创建一个Web工程
二、导入jar包到lib下
c3p0-0.9:
mvc_jackson-1.7.2
mybatis_spring
myBatis3.2.2
mysql_driver
spring-3.2-aop
spring-3.2-core
spring-3.2-persistence
spring-3.2-web
三、整合spring与mybatis及springmvc
注意:注释的代码是正常配置的,注释下边的是优化以后的
配置文件如下
myBatis-config.xml文件
<?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> <!-- 通过别名简化对类的使用 --> <typeAliases> <!-- <typeAlias type="cn.buaa.scm.entity.Dept" alias="Dept" /> --> <!-- 通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean, 并且默认设置一个别名,默认的名字为非限定类名来作为它的别名。 --> <package name="cn.buaa.scm.entity"/> </typeAliases> <!-- <mappers> <mapper resource="cn/buaa/scm/entity/DeptMapper.xml" /> </mappers> --> </configuration>
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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <!-- 配置数据源,记得去掉myBatis-config.xml的数据源相关配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/scm?useUnicode=true&characterEncoding=UTF-8" /> <property name="user" value="root" /> <property name="password" value="123456" /> </bean> <!-- 配置session工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:myBatis-config.xml" /> <!--配置扫描式加载SQL映射文件,记得去掉mybatis-config配置--> <property name="mapperLocations" value="classpath:cn/buaa/scm/dao/*.xml"/> </bean> <!-- 配置事务管理器,管理数据源事务处理--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务通知 --> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 --> <tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <!-- 配置切面织入的范围,后边要把事务边界定在service层 --> <aop:config> <aop:advisor advice-ref="advice" pointcut="execution(* cn.buaa.scm.service.impl.*.*(..))"/> </aop:config> <!-- 配置SessionTemplate,已封装了繁琐的数据操作--> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <!-- <context:component-scan base-package="*"/> --> <!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。 --> <context:component-scan base-package="cn.buaa"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 配置 转换器,对于在basePackage设置的包(包括子包)下的接口类,如果在Mapper.xml文件中定义过, 将被转换成spring的BEAN,在调用 的地方通过@Autowired方式将可以注入接口实例--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> <property name="basePackage" value="cn.buaa.scm.dao"/> </bean> </beans>myBatis-config.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> <mvc:annotation-driven></mvc:annotation-driven> <!-- <context:component-scan base-package="*"/> --> <!-- 扫描所有的controller 但是不扫描service --> <context:component-scan base-package="cn.buaa"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> </beans>log4j.properties
# Rules reminder: # DEBUG < INFO < WARN < ERROR < FATAL # Global logging configuration log4j.rootLogger=INFO,stdout # My logging configuration... log4j.logger.cn.jbit.mybatisdemo=DEBUG ## Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n log4j.logger.org.apache.ibatis=DEBUG ## log4j.logger.org.apache.jdbc.SimpleDataSource=DEBUG log4j.logger.org.apache.ibatis.jdbc.ScriptRunner=DEBUG ## log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapclientDelegate=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUGnewSql.sql
drop database if exists scm; create database scm default character set utf8; use scm; drop table if exists supplier; /*============================*/ /* Table: 管理员表结构 */ /*============================*/ create table account ( /* 管理员编号,自动增长 */ acc_id int not null auto_increment, /* 管理员登录名 */ acc_login varchar(20), /* 管理员姓名 */ acc_name varchar(20), /* 管理员密码 */ acc_pass varchar(20), /* 设置编号为主键 */ primary key (acc_id) ); /*==============================================================*/ /* Table: 供应商表 */ /*==============================================================*/ create table supplier ( sup_id int not null auto_increment, sup_name varchar(20), sup_linkman varchar(20), sup_phone varchar(11), sup_address varchar(100), sup_remark varchar(200), primary key (sup_id) ); /* 添加供应商数据, */ insert into account (acc_login,acc_pass) values ('admin','admin'); insert into account (acc_login,acc_pass) values ('admin2','admin2'); /* 添加供应商数据, */ insert into supplier (sup_name,sup_linkman,sup_phone,sup_address,sup_remark) values ('苹果供应商','小张','12388888887','广州花都','普通供应商'); insert into supplier (sup_name,sup_linkman,sup_phone,sup_address,sup_remark) values ('三星供应商','小王','12388888888','广州增城','普通供应商'); insert into supplier (sup_name,sup_linkman,sup_phone,sup_address,sup_remark) values ('华为供应商','小王','12388888889','广东深圳','一级供应商'); select * from account; select * from supplier;generatorConfig.xml (mybatis逆向工程配置文件,上个文章有介绍插件的安装)
<?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> <!-- <properties resource="conn.properties" /> --> <classPathEntry location="G:\jar_lib\mysql_driver\mysql-connector-java-5.1.26-bin.jar"/> <!-- 指定运行环境是mybatis3的版本 --> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否取消注释 --> <property name="suppressAllComments" value="true" /> <!-- 是否生成注释代时间戳 --> <property name="suppressDate" value="true" /> </commentGenerator> <!-- jdbc 连接信息 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/scm?useUnicode=true&characterEncoding=UTF-8" userId="root" password="123456"> </jdbcConnection> <!-- targetPackage指定模型在生成在哪个包 ,targetProject指定项目的src,--> <javaModelGenerator targetPackage="cn.buaa.scm.entity" targetProject="scm/src"> <!-- 去除字段前后空格 --> <property name="trimStrings" value="false" /> </javaModelGenerator> <!-- 配置SQL映射文件生成信息 --> <sqlMapGenerator targetPackage="cn.buaa.scm.dao" targetProject="scm/src" /> <!--配置dao接口生成信息--> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.buaa.scm.dao" targetProject="scm/src" /> <table tableName="account" domainObjectName="Account"/> <table tableName="supplier" domainObjectName="Supplier"/> </context> </generatorConfiguration>web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
四、entity及其dao等
SupplierMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="cn.buaa.scm.dao.SupplierMapper"> <resultMap id="supplierResultMap" type="cn.buaa.scm.entity.Supplier"> <id column="sup_id" property="supId" jdbcType="INTEGER" /> <result column="sup_name" property="supName" jdbcType="VARCHAR" /> <result column="sup_linkman" property="supLinkman" jdbcType="VARCHAR" /> <result column="sup_phone" property="supPhone" jdbcType="VARCHAR" /> <result column="sup_address" property="supAddress" jdbcType="VARCHAR" /> <result column="sup_remark" property="supRemark" jdbcType="VARCHAR" /> </resultMap> <insert id="insert" parameterType="Supplier"> insert into supplier(sup_name) values (#{supName}) </insert> </mapper>
SupplierMapper.java (Dao 以为插件生成了这样,认识就好)
package cn.buaa.scm.dao; import cn.buaa.scm.entity.Supplier; public interface SupplierMapper extends BaseMapper<Supplier>{ /** * 添加供应商 * @param supplier * @return */ }
SupplierServiceImpl.java
package cn.buaa.scm.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.buaa.scm.dao.SupplierMapper; import cn.buaa.scm.entity.Supplier; import cn.buaa.scm.service.SupplierService; @Service("supplierService") public class SupplierServiceImpl implements SupplierService { //@Resource @Autowired private SupplierMapper supplierMapper; public int insert(Supplier supplier) throws Exception { return supplierMapper.insert(supplier); } @Override public int delete(Supplier entity) { return 0; } @Override public Supplier select(Supplier entity) { return null; } @Override public int update(Supplier entity) throws Exception { // TODO Auto-generated method stub return 0; } }SupplierAction.java
package cn.buaa.scm.action; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.buaa.scm.entity.Supplier; import cn.buaa.scm.service.SupplierService; @Controller @RequestMapping(value="/supplier") public class SupplierAction extends BaseAction { @Resource private SupplierService supplierService; @RequestMapping(value="/insert") public String insert(Supplier supplier){ System.out.println("---action.dept:"+supplier); try { supplierService.insert(supplier); } catch (Exception e) { e.printStackTrace(); } return "forward:/jsp/main.jsp"; } @RequestMapping("/doAjax") @ResponseBody //如果返回json格式,需要这个注解,这里用来测试环境 public Object doAjax(Supplier supplier){ System.out.println("---doAjax.supplier:"+supplier); supplier.setSupName("supName1"); return supplier; } }
index.jsp 框架测试
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> </head> <body> <form action="supplier/insert.action" method="post"> 供应商名称:<input type="text" name="supName"><br> <input type="submit" value="ok"> </form> </body> </html>json.jsp easyUI和jquery测试
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> </head> <body> <form action="supplier/insert.action" method="post"> 供应商名称:<input type="text" name="supName"><br> <input type="submit" value="ok"> </form> </body> </html>
注意,这些配置要根据自己包名等调整,dao的实现类用xml配置了,直接可以实现,不用在写dao的实现类,有点方法抽取没贴出来,不过不影响整合
这个版本切记在Tomcat7.0以下版本运行,8.0会报错,原因不明。
ssi整合,即spring、springmvc、mybatis终极整合,包括一些优化
标签:
原文地址:http://blog.csdn.net/zd305826520/article/details/51357454