• spring mvc与mybatis与maven+mysql框架整合


    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    <html>  
      <head>  
        <title>测试</title>  
      </head>  
        
      <body>  
        ${user.userName}  
      </body>  
    </html>

    </pre>最近看了一些博客怎么搭建ssm网上的基本上都有一些小问题,网上的基本上都是不支持事物的,然后自己整理下修改成功支持事物 然后自己需要修改一下最后终于搭建成功。特意记下废话不多说直接上代码<p></p><p>工程的整个结构如下</p><p><img src="https://img-blog.csdn.net/20161014091143825?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></p><p><span style="font-size:24px">maven的pom.xml</span></p><p></p><pre name="code" class="html"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.workIt.www</groupId>
      <artifactId>workIt</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>workIt Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <properties>  
            <!-- spring版本号 -->  
            <spring.version>4.0.2.RELEASE</spring.version>  
            <!-- mybatis版本号 -->  
            <mybatis.version>3.2.6</mybatis.version>  
            <!-- log4j日志文件管理包版本 -->  
            <slf4j.version>1.7.7</slf4j.version>  
            <log4j.version>1.2.17</log4j.version>  
        </properties>  
      
        <dependencies>  
            <dependency>  
                <groupId>junit</groupId>  
                <artifactId>junit</artifactId>  
                <version>4.11</version>  
                <!-- 表示开发的时候引入,发布的时候不会加载此包 -->  
                <scope>test</scope>  
            </dependency>  
            <!-- spring核心包 -->  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-core</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-web</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-oxm</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-tx</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-jdbc</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-webmvc</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-aop</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-context-support</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-test</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <!-- mybatis核心包 -->  
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis</artifactId>  
                <version>${mybatis.version}</version>  
            </dependency>  
            <!-- mybatis/spring包 -->  
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis-spring</artifactId>  
                <version>1.2.2</version>  
            </dependency>  
            <!-- 导入java ee jar 包 -->  
            <dependency>  
                <groupId>javax</groupId>  
                <artifactId>javaee-api</artifactId>  
                <version>7.0</version>  
            </dependency>  
            <!-- 导入Mysql数据库链接jar包 -->  
            <dependency>  
                <groupId>mysql</groupId>  
                <artifactId>mysql-connector-java</artifactId>  
                <version>5.1.30</version>  
            </dependency>  
            <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->  
            <dependency>  
                <groupId>commons-dbcp</groupId>  
                <artifactId>commons-dbcp</artifactId>  
                <version>1.2.2</version>  
            </dependency>  
            <!-- JSTL标签类 -->  
            <dependency>  
                <groupId>jstl</groupId>  
                <artifactId>jstl</artifactId>  
                <version>1.2</version>  
            </dependency>  
            <!-- 日志文件管理包 -->  
            <!-- log start -->  
            <dependency>  
                <groupId>log4j</groupId>  
                <artifactId>log4j</artifactId>  
                <version>${log4j.version}</version>  
            </dependency>  
              
              
            <!-- 格式化对象,方便输出日志 -->  
            <dependency>  
                <groupId>com.alibaba</groupId>  
                <artifactId>fastjson</artifactId>  
                <version>1.1.41</version>  
            </dependency>  
      
      
            <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-api</artifactId>  
                <version>${slf4j.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.slf4j</groupId>  
                <artifactId>slf4j-log4j12</artifactId>  
                <version>${slf4j.version}</version>  
            </dependency>  
            <!-- log end -->  
            <!-- 映入JSON -->  
            <dependency>  
                <groupId>org.codehaus.jackson</groupId>  
                <artifactId>jackson-mapper-asl</artifactId>  
                <version>1.9.13</version>  
            </dependency>  
            <!-- 上传组件包 -->  
            <dependency>  
                <groupId>commons-fileupload</groupId>  
                <artifactId>commons-fileupload</artifactId>  
                <version>1.3.1</version>  
            </dependency>  
            <dependency>  
                <groupId>commons-io</groupId>  
                <artifactId>commons-io</artifactId>  
                <version>2.4</version>  
            </dependency>  
            <dependency>  
                <groupId>commons-codec</groupId>  
                <artifactId>commons-codec</artifactId>  
                <version>1.9</version>  
            </dependency>  
              
              
        </dependencies>  
      <build>
        <finalName>workIt</finalName>
      </build>
    </project>
    

    jdbc.properties文件

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/workit
    jdbc.username=root
    jdbc.password=root
    #u5B9Au4E49u521Du59CBu8FDEu63A5u6570  
    jdbc.initialSize=0
    #u5B9Au4E49u6700u5927u8FDEu63A5u6570  
    jdbc.maxActive=20
    #u5B9Au4E49u6700u5927u7A7Au95F2  
    jdbc.maxIdle=20
    #u5B9Au4E49u6700u5C0Fu7A7Au95F2  
    jdbc.minIdle=1
    #u5B9Au4E49u6700u957Fu7B49u5F85u65F6u95F4  
    jdbc.maxWait=60000

    log4j.properties文件

    </pre><span style="font-size:12px"></span><pre name="code" class="html">log4j.rootLogger=INFO,Console,File  
    #u5B9Au4E49u65E5u5FD7u8F93u51FAu76EEu7684u5730u4E3Au63A7u5236u53F0  
    log4j.appender.Console=org.apache.log4j.ConsoleAppender  
    log4j.appender.Console.Target=System.out  
    #u53EFu4EE5u7075u6D3Bu5730u6307u5B9Au65E5u5FD7u8F93u51FAu683Cu5F0FuFF0Cu4E0Bu9762u4E00u884Cu662Fu6307u5B9Au5177u4F53u7684u683Cu5F0F  
    log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
    log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
      
    #u6587u4EF6u5927u5C0Fu5230u8FBEu6307u5B9Au5C3Au5BF8u7684u65F6u5019u4EA7u751Fu4E00u4E2Au65B0u7684u6587u4EF6  
    log4j.appender.File = org.apache.log4j.RollingFileAppender  
    #u6307u5B9Au8F93u51FAu76EEu5F55  
    log4j.appender.File.File = logs/ssm.log  
    #u5B9Au4E49u6587u4EF6u6700u5927u5927u5C0F  
    log4j.appender.File.MaxFileSize = 10MB  
    # u8F93u51FAu6240u4EE5u65E5u5FD7uFF0Cu5982u679Cu6362u6210DEBUGu8868u793Au8F93u51FADEBUGu4EE5u4E0Au7EA7u522Bu65E5u5FD7  
    log4j.appender.File.Threshold = ALL  
    log4j.appender.File.layout = org.apache.log4j.PatternLayout  
    log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n  
    


    spring-mybatis.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:p="http://www.springframework.org/schema/p"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:tx="http://www.springframework.org/schema/tx"  
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
                            http://www.springframework.org/schema/tx 
        					http://www.springframework.org/schema/tx/spring-tx-3.1.xsd   
                            http://www.springframework.org/schema/context    
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
        <!-- 自动扫描 -->  
        <context:component-scan base-package="com.workit" > 
         	<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 
         </context:component-scan>
         
        <tx:annotation-driven transaction-manager="transactionManager" />
        
        <!-- 引入配置文件 -->  
        <bean id="propertyConfigurer"  
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
            <property name="location" value="classpath:jdbc.properties" />  
        </bean>  
      
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
            destroy-method="close">  
            <property name="driverClassName" value="${jdbc.driver}" />  
            <property name="url" value="${jdbc.url}" />  
            <property name="username" value="${jdbc.username}" />  
            <property name="password" value="${jdbc.password}" />  
            <!-- 初始化连接大小 -->  
            <property name="initialSize" value="${jdbc.initialSize}"></property>  
            <!-- 连接池最大数量 -->  
            <property name="maxActive" value="${jdbc.maxActive}"></property>  
            <!-- 连接池最大空闲 -->  
            <property name="maxIdle" value="${jdbc.maxIdle}"></property>  
            <!-- 连接池最小空闲 -->  
            <property name="minIdle" value="${jdbc.minIdle}"></property>  
            <!-- 获取连接最大等待时间 -->  
            <property name="maxWait" value="${jdbc.maxWait}"></property>  
        </bean>  
      
      	<!-- 事务管理器 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
            <property name="dataSource" ref="dataSource" />  
            <!-- 自动扫描mapping.xml文件 -->  
            <property name="mapperLocations" value="classpath:com/workit/mapper/*.xml"></property>  
        </bean>  
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
            <property name="basePackage" value="com.workit.dao" />  
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
        </bean>  
      
       
      
    </beans>

    spring-mvc.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:p="http://www.springframework.org/schema/p"  
        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-3.1.xsd    
                            http://www.springframework.org/schema/context    
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
        <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->  
        <context:component-scan base-package="com.workit.controller" />
        <!--避免IE执行AJAX时,返回JSON出现下载文件 -->  
        <bean id="mappingJacksonHttpMessageConverter"  
            class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
            <property name="supportedMediaTypes">  
                <list>  
                    <value>text/html;charset=UTF-8</value>  
                </list>  
            </property>  
        </bean>  
        <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->  
        <bean  
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
            <property name="messageConverters">  
                <list>  
                    <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->  
                </list>  
            </property>  
        </bean>  
        <!-- 定义跳转的文件的前后缀 ,视图模式配置-->  
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
            <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->  
            <property name="prefix" value="/WEB-INF/jsp/" />  
            <property name="suffix" value=".jsp" />  
        </bean>  
          
        <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->  
        <bean id="multipartResolver"    
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
            <!-- 默认编码 -->  
            <property name="defaultEncoding" value="utf-8" />    
            <!-- 文件大小最大值 -->  
            <property name="maxUploadSize" value="10485760000" />    
            <!-- 内存中的最大值 -->  
            <property name="maxInMemorySize" value="40960" />    
        </bean>   
      
    </beans>  

    创建测试用表

    既然我们需要测试,那么我们就需要建立在数据库中建立一个测试表,这个表建的很简单,SQL语句为:

    DROP TABLE IF EXISTS `user_t`;  
      
    CREATE TABLE `user_t` (  
      `id` int(11) NOT NULL AUTO_INCREMENT,  
      `user_name` varchar(40) NOT NULL,  
      `password` varchar(255) NOT NULL,  
      `age` int(4) NOT NULL,  
      PRIMARY KEY (`id`)  
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  
      
    /*Data for the table `user_t` */  
      
    insert  into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'测试','sfasgfaf',24); 
    ql] view placopy派生到我的代码片




    利用MyBatis Generator自动创建代码

    参考博文:http://blog.csdn.net/zhshulin/article/details/23912615


    
    
    BaseDao文件
    <pre name="code" class="java">package com.workit.dao;
    
    import java.util.List;
    
    public interface BaseDao<T> {
    
    	int deleteByPrimaryKey(Integer id);
    
    	int insert(T model);
    
    	T selectByExample(Integer id);
    
    	List<T> selectByPrimaryKey(T model);
    }
    


    
    UserDao文件
    
    
    
    <pre name="code" class="java">package com.workit.dao;
    
    import com.workit.model.UserT;
    
    public interface UserDao extends BaseDao<UserT> {
    
    }


    
    UserMapper文件
    
    
    
    <pre name="code" class="html"><?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="com.workit.dao.UserDao" >
      <resultMap id="BaseResultMap" type="com.workit.model.UserT" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
      </resultMap>
      <sql id="Base_Column_List" >
        id, user_name, password, age
      </sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from user_t
        where id = #{id,jdbcType=INTEGER}
      </select>
        <insert id="insert" parameterType="com.workit.model.UserT" >
        insert into user_t (id, user_name, password, 
          age)
        values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
          #{age,jdbcType=INTEGER})
      </insert>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from user_t
        where id = #{id,jdbcType=INTEGER}
      </delete>
    </mapper>


    
    
    
    
    UserT文件
    <pre name="code" class="java">package com.workit.model;
    
    public class UserT {
        private Integer id;
    
        private String userName;
    
        private String password;
    
        private Integer age;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName == null ? null : userName.trim();
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password == null ? null : password.trim();
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
    	@Override
    	public String toString() {
    		return "UserT [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]";
    	}
        
    }


    
    BaseService文件
    
    
    
    <pre name="code" class="java">package com.workit.service;
    
    import java.util.List;
    
    public interface BaseService<T> {
    	int deleteById(Integer id);
    
    	int insert(T model);
    
    	T getModelById(Integer id);
    
    	List<T> getListModelById(T model);
    	
    }
    

    
    

    UserService文件

    package com.workit.service;
    
    import com.workit.model.UserT;
    
    /** 
    * @author 作者 E-mail: zfg@jkinvest.cn;
    * @version 创建时间:2016年10月12日 下午4:55:15 
    * 类说明 
    */
    public interface UserService extends BaseService<UserT>{
    }
    

    UserServiceImpl文件

    package com.workit.service.impl;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.workit.dao.UserDao;
    import com.workit.model.UserT;
    import com.workit.service.UserService;
    
    /** 
    * @author 作者 E-mail: zfg@jkinvest.cn;
    * @version 创建时间:2016年10月12日 下午4:56:01 
    * 类说明 
    */
    @Transactional
    @Service("userService")  
    public class UserServiceImpl implements UserService {
    	
    	 @Resource  
    	  private UserDao userDao;
    	 
    
    
    
    	@Override
    	public int deleteById(Integer id) {
    		// TODO Auto-generated method stub
    		return userDao.deleteByPrimaryKey(id);
    	}
    
    
    	@Override
    	public UserT getModelById(Integer id) {
    		// TODO Auto-generated method stub
    		return userDao.selectByExample(id);
    	}
    
    
    	@Override
    	public List<UserT> getListModelById(UserT model) {
    		// TODO Auto-generated method stub
    		return userDao.selectByPrimaryKey(model);
    	}
    
    
    	@Override
    	public int insert(UserT model) {
    		// TODO Auto-generated method stub
    		return userDao.insert(model);
    	}
    
    }
    

    UserController文件

    package com.workit.controller;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.workit.model.UserT;
    import com.workit.service.UserService;
    
    @Controller
    public class UserController {
    	 @Resource  
    	    private UserService userService;  
    	     Logger logger =  LoggerFactory.getLogger(UserController.class);
    	    @RequestMapping("/showUser")  
    	    public String toIndex(HttpServletRequest request,Model model){  
    	    	logger.info("index to index");
    	        int userId = Integer.parseInt(request.getParameter("id"));  
    	        UserT user = userService.getModelById(userId);
    	        model.addAttribute("user", user);  
    	        return "showUser"; 
    	    }
    }
    showUser.jsp

    测试类

    package workit;
    
    import javax.annotation.Resource;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.workit.model.UserT;
    import com.workit.service.UserService;
    
    /** 
    * @author 作者 E-mail: zfg@jkinvest.cn;
    * @version 创建时间:2016年10月12日 下午4:59:05 
    * 类说明 
    */
    @RunWith(SpringJUnit4ClassRunner.class)     //表示继承了SpringJUnit4ClassRunner类  
    @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})  
    public class test {
    
    	@Resource  
        private UserService userService;  
    	
    	@Test
    	public void test() {
    		try {
    			//userService.deleteByPrimaryKey(12);
    			UserT user = new UserT();
    			user.setId(122);
    			user.setUserName("12122");
    			user.setPassword("222");
    			user.setAge(90);
    			//userService.insert(user);
    			userService.insert(user);
    			//System.out.println(userService.selectByPrimaryKey(12));
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    	}
    
    }
    

    资源下载http://download.csdn.net/detail/zengfanwei1990/9653507

    
    

  • 相关阅读:
    蓝桥杯 小朋友排队
    uestc 方老师和缘分
    uestc 方老师抢银行
    Tarjan 求强连通分量模板
    树边,前向边,后向边,横叉边
    hihocoder 第三十六周 二分·二分查找
    hihocoder 第三十四周 二分图三·二分图最小点覆盖和最大独立集
    CF 两题
    hihocoder 第三十三周 二分图一•二分图判定
    hdu 4430 Yukari's Birthday
  • 原文地址:https://www.cnblogs.com/root429/p/9251398.html
Copyright © 2020-2023  润新知