Spring与MyBatis整合

2021-06-20 11:05

阅读:669

标签:name   local   end   ora   val   figure   version   修改   utf-8   

在 spring运行在tomcat上 的基础上,进行增加mybatis整合

第一步:增加com.fd.spring.mapper包,并增加 StudentMapper接口

package com.fd.spring.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.fd.spring.model.Student;

public interface StudentMapper {
	@Select("select * from student")
	public List selAll();
}

第二步:增加com.fd.spring.service包,并增加 StudentService接口

package com.fd.spring.service;

import java.util.List;

import com.fd.spring.model.Student;

public interface StudentService {
	public List selAll();
}

第三步:增加com.fd.spring.service.impl包,并增加StudentServiceImpl类

package com.fd.spring.service.impl;

import java.util.List;

import com.fd.spring.mapper.StudentMapper;
import com.fd.spring.model.Student;
import com.fd.spring.service.StudentService;

public class StudentServiceImpl implements StudentService{
	private StudentMapper studentMapper;
	
	@Override
	public List selAll() {
		return studentMapper.selAll();
	}

	public StudentMapper getStudentMapper() {
		return studentMapper;
	}

	public void setStudentMapper(StudentMapper studentMapper) {
		this.studentMapper = studentMapper;
	}

}

 第四步:修改applicationContext.xml

 第五步:修改StudentServlet类

package com.fd.spring.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
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 org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.fd.spring.model.Student;
import com.fd.spring.service.StudentService;
import com.fd.spring.service.impl.StudentServiceImpl;

@WebServlet("/student")
public class StudentServlet extends HttpServlet{
	private StudentService studentService;
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		studentService = wac.getBean("studentService", StudentServiceImpl.class);
		System.out.println("studentService = " + studentService);
	}
	
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("service...");
		List list = studentService.selAll();
		System.out.println("list.size() = " + list.size());
		req.setAttribute("list", list);
		req.getRequestDispatcher("index.jsp").forward(req, resp);
	}
}

  最后运行结果如下图所示

技术分享图片

 

 

 

Spring与MyBatis整合

标签:name   local   end   ora   val   figure   version   修改   utf-8   

原文地址:https://www.cnblogs.com/spark-quant/p/9688853.html


评论


亲,登录后才可以留言!