Mybatis 基础入门

在这里插入图片描述

原始数据库test中student表结构:
在这里插入图片描述

创建Maven工程,在pom.xml文件导入相应的包

pom.xml:

<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.mybatis_learn1</groupId>
  <artifactId>MybatisDemo1</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>
	  <!--  mysql驱动包 -->
	  <dependency>
	  	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>8.0.22</version>
	  </dependency>
	  <!--  日志包  -->
	  <dependency>
	  	<groupId>log4j</groupId>
	  	<artifactId>log4j</artifactId>
	  	<version>1.2.17</version>
	  </dependency>
	  <!--  测试包 -->
	  <dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
  	</dependency>
 </dependencies>
</project>

建立接口,这个接口是不需要实现的,Mybatis会自动实现

StudentMapper.java:

package com.wu.mapper;

import java.util.List;

import com.wu.pojo.Student;

public interface StudentMapper {
	void addStudent(Student studnet); // 增加学生
	void removeStudent(Long id); // 删除学生
	List<Student> getAllStudent(); // 查看学生
	void updateStudent(Student student); // 修改学生
}

建立持久化对象,该对象的属性名要与数据库表结构中的列明保持一致,否则就要对属性名起别名,而且一般提供get和set方法

Student.java:

package com.wu.pojo;

// 持久化对象
public class Student {
	private String name;
	private Long id;
	private Integer age;
	private String grade;
	public Student(String name,Long id,Integer age,String grade) {
		this.name = name;
		this.id = id;
		this.age = age;
		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;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
	@Override
	public String toString() {
		return "学生姓名:"+name+",学生学号:"+id+ ",学生年龄:"+age+",学生班级:"+grade;
	}
}

配置mybatis文件,主要有两个,还有一个用于日志的初始化配置,如下为相应的目录结构:
在这里插入图片描述
log4j.properties:

# Global logging configuration
log4j.rootLogger=DEBUG, cosole
# 控制台输出
log4j.appender.cosole=org.apache.log4j.ConsoleAppender
log4j.appender.cosole.layout=org.apache.log4j.PatternLayout
log4j.appender.cosole.layout.ConversionPattern=%5p [%t] - %m%n

config.xml:

