1. 程式人生 > >spring + struts2 + mybatis整合

spring + struts2 + mybatis整合

我接觸最多的java持久層的框架應該是hibernate了,但是看一些企業招聘好多都要求會mybatis,所以學習了並整合了一下。

對於hibernate和mybatis的優缺點下片文章再細講,我們先來整合。

首先整合spring+struts2,引入他們的jar包,這裡直接給出我引入所有包的圖:

首先在web.xml檔案中配置spring的監聽器:

<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


classpath下新增spring的配置檔案spring.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" xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

	<!-- 自動掃描dao和service包(自動注入) -->
	<context:component-scan base-package="com.dxy.service" />

</beans>


在web.xml檔案中新增:

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:spring.xml,classpath:springmybatis.xml</param-value>
</context-param>

用來指定spring的配置檔案。

注意:讓spring來管理你的action,我們得新增struts2-spring-plugin.jar。


然後在classpath下新增struts.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

	<!-- 指定由spring負責action物件的建立 -->
	<constant name="struts.objectFactory" value="spring" />
	<!-- 所有匹配*.action的請求都由struts2處理 -->
	<constant name="struts.action.extension" value="action" />
	<!-- 是否啟用開發模式 -->
	<constant name="struts.devMode" value="true" />
	<!-- struts配置檔案改動後,是否重新載入 -->
	<constant name="struts.configuration.xml.reload" value="true" />
	<!-- 設定瀏覽器是否快取靜態內容 -->
	<constant name="struts.serve.static.browserCache" value="false" />
	<!-- 請求引數的編碼方式 -->
	<constant name="struts.i18n.encoding" value="utf-8" />
	<!-- 每次HTTP請求系統都重新載入資原始檔,有助於開發 -->
	<constant name="struts.i18n.reload" value="true" />
	<!-- 檔案上傳最大值 -->
	<constant name="struts.multipart.maxSize" value="104857600" />
	<!-- 讓struts2支援動態方法呼叫 -->
	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
	<!-- Action名稱中是否還是用斜線 -->
	<constant name="struts.enable.SlashesInActionNames" value="false" />
	<!-- 允許標籤中使用表示式語法 -->
	<constant name="struts.tag.altSyntax" value="true" />
	<!-- 對於WebLogic,Orion,OC4J此屬性應該設定成true -->
	<constant name="struts.dispatcher.parametersWorkaround" value="false" />
	
	<!--用於WEB-INF下的頁面的跳轉 -->
	<package name="skip" namespace="/skip" extends="struts-default">
	</package>
</struts>


注意:讓spring幫我們來管理action,struts.xml檔案中得加入

<!-- 指定由spring負責action物件的建立 -->
<constant name="struts.objectFactory" value="spring" />

上文中已加入。

接著整合mybatis,在classpath下新增springmybatis.xml檔案:

springmybatis.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/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
    <context:property-placeholder location="classpath:jdbc.properties" />
    <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}" />
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="mapperLocations" value="classpath:com/dxy/mapper/*.xml" />
       <property name="typeAliasesPackage" value="com.dxy.model" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.dxy.mapper" />
    </bean>
</beans>


感覺和spring整合hibernate差別不大。

建立自己的類:

Blog.java

package com.dxy.model;

public class Blog {
	
	private int id;
	
	private String title;
	
	private String content;
	
	private String owner;

	public int getId() {
		return id;
	}

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

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}
	
}


BlogService.java

package com.dxy.service;

import java.util.List;

import com.dxy.model.Blog;

public interface BlogService {
	
	public Blog selectBlog(int id);
	   
    public void insertBlog(Blog blog);
   
    public void updateBlog(Blog blog);
   
    public void deleteBlog(int id);
   
    public List<Blog> selectAll();
}


建立BlogMapper.java:

package com.dxy.mapper;
import java.util.List;

import com.dxy.model.Blog;

 
public interface BlogMapper {
 
    public Blog selectBlog(int id);
   
    public void insertBlog(Blog blog);
   
    public void updateBlog(Blog blog);
   
    public void deleteBlog(int id);
   
    public List<Blog> selectAll();
   
}


建立BlogMapper.java的配置檔案BlogMapper.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="com.dxy.mapper.BlogMapper">

<resultMap type="com.dxy.model.Blog" id="blogMapper">
	<result property="id" column="id"/>
	<result property="title" column="title"/>
	<result property="content" column="content"/>
	<result property="owner" column="owner"/>
</resultMap>

<!--  新增記錄  -->
    <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="id">
        insert into t_blog(title,content,owner) values(#{title},#{content},#{owner})
    </insert>
<!--  查詢單條記錄  -->
    <select id="selectBlog" parameterType="int" resultMap="blogMapper">
       select * from t_blog where id = #{id}
    </select>
<!--  修改記錄  -->
    <update id="updateBlog" parameterType="Blog">
        update t_blog set title = #{title},content = #{content},owner = #{owner} where id = #{id}
    </update>
<!--  查詢所有記錄  -->
    <select id="selectAll" resultMap="blogMapper">
        select * from t_blog
    </select>
<!--  刪除記錄  -->
    <delete id="deleteBlog" parameterType="int">
       delete from t_blog where id = #{id}
    </delete>
   
</mapper>


建立service的實現類BlogServiceImpl.java:

package com.dxy.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.dxy.mapper.BlogMapper;
import com.dxy.model.Blog;
import com.dxy.service.BlogService;
@Service("blogService")
public class BlogServiceImpl implements BlogService {
	
	private BlogMapper blogMapper;

	@Override
	public Blog selectBlog(int id) {
		return blogMapper.selectBlog(id);
	}

	@Override
	public void insertBlog(Blog blog) {
		blogMapper.insertBlog(blog);
		
	}

	@Override
	public void updateBlog(Blog blog) {
		blogMapper.updateBlog(blog);
	}

	@Override
	public void deleteBlog(int id) {
		blogMapper.deleteBlog(id);
	}

	@Override
	public List<Blog> selectAll() {
		return blogMapper.selectAll();
	}

	public BlogMapper getBlogMapper() {
		return blogMapper;
	}
	@Resource
	public void setBlogMapper(BlogMapper blogMapper) {
		this.blogMapper = blogMapper;
	}


}


在新增BlogMapper.xml時,在查詢時有查詢結果,在BlogMapper.xml檔案中得定義resultMap:

<resultMap type="com.dxy.model.Blog" id="blogMapper">
	<result property="id" column="id"/>
	<result property="title" column="title"/>
	<result property="content" column="content"/>
	<result property="owner" column="owner"/>
</resultMap>



接下來新增action類BlogAction.java:

package com.dxy.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.dxy.model.Blog;
import com.dxy.service.BlogService;

@Namespace("/")
@Results({
	@Result(name="addBlog",location="/index.jsp")
})
@Action("blogAction")
public class BlogAction {
	
	private BlogService blogService;
	
	public String addBlog() {
		Blog blog = new Blog();
		blog.setTitle("test");
		blog.setContent("test1");
		blog.setOwner("test3");
		blogService.insertBlog(blog);
		System.out.println("test");
		Blog blog2 = blogService.selectBlog(1);
		System.out.println(blogService.selectBlog(1));
		System.out.println(blog2.getContent());
		return "addBlog";
	}

	public BlogService getBlogService() {
		return blogService;
	}
	@Autowired
	public void setBlogService(BlogService blogService) {
		this.blogService = blogService;
	}
}

檢查資料庫和後臺輸出。資料庫有資料後臺列印test,整合完成。

經檢驗,上述程式正常執行。