标签:9.1 alias 1.2 item ram enc doctype jdbc cal
一、搭建开发环境
1.使用maven创建web项目
2.编辑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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>mybatis_spring_test</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis_spring_test Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope> -->
</dependency>
<!-- 添加Spring-core包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 添加spring-context包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- 添加spring-tx包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<!-- 添加spring-jdbc包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<!-- 为了方便进行单元测试,添加spring-test包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
<!--添加spring-web包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--添加aspectjweaver包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!-- 添加mybatis的核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 添加mybatis与Spring整合的核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 添加servlet3.0核心包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>mybatis_spring_test</finalName>
<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
3.为项目手动添加src/main/java、src/test/resources、src/test/java这三个source folder,至此,项目搭建的工作全部完成。
二、创建数据库和表
三、编写相关代码
1.dao类
public interface TeacherMapper {
int deleteByPrimaryKey(String tid);
int insert(Teacher record);
Teacher selectByPrimaryKey(int key);
int updateByPrimaryKey(Teacher record);
}
TeacherMapper是一个接口,里面定义了操作ksl_teacher表的增删改查的方法。
2.实体类
public class Teacher implements Serializable{
private int id;// id --> tid
private String name;// name --> tname
public Teacher(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Teacher() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Teacher [id=" + id + ", name=" + name + "]";
}
}
3.SQL映射文件
<?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.dao.TeacherMapper">
<select id="selectByPrimaryKey" parameterType="int"
resultType="com.domain.Teacher">
select tid id, tname name from ksl_teacher where tid=#{key}
</select>
<update id="updateByPrimaryKey" parameterType="com.domain.Teacher">
update ksl_teacher
<set>
tname=#{name}
</set>
where tid=#{id}
</update>
<delete id="deleteByPrimaryKey" parameterType="int">
delete from ksl_teacher where tid=#{tid}
</delete>
<insert id="insert" parameterType="com.domain.Teacher">
insert into ksl_teacher(tname) values (#{name, jdbcType=VARCHAR})
</insert>
</mapper>
-----------------------
teacherMapping.xml这个文件的内容是编写操作ksl_teacher表的SQL语句,需要注意:
1.teacherMapping.xml的<mapper>标签的namespace必须是TeacherMapper接口的全类名,即<mapper namespace="com.dao.TeacherMapper">;
2.TeacherMapping.xml的定义操作数据库的<select><delete><update><insert>这些标签的id属性值必须和TeacherMapper接口定义的方法名一致。
之所以有上述的两点要求,就是为了能够让MyBatis可以根据TeacherMapper接口和TeacherMapping.xml文件去自动实现TeacherMapper接口中定义的相关方法,这样我们就不再需要针对TeacherMapper接口去编写具体的实现代码了。
四、Spring与MyBatis整合
1.编写相关配置文件(以下都在src/main/resources目录下)
dbconfig.properties:
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/mysql
jdbc_username=root
jdbc_password=######
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">
<!-- 引入dbconfig.properties属性文件 -->
<context:property-placeholder location="classpath:dbconfig.properties" />
<!-- 自动扫描(自动注入),扫描com.service这个包以及它的子包的所有使用@Service注解标注的类 -->
<context:component-scan base-package="com.service" />
</beans>
spring-mybatis.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!--1 配置C3P0数据源 -->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!--驱动类名 -->
<property name="driverClass" value="${driverClassName}" />
<!-- url -->
<property name="jdbcUrl" value="${jdbc_url}" />
<!-- 用户名 -->
<property name="user" value="${jdbc_username}" />
<!-- 密码 -->
<property name="password" value="${jdbc_password}" />
<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
<property name="acquireIncrement" value="5"></property>
<!-- 初始连接池大小 -->
<property name="initialPoolSize" value="10"></property>
<!-- 连接池中连接最小个数 -->
<property name="minPoolSize" value="5"></property>
<!-- 连接池中连接最大个数 -->
<property name="maxPoolSize" value="20"></property>
</bean>
<!--2 会话工厂bean sqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="datasource"></property>
<!-- 别名 -->
<!-- <property name="typeAliasesPackage" value="com.domain"></property> -->
<!-- sql映射文件路径 -->
<property name="mapperLocations" value="classpath*:com/mapping/*Mapping.xml"></property>
</bean>
<!--3 自动扫描对象关系映射 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 指定要自动扫描接口的基础包,实现接口 -->
<property name="basePackage" value="com.dao"></property>
</bean>
<!--4 声明式事务管理 -->
<!--定义事物管理器,由spring管理事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!--支持注解驱动的事务管理,指定事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--5 容器自动扫描IOC组件 -->
<context:component-scan base-package="com.dao"></context:component-scan>
<!--6 aspectj支持自动代理实现AOP功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
2.进行单元测试
首先,在src/main/java目录下创建一个com.service包,然后在此包下创建一个TeacherServiceI接口:
public interface TeacherServiceI {
void addTeacher(Teacher record);
Teacher selectById(int tid);
}
然后,在com.service.impl包下创建一个针对此接口的实现类:
/*
* 使用@Service注解将TeacherServiceImpl标注为一个Service
* 其id为teacherService
*/
@Service("teacherService")
public class TeacherServiceImpl implements TeacherServiceI {
/*
* 使用@Autowired变量标注teacherMapper变量,
* 当需要使用teacherMapper时,Spring就会自动注入
*/
@Autowired
private TeacherMapper teacherMapper;
public void addTeacher(Teacher record) {
teacherMapper.insert(record);
}
public Teacher selectById(int tid) {
return teacherMapper.selectByPrimaryKey(tid);
}
}
在src/test/java目录下编写单元测试类,新建一个com.test包,然后创建MyBatisTest类:
public class MyBatisTest {
private TeacherServiceI teacherService;
/*
* Before方法在所有测试方法之前执行,并且只执行一次
* 所有做Junit单元测试时一些初始化工作可以在这个方法里进行
* 比如在Before方法里初始化ApplicationContext与TeacherService
*/
@Before
public void before() {
//使用spring.xml和spring-mybatis.xml这两个配置文件创建Spring上下文
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml", "spring-mybatis.xml"});
//从Spring的容器中根据Bean的id取出teacherService
teacherService = (TeacherServiceI) ac.getBean("teacherService");
}
@Test
public void testAddTeacher() {
Teacher t = new Teacher();
t.setName("nigemaiti");
teacherService.addTeacher(t);
}
}
最终,执行了maven clean--maven install之后,即可正常运行测试。
----------------------------------
五、在web服务器中进行测试
1.编辑web.xml,添加Spring监听器配置项:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<description>Spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- ContextLoaderListener初始化Spring上下文时需要使用到的contextConfigLocation参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置spring.xml和spring-mybatis.xml这两个配置文件的位置,固定写法 -->
<param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
</web-app>
2.在TeacherMapper接口中添加一个获取表格所有信息的方法:
List<Teacher> getAllTeachers();
3.在TeacherMapping.xml中编写getAllTeachers:
<resultMap type="com.domain.Teacher" id="BaseResultMap">
<id column="tid" property="id" jdbcType="INTEGER" />
<result column="tname" property="name" jdbcType="VARCHAR" />
</resultMap>
<select id="getAllTeachers" resultMap="BaseResultMap">
select tid id, tname name from ksl_teacher
</select>
4.更新TeacherServiceI:
List<Teacher> getAllTeachers();
5.更新TeacherServiceImpl:
public List<Teacher> getAllTeachers() {
return teacherMapper.getAllTeachers();
}
6.在src/main/java目录下创建一个com.web.controller包,然后在包中创建TeacherServlet:
/*
* @WebServlet是Servlet3.0提供的注解,目的是将一个继承了HttpServlet的普通Java类标注为一个Servlet
* TeacherServlet在使用了@WebServlet标注后,就不需要在web.xml中配置了
*/
@WebServlet("/teacherServlet")
public class TeacherServlet extends HttpServlet {
// 处理业务逻辑的TeacherServiceI
private TeacherServiceI teacherService;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Teacher> list = teacherService.getAllTeachers();
request.setAttribute("listTeachers", list);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
public void init() {
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
teacherService = (TeacherServiceI) ac.getBean("teacherService");
}
}
7.编辑index.jsp,用于展示查询到的用户信息:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%--加入该标签手动开启el功能--%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<title>显示教师信息</title>
<style type="text/css">
table,td{
border: 1px solid;
border-collapse: collapse;
}
</style>
</head>
<body>
<table>
<tr>
<td>教师ID</td>
<td>教师名</td>
</tr>
<%--遍历listTeachers集合中的Teacher对象 --%>
<c:forEach var="teacher" items="${listTeachers}">
<tr>
<td>${teacher.id}</td>
<td>${teacher.name}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
8.执行maven clean-maven install,然后将项目部署到Tomcat服务器中运行,最后输入地址
http://localhost:9080/mybatis_spring_test/teacherServlet访问。
标签:9.1 alias 1.2 item ram enc doctype jdbc cal
原文地址:https://www.cnblogs.com/yuanfei1110111/p/10352574.html