 <?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>
	<typeAliases>
		<typeAlias type = "com.wu.pojo" alias = "student"/>
	</typeAliases>
	<!--  default引用environment的id,当前所使用的环境 -->
	<environments default="mysql">
		<!--  对不同数据库环境不同  -->
		<environment id="mysql">
			<!-- 使用原生JDBC事务 -->
				<transactionManager type="JDBC"></transactionManager>
				<!--  配置连接池 -->
				<dataSource type="POOLED">
					<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
					<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"/>
					<property name="username" value="root"/>
					<property name="password" value="root"/>
				</dataSource>
		</environment>
	</environments>
	<mappers>
		<!--  加载映射文件 -->
		<mapper resource = "mapper/studentMapper.xml"></mapper>
	</mappers>
</configuration>

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">
	<!--  
		id 方法名
		parameterType 传入类型
		resultType 返回类型
		#{}表示一个占位符
	 -->
	 <!--  这里注意接口中的方法名要与这里的id保持一致 -->
	 <!--  增添学生 -->
	 <insert id="addStudent" parameterType = "student">
	 	insert into student(name,id,age,grade) values(#{name},#{id},#{age},#{grade})
	 </insert>
	 <!--  删除学生 -->
	 <delete id="removeStudent" parameterType = "java.lang.Long">
	 	delete from student where id = #{id}
	 </delete>
	 <!-- 查看学生 -->
	<select id="getAllStudent" resultType = "student">
		select * from student
	</select>
	<!--  修改学生 -->
	<update id="updateStudent" parameterType = "student">
		update student set name  = #{name} , age = #{age} , grade = #{grade} where id = #{id}
	</update>
</mapper>
	

最后创建一个测试TestDemo类:

package com.wu.TestMybatis;

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.wu.pojo.Student;

public class TestDemo {
	@Test
	public void test() {
		InputStream config = null;
		try {
			config = Resources.getResourceAsStream("mybatis/config.xml");
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 使用工厂设计模式:根据配置文件生成SqlSession
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
		//System.out.println(factory);
		// 生产SqlSession
		SqlSession session = factory.openSession();
		// 增
		Student student = new Student("李四",20200101L,10,"二班");
		session.insert("com.wu.mapper.StudentMapper.addStudent",student);
		// 查
		System.out.println("增添后查看学生列表");
		List<Student> students = session.selectList("com.wu.mapper.StudentMapper.getAllStudent");
		for(Student s:students) {
			System.out.println(s);
		}
		System.out.println();
		// 删
		session.delete("com.wu.mapper.StudentMapper.removeStudent",20201227L);
		// 查
		System.out.println("删除后查看学生列表");
		students = session.selectList("com.wu.mapper.StudentMapper.getAllStudent");
		for(Student s:students) {
			System.out.println(s);
		}
		System.out.println();
		// 改
		student = new Student("炎黄",20200101L,10000,"一班");
		session.update("com.wu.mapper.StudentMapper.updateStudent",student);
		// 查
		System.out.println("修改后查看学生列表");
		students = session.selectList("com.wu.mapper.StudentMapper.getAllStudent");
		for(Student s:students) {
			System.out.println(s);
		}
		session.commit(); // 提交事物,否则不会影响数据库数据
		session.close();
	}
}

输出结果:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 500618423.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1dd6d4b7]
DEBUG [main] - ==>  Preparing: insert into student(name,id,age,grade) values(?,?,?,?) 
DEBUG [main] - ==> Parameters: 李四(String), 20200101(Long), 10(Integer), 二班(String)
DEBUG [main] - <==    Updates: 1
增添后查看学生列表
DEBUG [main] - ==>  Preparing: select * from student 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 3
学生姓名:李四,学生学号:20200101,学生年龄:10,学生班级:二班
学生姓名:王五,学生学号:20201227,学生年龄:20,学生班级:三班
学生姓名:张三,学生学号:20201228,学生年龄:20,学生班级:一班

DEBUG [main] - ==>  Preparing: delete from student where id = ? 
DEBUG [main] - ==> Parameters: 20201227(Long)
DEBUG [main] - <==    Updates: 1
删除后查看学生列表
DEBUG [main] - ==>  Preparing: select * from student 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 2
学生姓名:李四,学生学号:20200101,学生年龄:10,学生班级:二班
学生姓名:张三,学生学号:20201228,学生年龄:20,学生班级:一班

DEBUG [main] - ==>  Preparing: update student set name = ? , age = ? , grade = ? where id = ? 
DEBUG [main] - ==> Parameters: 炎黄(String), 10000(Integer), 一班(String), 20200101(Long)
DEBUG [main] - <==    Updates: 1
修改后查看学生列表
DEBUG [main] - ==>  Preparing: select * from student 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 2
学生姓名:炎黄,学生学号:20200101,学生年龄:10000,学生班级:一班
学生姓名:张三,学生学号:20201228,学生年龄:20,学生班级:一班
DEBUG [main] - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1dd6d4b7]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1dd6d4b7]
DEBUG [main] - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1dd6d4b7]
DEBUG [main] - Returned connection 500618423 to pool.

在这里插入图片描述

通过注解进一步简化操作,该方式可以不需要使用StudentMapper.xml映射文件,并且修改全局配置文件的Mappers属性,如下:

StudentMapper.java:

package com.wu.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.wu.pojo.Student;

public interface StudentMapper {
	@Insert("insert into student(name,id,age,grade) values(#{name},#{id},#{age},#{grade})")
	void addStudent(Student studnet); // 增加学生
	@Delete("delete from student where id = #{id}")
	void removeStudent(Long id); // 删除学生
	@Select("select * from student")
	List<Student> getAllStudent(); // 查看学生
	@Update("update student set name = #{name},age = #{age},grade = #{grade} where id = #{id}")
	void updateStudent(Student student); // 修改学生
}

config.xml:

<?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>
	<!--  别名  -->
	<typeAliases>
		<typeAlias type="com.wu.pojo.Student" alias = "student"/>
		<!--  pojo包下所有的类起别名 -->
		<!--  
			<package name = "com.wu.pojo" />
		 -->
	</typeAliases>
	<!--  default引用environment的id,当前所使用的环境 -->
	<environments default="mysql">
		<!--  对不同数据库环境不同  -->
		<environment id="mysql">
			<!-- 使用原生JDBC事务 -->
				<transactionManager type="JDBC"></transactionManager>
				<!--  配置连接池 -->
				<dataSource type="POOLED">
					<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
					<property name="url" value="jdbc:mysql://localhost:3306/jdbc_db?serverTimezone=UTC"/>
					<property name="username" value="root"/>
					<property name="password" value="root"/>
				</dataSource>
		</environment>
	</environments>
	<mappers>
		<!--  使用class属性加载映射文件 -->
		<mapper class = "com.wu.mapper.StudentMapper"></mapper>
	</mappers>
</configuration>

TestDemo.java:

package com.wu.TestMybatis;


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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

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

