欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring&Mybatis 整合开发基础

程序员文章站 2022-06-28 23:05:03
首先新建MavenWeb项目,在webapp目录下新建WEB-INF目录,在其中新建web.xml文件:

首先新建MavenWeb项目,在webapp目录下新建WEB-INF目录,在其中新建web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
 <display-name>SpringDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

导入相关jar包:

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wu.springdemo</groupId>
  <artifactId>SpringDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  <!--  Mybatis核心包 -->
  	<dependency>
  		<groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.5.2</version>
  	</dependency>
  	<dependency>
  		<!--  Spring核心依赖包  -->
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-core</artifactId>
    	<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!--  Spring核心依赖包 -->
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-context</artifactId>
    	<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!-- Spring核心依赖包  -->
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-beans</artifactId>
    	<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!--  测试包 -->
  		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
  	</dependency>	
  </dependencies>
</project>

新建pojo,Student.java类:

package com.wu.pojo;

public class Student {
	private String name;
	private long id;
	public Student() {}
	public Student(String name,long id) {
		this.name = name;
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", id=" + id + "]";
	}
}

Spring对象创建的三种方式:

创建工厂类StudentFactory.java:

package com.wu.pojo;

public class StudentFactory {
	public  static Student getStudentStatic() {
		return new Student();
	}
	public Student getStudent() {
		return new Student();
	}
}

在src下创建sprinp的配置文件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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!--  通过bean无参创建对象 -->
	<!--  id表示对象标识 -->
	<!--  class为需要创建的类的全路径 -->
	<!--  默认为无参构造方法创建对象 -->
	<bean id="student1" class = "com.wu.pojo.Student" />
	<!--  调用相应的有参构造方法创建对象 -->
	<bean id = "student2" class = "com.wu.pojo.Student">
		  <!-- ref表示另一个bean value表示基本数据类型或者String类型  -->
		  <!--  由name和id确定参数对应参数列表的有参构造方法 -->
		<constructor-arg index = "0"  value = "张三"></constructor-arg>
		<constructor-arg index = "1"  value = "2020" name = "id"></constructor-arg>
	</bean>
	<!--  通过实例工厂创建对象 -->
	<bean id = "factory" class = "com.wu.pojo.StudentFactory"></bean>
	<bean id = "student3" factory-bean="factory" factory-method="getStudent" />
	<!--  通过静态工厂创建对象 -->
	<bean id = "student4"  class = "com.wu.pojo.StudentFactory" factory-method="getStudentStatic" />
</beans>

创建测试类TestDemo.java:

package com.wu.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.wu.pojo.Student;

public class TestDemo {
	@Test
	public void test() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Student s1 = ac.getBean("student1",Student.class);
		System.out.println("无参构造方法创建对象:"+s1);
		Student s2 = ac.getBean("student2",Student.class);
		System.out.println("有参构造方法创建对象:"+s2);
		Student s3 = ac.getBean("student3",Student.class);
		System.out.println("实例工厂创建对象:"+s3);
		Student s4 = ac.getBean("student4",Student.class);
		System.out.println("静态工厂创建对象:"+s4);
		
		 // 获取容器中管理的所有对象名
		String[] names = ac.getBeanDefinitionNames();
		for(String name : names) {
			System.out.println(name);
		}
		
	}
}

结果:

Spring&Mybatis 整合开发基础

属性注入:

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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- -通过setter赋值 -->
	<bean id = "student1" class="com.wu.pojo.Student">
		<property name="name"  value = "张三"></property>
		<!--  等效于以下语句 -->
		<property name="id">
	 		<value>2020</value>
		</property>
		<!--  类型为set集合类型 -->
		<property name="sets">
			<set>
				<value>1</value>
				<value>2</value>
				<value>3</value>
				<value>4</value>
			</set>
		</property>
		<!--  当list只要赋值一个时,只需<property name = "lists" value = "值">即可 -->
		<property name="lists">
			<list>
				<value>1</value>
				<value>2</value>
				<value>3</value>
				<value>4</value>
			</list>
		</property>
		<property name="strs">
			<array>
				<value>1</value>
				<value>2</value>
				<value>3</value>
				<value>4</value>
			</array>				
		</property>
		<property name="maps">
			<map>
				<entry key = "key1" value ="value1"></entry>
				<entry key = "key2" value ="value2"></entry>
			</map>
		</property>
		<!--  属性文件 -->
		<!-- <property name="propertys">
			<props>
				<prop key="key1">value1</prop>
				<prop key="key2">value2</prop>
				<prop key="key3">value3</prop>
			</props>
		</property> -->
	</bean>
