Spring4.2.4 + Mybatis 3.4.5 整合成web项目

  1. 开发环境为:

        Eclispe 4.6.3

              Windows x64

              Tomcat 7.0

       2.项目的目录结构

        

3.使用jar包截图

         

4.实体bean

        

package com.cn.bean;

public class Goods {
	private Integer id;
	private String name;
	private String type;

	public Goods() {
		super();
	}

	public Goods(String name, String type) {
		super();
		this.name = name;
		this.type = type;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getId() {
		return id;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getType() {
		return type;
	}

	@Override
	public String toString() {
		return "Goods [id=" + id + ", name=" + name + ", type=" + type + "]";
	}

}

5.mapper接口和映射文件

         

package com.cn.mapper;

import java.util.List;

import com.cn.bean.Goods;

/**
 * @ClassName GoodsMapper
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hasee
 * @Date 2017年12月1日 下午5:46:25
 * @version 1.0.0
 */
public interface GoodsMapper {

	List<Goods> findAll();

	void save(Goods goods);

}

<?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.cn.mapper.GoodsMapper">

  <select id="findAll" resultType="goods">
     select * from goods
  </select>
  
  <insert id="save" parameterType="goods">
      insert into goods(name,type) values(#{name},#{type})
  </insert>

</mapper>


6.service层

package com.cn.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cn.bean.Goods;
import com.cn.mapper.GoodsMapper;

/**
 * @ClassName GoodsServiceImpl
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hasee
 * @Date 2017年12月1日 下午5:50:11
 * @version 1.0.0
 */
@Transactional
@Service
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private GoodsMapper mapper;

	@Override
	public List<Goods> queryAll() {
		// TODO Auto-generated method stub
		return mapper.findAll();
	}

	@Override
	public void add(Goods goods) {
		mapper.save(goods);
	}

}

7.mybatis 的配置文件

 

<?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="autoMappingBehavior" value="FULL" /> <!-- 开启全部自动映射,包含嵌套查询 -->

		<!-- 打开懒加载的开关 -->
		<!-- <setting name="lazyLoadingEnabled" value="true" /> -->

	</settings>


</configuration>

8.spring整合mybatis的配置文件

<?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: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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

	<!-- 开启组件扫描 -->
	<context:component-scan base-package="com.cn.service"></context:component-scan>


	<!--配置数据源 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3308/mybatis"></property>
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
		<!-- <property name="defaultAutoCommit" value="false"></property> -->

		<!-- 选配信息 -->

	</bean>


	<!-- 配置sqlsessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<!--扫描映射文件 -->
		<property name="mapperLocations" value="classpath:com/cn/mapper/*.xml"></property>
		<!--设置别名 -->
		<property name="typeAliasesPackage" value="com.cn.bean"></property>
		
	</bean>

	<!--配置扫描Mapper接口 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
		<property name="basePackage" value="com.cn.mapper"></property>
	</bean>

	<!--配置JDBC事务管理 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!--开启注解事务 -->
	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>


9.注意,因为整合的普通web项目,使用的是servlet,所以在servlet中调用服务层的方法时,service的对象不能够通过注解注入,因为servlet是由tomcat容器管理,会导致spring容器的注解注入失效,所以必须通过下面的applicationContext 工具类来获取 context对象,进而从容器中获取service层的实例对象

package com.cn.service;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class CtxUtil implements ApplicationContextAware {

	public static ApplicationContext ctx;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		this.ctx = arg0;
	}

	/**
	* 根据类型获得bean
	*/
	public static <T> T getBean(Class<T> clazz) {
		return ctx.getBean(clazz);
	}

	/**
	 * 根据名称名称获得bean
	 */
	public static Object getBean(String name) {
		return ctx.getBean(name);
	}

}

10.控制器servlet中的代码

package com.cn.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.bean.Goods;
import com.cn.service.CtxUtil;
import com.cn.service.GoodsService;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/test.do")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private GoodsService service;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		service = CtxUtil.getBean(GoodsService.class);

		String name = request.getParameter("name");
		String type = request.getParameter("type");

		Goods goods = new Goods(name, type);

		service.add(goods);

		response.getWriter().println("add success!");

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

11.jsp页面

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Spring-Mybatis 整合 WEB 项目</title>
</head>
<body>




       <form action="test.do">
       
          <p> 商品名称:<input type="text" name="name" /></p>
          <p>商品类型:<input type="text" name="type"/></p>
          <p> <input type="submit" /></p>
       
       </form>
</body>
</html>

12.最为重要的一步,必须在web.xml 配置文件中,配置spring 配置文件的 监听器和初始化参数

<?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>Spring-Mybatis_Web</display-name>
  
  <!--全局初始化参数  加载配置文件  -->
  <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>
  
  
  <!-- 配置监听器 -->
  <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  
  
</web-app>



          

 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值