public class TestDemo {
	@Test
	public void test() {
		//1.读取配置文件
		InputStream config = null;
		try {
			config = Resources.getResourceAsStream("mybatis/config.xml");
		}catch(IOException e) {
			e.printStackTrace();
		}
		//2.创建SqlSessionFactory工厂
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
		//3.通过工厂创建生产SqlSession对象
		SqlSession session = factory.openSession();
		//4.通过SqlSession对象创建接口实例
		StudentMapper student = session.getMapper(StudentMapper.class);
		//5.通过代理对象执行方法
		
		//增
		Student stu = new Student("伏羲",20210104L,100000,"一班");
		student.addStudent(stu);
		//查
		List<Student> students = student.getAllStudent();
		for(Student s : students) {
			System.out.println(s);
		}
		System.out.println();
		//删
		student.removeStudent(20210101L);
		//查
		students = student.getAllStudent();
		for(Student s : students) {
			System.out.println(s);
		}
		System.out.println();
		//改
		stu = new Student("老子",20210102L,100000,"一班");
		student.updateStudent(stu);
		//查
		students = student.getAllStudent();
		for(Student s : students) {
			System.out.println(s);
		}
		session.commit(); // 事务提交
		//6.释放资源
		session.close();
		try {
			config.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}	
}

结果:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 288306765.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@112f364d]
DEBUG [main] - ==>  Preparing: insert into student(name,id,age,grade) values(?,?,?,?) 
DEBUG [main] - ==> Parameters: 伏羲(String), 20210104(Long), 100000(Integer), 一班(String)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: select * from student 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
学生姓名:张一,学生学号:20210101,学生年龄:20,学生班级:二班
学生姓名:张二,学生学号:20210102,学生年龄:20,学生班级:一班
学生姓名:张三,学生学号:20210103,学生年龄:20,学生班级:三班
学生姓名:伏羲,学生学号:20210104,学生年龄:100000,学生班级:一班

DEBUG [main] - ==>  Preparing: delete from student where id = ? 
DEBUG [main] - ==> Parameters: 20210101(Long)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: select * from student 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 3
学生姓名:张二,学生学号:20210102,学生年龄:20,学生班级:一班
学生姓名:张三,学生学号:20210103,学生年龄:20,学生班级:三班
学生姓名:伏羲,学生学号:20210104,学生年龄:100000,学生班级:一班

DEBUG [main] - ==>  Preparing: update student set name = ?,age = ?,grade = ? where id = ? 
DEBUG [main] - ==> Parameters: 老子(String), 100000(Integer), 一班(String), 20210102(Long)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: select * from student 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 3
学生姓名:老子,学生学号:20210102,学生年龄:100000,学生班级:一班
学生姓名:张三,学生学号:20210103,学生年龄:20,学生班级:三班
学生姓名:伏羲,学生学号:20210104,学生年龄:100000,学生班级:一班
DEBUG [main] - Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@112f364d]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@112f364d]
DEBUG [main] - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@112f364d]
DEBUG [main] - Returned connection 288306765 to pool.

实例:

实现分页功能

数据库test中student表结构:

在这里插入图片描述

新建Maven项目,选择war:

在这里插入图片描述
在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>pagedemo</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>

在pom.xml文件下导入相应的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.pagedemo</groupId>
  <artifactId>pagedemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
  	<dependency>
  		 <groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.5.2</version>
  	</dependency>
  	<dependency>
  		<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>8.0.22</version>
  	</dependency>
  	<dependency>
  		<groupId>log4j</groupId>
	  	<artifactId>log4j</artifactId>
	  	<version>1.2.17</version>
  	</dependency>
  	<dependency>
  		<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>
  </dependencies>
</project>

新建持久化对象Student.java:

package com.wu.pojo;