</beans>

Student.java:

package com.wu.pojo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Student {
	private String name;
	private long id;
	private Set<?> sets;
	private List<String> lists;
	private String[] strs;
	private Map<String,String> maps;
	
	public Map<String, String> getMaps() {
		return maps;
	}
	public void setMaps(Map<String, String> maps) {
		this.maps = maps;
	}
	public String[] getStrs() {
		return strs;
	}
	public void setStrs(String[] strs) {
		this.strs = strs;
	}
	public List<String> getLists() {
		return lists;
	}
	public void setLists(List<String> lists) {
		this.lists = lists;
	}
	public Set<?> getSets() {
		return sets;
	}
	public void setSets(Set<?> sets) {
		this.sets = sets;
	}
	public Student() {}
	public Student(String name,long id) {
		this.name = name;
		this.id = id;
	}
	public Student(long id,String name) {
		this.name = name;
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", id=" + id + ", sets=" + sets + ", lists=" + lists + ", strs="
				+ Arrays.toString(strs) + ", maps=" + maps + "]";
	}
}

TestDemo.java:

package com.wu.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.wu.pojo.Student;

public class TestDemo {
	@Test
	public void test() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Student s1 = ac.getBean("student1",Student.class);
		System.out.println("通过setter赋值:"+s1);
		
		 // 获取容器中管理的所有对象名
		String[] names = ac.getBeanDefinitionNames();
		for(String name : names) {
			System.out.println(name);
		}
		
	}
}

结果:

通过setter赋值:Student [name=张三, id=2020, sets=[1, 2, 3, 4], lists=[1, 2, 3, 4], strs=[1, 2, 3, 4], maps={key1=value1, key2=value2}]
student1

DI(依赖注入)

新建Book.java:

package com.wu.pojo;

public class Book {
	private String name;
	private String  author;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	@Override
	public String toString() {
		return "Book [name=" + name + ", author=" + author + "]";
	}
}

修改Student.java:

package com.wu.pojo;

public class Student {
	private String name;
	private long id;
	private Book book;
	@Override
	public String toString() {
		return "Student [name=" + name + ", id=" + id + ", book=" + book + "]";
	}
	public Book getBook() {
		return book;
	}
	public void setBook(Book book) {
		this.book = book;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}	
}

修改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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- -通过setter赋值 -->
	<bean id = "student1" class="com.wu.pojo.Student">
		<property name="name"  value = "张三"></property>
		<!--  等效于以下语句 -->
		<property name="id">
	 		<value>2020</value>
		</property>
		<property name="book" ref = "book"></property>
	</bean>
	<bean id = "book" class = "com.wu.pojo.Book">
		<property name="name">
			<value>三体</value>
		</property>
		<property name="author">
			<value>刘慈欣</value>
		</property>
	</bean>
</beans>

结果:

依赖注入:Student [name=张三, id=2020, book=Book [name=三体, author=刘慈欣]]
student1
book

Mybatis整合

在pom.xml文件中新增包:

<!--  Mybatis-Spring包 -->
  	<dependency>
  		<groupId>org.mybatis</groupId>
    	<artifactId>mybatis-spring</artifactId>
    	<version>1.3.2</version>
  	</dependency>
  	<dependency>
  		<!--  Spring DAO依赖包 -->
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-jdbc</artifactId>
    	<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!--  Spring DAO依赖包 -->
  		<groupId>org.springframework</groupId>
   		<artifactId>spring-tx</artifactId>
    	<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!--  Spring Web依赖包 -->
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-web</artifactId>
   		<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!--  Spring 测试包 -->
  		<groupId>org.springframework</groupId>
    	<artifactId>spring-test</artifactId>
    	<version>5.2.9.RELEASE</version>
  	</dependency>
  	<dependency>
  		<!--  mysql驱动包 -->
  		<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>8.0.22</version>
  	</dependency>
  	<dependency>
  		<!--  Servlet包 -->
  		<groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>4.0.1</version>
  	</dependency>
  	<dependency>
  		<groupId>javax.servlet</groupId>
    	<artifactId>jstl</artifactId>
    	<version>1.2</version>
  	</dependency>
  	<dependency>
  		<groupId>taglibs</groupId>
    	<artifactId>standard</artifactId>
    	<version>1.1.2</version>
  	</dependency>