public class Student {
	private String name;
	private long id;
	private String grade;
	public Student(String name,long id,String grade) {
		this.name = name;
		this.id = id;
		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;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
}

新建接口StudentMapper.java:

package com.wu.mapper;

import java.util.List;

import com.wu.pojo.Student;

public interface StudentMapper {
	List<Student> findStudent(long pagestart , long pagesize); // 查找页数据
	long getCount(); // 获取学生总数
}

新建基础配置文件config.xml:

<?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>
	<typeAliases>
		<package name="com.wu.pojo"/>
	</typeAliases>
	<environments default="mysql">
		<environment id="mysql">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"/>
				<property name="username" value="root"/>
				<property name="password" value="root"/>
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="mapper/StudentMapper.xml"/>
	</mappers>
</configuration>

新建映射文件StdentMapper.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="findStudent" resultType = "Student" parameterType = "map">
		select * from student limit #{pageStart} , #{pageSize}
	</select>
	<select id="getCount" resultType ="long">
		select count(*) from student
	</select>
</mapper>

新建数据库操作文件Paging.java:

package com.wu.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.wu.pojo.Student;

public class Page {
	private List<Student> result;
	private int startpage; // 当前的页数
	private int pagesize; // 每页的记录个数
	private int totalpages; // 总页数
	private long total; //总记录个数
	public void paging() {
		InputStream config  = null;
		try {
			config = Resources.getResourceAsStream("mybatis/config.xml");
		}catch(IOException e) {
			e.printStackTrace();
		}
		SqlSessionFactory facatory  = new SqlSessionFactoryBuilder().build(config);
		SqlSession session = facatory.openSession();
		Map<String,Integer> map = new HashMap<String, Integer>();
		map.put("pageStart", startpage*pagesize);
		map.put("pageSize",pagesize);
		result = session.selectList("com.wu.mapper.StudentMapper.findStudent",map);
		total = session.selectOne("com.wu.mapper.StudentMapper.getCount"); // 获取学生总记录个数
		totalpages = (int) ( total%pagesize==0 ?  total/pagesize : total/pagesize+1);
		session.close();
	}
	public void setStartpage(int startpage) {
		this.startpage = startpage;
	}
	public List<Student> getResult(){
		return  result;
	}
	public int getStartPage() {
		return startpage;
	}
	public int getStartpage() {
		return startpage;
	}
	public  int getPagesize() {
		return pagesize;
	}
	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}
	public int getTotalpages() {
		return totalpages;
	}
	public void setTotalPages(int totalpages) {
		this.totalpages = totalpages;
	}
}

新建servlet类:

package com.wu.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

import com.wu.dao.Page;

@WebServlet(name = "pageServlet",value  = {"/page"})
public class Myservlet implements Servlet{
	private Page page = new Page();
	public void service(ServletRequest req, ServletResponse res) {
		String start = req.getParameter("pageNumber");
		String size = req.getParameter("pageSize");
		// 默认为第一页,每页的显示记录个数为十个
		int startpage = 0;
		int pagesize = 10; 
		if(start != null) {
			startpage = Integer.parseInt(start);
		}
		if(size != null) {
			pagesize = Integer.parseInt(size);
		}
		page.setStartpage(startpage);
		page.setPagesize(pagesize);
		page.paging(); // 处理每页学生数据、学生总数、总页数
		req.setAttribute("PageInfo",page);
		try {
			req.getRequestDispatcher("index.jsp").forward(req, res); // 转发
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}
	public String getServletInfo() {
		return null;
	}
	public void destroy() {	
	}
	public void init(ServletConfig config) throws ServletException {		
	}
	public ServletConfig getServletConfig() {
		return null;
	}
}

新建视图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" %>
<%@ page isELIgnored="false" %>

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>分页</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.PageInfo.result}" var = "s">
				<tr>
					<td>${pageScope.s.name} </td>
					<td>${pageScope.s.id}</td>
					<td>${pageScope.s.grade}</td>
				</tr>
			</c:forEach>
			<tr>
				<td>
					<c:if test ="${requestScope.PageInfo.startpage gt 0 }">
						<a href = "page?pageNumber=${requestScope.PageInfo.startpage-1}&pageSize=${requestScope.PageInfo.pagesize}">上一页</a>
					</c:if>
				</td>
				<td>当前页数:${requestScope.PageInfo.startpage+1}</td>
				<td>
				<c:if test= "${requestScope.PageInfo.startpage+1 lt requestScope.PageInfo.totalpages }">
					<a href = "page?pageNumber=${requestScope.PageInfo.startpage+1}&pageSize=${requestScope.PageInfo.pagesize}">下一页</a>
				</c:if>
				</td>
			</tr>
		</table>
	</div>
</body>
</html>

极其简陋的效果如下:

在这里插入图片描述
在这里插入图片描述

补充

log4j

log4j有五个级别的输出:
fatal(致命级别)>error(错误级别)>warn(警告)>info(普通信息)>debug(调试信息)
在log4j.properties文件文件中第一行控制输出级别

以上程序是包括所有信息的输出,原因是debug级别是最低的:

# 第一个参数控制输出等级控制输出,第二个参数控制输出目的地
log4j.rootLogger=error, cosole

session的select

session.selectList(String statement,Object parameter) // 返回值类型以resultType类型的列表
session.selectOne(String statement,Object parameter) // 返回一个对象
session.selectMap(String statement,String MapKey,Object parameter) // 返回值为map对象


如果DTD没有快捷键提示(可跳过… )

dtd文件读者可以从以下地址下载:
http://mybatis.org/dtd/mybatis-3-config.dtd
也可以从下载的mybatis-3.5.2-sources.jar包中找到builder目录下找到xml文件,可以发现自己想要的xml文件:

在这里插入图片描述
在这里插入图片描述
复制xml文件的路径,打开eclipse,点击window->preference->xml->xml catalog,点击Add:
在这里插入图片描述

在这里插入图片描述
同理,mapper约束也是如此

映射文件中查询id值,其中主键自增

一种情况:新增一条数据时,知道新增成功即可。
另一种情况:新增一条数据时,需要使用到这条新增数据的主键,而此时再将其查询出来会效率就会低下。

<!-- 这里KeyProperty为pojo对象的属性值,resultType为int返回值类型,order为操作(insert)前或后返回结果 -->
<selectKey keyProperty = "id" resultType = "int" order = "AFTER">
	select last_insert_id()
</selectKey>

非基本数据类型作为查询条件

查询条件是综合的查询条件,不仅包含用户查询条件,还包括其它的查询条件,这时可以使用包装对象传递输入参数。

如新建一个pojo,book.java:

public class book{
	private Student student;
	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}
}

通过book类查询学生信息,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="findStudentByBook" parameterType = "com.wu.pojo.Book" resultType ="com.wu.pojo.Student">
		select * from student where id = #{student.id}
	</select>
</mapper>

动态Sql标签

1.if标签

<if test = "条件"></if>

2.foreach标签

<foreach collection = "遍历集合" item = "遍历集合的单个元素" open = "语句开头" close = "语句结尾" sperator = "分隔符">
</foreach>

3.where标签

<where></where>
<!-- 只有标签内的一个以上的if条件满足时才插入where语句 -->

4.choose标签

<choose>
	<when test = "条件一"></when>
	<when test = "条件二"></when>
</choose>

5.trim标签

<trim prefix = "添加sql语句拼接的前缀" suffix = "添加sql语句拼接的后缀" prefixOverrides = "删除sql语句前面的关键字或者字符" suffixOverrides = "删除sql语句后面的关键字或者字符">
</trim>

6.set标签

<set></set>
<!-- 只有标签内的一个以上的if条件满足时才插入set语句 -->

resultMap的使用

ResultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。

<!-- 定义resultMap -->
<resultMap id = "studentMap" type = "com.wu.pojo.Student">
	<!--
		property表示pojo中的属性名
		column表示数据库表中的字段名
		javaType表示pojo对应属性的类型
		jdbcType表示数据库表中对应字段的类型
	-->
	<!-- 主键映射 -->
	<id property = "id" column = "id" javaType = "long" jdbcType = "VARCHAR"></id>
	<!-- 非主键映射 -->
	<result property = "studentName" column = "student_name" javaType = "string" jdbcType = "VARCHAR"></result>
	<result property = "studentAge" column = "student_age" javaType = "int" jdbcType = "NUMRIC"></result>
	<result property = "studentGrade" column = "student_grade" javaType = "string" jdbcType = "VARCHAR"></result>
</resultMap>
<!-- 使用resultMap -->
<select resultMap = "studentMap" id = "findAllStudent" >
	select * from student
</select>

关联表查询:

<!-- 书和学生的关系为:多对一 -->
<!-- 这里Book类中属性包含了Student类 -->
<resultMap id = "bookMap" type = "com.wu.pojo.Book">
	<id property = "bookId" column = "book_id"></id>
	<result property = "bookName" column = "book_name"></result>
	<association property = "sid" javaType = "com.wu.pojo.Student">
		<id property = "studentId" column = "student_id"></id>
		<result property = "studentName" column = "
		"student_name"></result>
	</association>
</resultMap>
<!-- resultMap的使用 -->
<select id = "getStudentNameByBookName" resultMap = "bookMap">
	select s.name,b.name,b.id from book b,student s
	where b.sid = s.id and b.book_name = #{bookName};
</select>
<!-- 学生和书的关系为:一对多 -->
<!-- 这里Book类中属性包含了Student类 -->
<resultMap id = "studentMap" type = "com.wu.pojo.Student">
	<id property = "studentId" column = "student_id"></id>
	<result property = "studentName" column = "student_name"></result>
	<collection property = "books" ofType = "com.wu.pojo.Book">
		<id property = "boolId" column = "book_id"></id>
		<result property = "bookName" column = "
		"book_name"></result>
	</collection>
</resultMap>
<!-- resultMap的使用 -->
<select id = "getStudentNameByBookName" resultMap = "studentMap" parameterType = "string">
	select s.name,b.name,b.id from book b,student s
	where b.sid = s.id and b.book_name = #{bookName};
</select>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值