在src文件夹下创建Spring全局配置文件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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!--  数据源封装类 -->
	<bean id = "datasource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value = "com.mysql.cj.jdbc.Driver"></property>
		<property name="url" value = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC"></property>
		<property name="username" value = "root"></property>
		<property name="password" value = "root"></property>
	</bean>
	<!--  创建SqlSessionFactory对象 -->
	 <bean id = "factory" class = "org.mybatis.spring.SqlSessionFactoryBean">
	 	<!--  通过依赖把数据库连接信息注入dataSource属性中 -->
	 	<property name="dataSource" ref = "datasource"></property>
	 </bean>
	 <bean id = "mapperconfig" class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
	 		<!--  相当于Mybatis全局配置文件中的mapper标签里的属性 -->
	 		<!--  package标签赋值 -->
	 		<property name="basePackage" value = "com.wu.mapper"></property>
	 		<!--  确定映射关系 -->
	 		<property name="sqlSessionFactory"  ref = "factory"></property>
	 </bean>
	 <!--  Spring管理业务实现类 -->
	 <bean id = "studentservice" class = "com.wu.service.StudentServiceImpl">
	 	<property name="studentmapper" ref = "studentMapper"></property>
	 </bean>
</beans>

创建pojo,Student.java:

package com.wu.pojo;

public class Student {
	private String name;
	private long id;
	private String grade;   
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", id=" + id + ", grade=" + grade + "]";
	}
}

创建映射接口StudentMapper.java:

package com.wu.mapper;

import java.util.List;

import com.wu.pojo.Student;

public interface StudentMapper {
	List<Student> findAll();
}

创建配置Mybatis的映射文件StudentMapper.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.wu.mapper.StudentMapper">
	<select id="findAll" resultType = "com.wu.pojo.Student">
		select * from student
	</select>
</mapper>

创建业务类接口StudentService.java:

package com.wu.service;

import java.util.List;

import com.wu.pojo.Student;

public interface  StudentService {
	List<Student> show();
}

创建业务接口实现类StudentServiceMapper.java:

package com.wu.service;

import java.util.List;

import com.wu.mapper.StudentMapper;
import com.wu.pojo.Student;

public class StudentServiceImpl implements StudentService{
	private StudentMapper studentmapper;
	
	
	public StudentMapper getStudentmapper() {
		return studentmapper;
	}


	public void setStudentmapper(StudentMapper studentmapper) {
		this.studentmapper = studentmapper;
	}
	@Override
	public List<Student> show() {
		return studentmapper.findAll();
	}
	
}

创建Servlet:

package com.wu.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.wu.service.StudentService;

@WebServlet(name = "servlet" , value = {"/findAllStudent"})
public class Myservlet extends HttpServlet{
	
	private static final long serialVersionUID = -6251824731945077927L;
	private StudentService studentservice;
	@Override
	public void init(ServletConfig config) throws ServletException {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		studentservice = ac.getBean("studentservice",StudentService.class);
	}
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		req.setAttribute("studentlist", studentservice.show());
		try {
			req.getRequestDispatcher("index.jsp").forward(req,res);
		}catch(IOException | ServletException e) {
			e.printStackTrace();
		}
	}
}

创建视图层,Index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix = "c"  uri = "http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Spring&Mybatis</title>
</head>
<body>
	<div align = "center">
	<h1>学生信息表</h1>
	<table border = "1" cellspacing = "0">
		<tr>
			<th>姓名</th>
			<th>学号</th>
			<th>班级</th>
		</tr>
	<c:forEach items = "${requestScope.studentlist}" var = "s">
		<tr>
			<td>${s.name }</td>
			<td>${s.id }</td>
			<td>${s.grade }</td>
		</tr>
	</c:forEach>
	</table>
	</div>
</body>
</html>

结果:

Spring&Mybatis 整合开发基础

本文地址:https://blog.csdn.net/weixin_43914658/article/details/111995419

相关标签: SSM spring