Construction of jt project environment
First pass the user (user table to test whether the entire environment can run through)
1. Writing of the User entity class: (under the com.jt.manage.pojo package)
package com.jt.manage.pojo;
/**
* 用户的实体类
* @author thp
*
*/
public class User {
private Integer id; // id主键自增
private String name;
private Integer age;
private String sex;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2. Write the interface of the entity class:
package com.jt.manage.mapper;
import java.util.List;
import com.jt.manage.pojo.User;
/**
* 用户的mapper接口
* @author thp
*
*/
public interface UserMapper {
// 查询全部的用户信息
List<User> findAll();
}
3. Write the mapping file corresponding to the interface:
<?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.jt.manage.mapper.UserMapper">
<!-- 说明:编辑sql语句时,不要加;(分号),否则Oracle在解析时必定报错 -->
<select id="findAll" resultType="User">
select * from user
</select>
</mapper>
4. Business layer:
package com.jt.manage.service;
import java.util.List;
import com.jt.manage.pojo.User;
public interface UserService {
List<User> findAll();
}
package com.jt.manage.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.jt.manage.mapper.UserMapper;
import com.jt.manage.pojo.User;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
//查询所有用户信息
@Override
@Transactional(propagation=Propagation.REQUIRED) // 表示该方法需要添加事务
public List<User> findAll() {
return userMapper.findAll();
}
}
5. Control layer:
package com.jt.manage.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jt.manage.pojo.User;
import com.jt.manage.service.UserService;
/**
* 用户的controller
* @author thp
*
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public String findAll(Model model) { // 查询所有的用户 这个Model对象是spring帮你生成的
List<User> userList = userService.findAll();
// 需要将数据传递到页面中 将数据保存到request域中
model.addAttribute("userList", userList);
// 返回展现的页面
return "userList";
}
}
6. The returned jsp page:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>用户列表页面</title>
</head>
<body>
<table width="60%" algin="center" border="1">
<tr align="center">
<td colspan="5"><h2>用户信息</h2></td>
</tr>
<tr align="center">
<td>ID</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<!-- 通过jstl标签实现数据的循环遍历 -->
<c:forEach items="${userList }" var="user">
<tr align="center">
<td>${user.id }</td>
<td>${user.name }</td>
<td>${user.age }</td>
<td>${user.sex }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
7. Configuration file writing: key points
7.1: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="jt-manage" version="2.5">
<display-name>jt-manage</display-name>
<!-- 前端控制器
说明:如果没有配置<load-on-startup>的话,那么就只有等第一个请求来了
才去加载spring的配置文件,那么这样用户等待的时候会很长
-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/applicationContext*.xml</param-value>
</init-param>
<!-- 一启动服务器时,就加载配置文件 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--
/ 只匹配前缀型路径,目的是使用restFul传参方便
规则:/拦截前缀型的请求,同时拦截静态资源
但是放行.jsp等动态资源
/* 过滤器中使用/*, 全部的资源请求 ;
-->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!-- 禁止使用/* 静态资源不需要转发请求,静态资源是不经过controller转发的 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 全栈乱码的解决,主要解决post乱码问题 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 指定过滤器的字符集编码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!-- 注意这里是/* -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
7.2 Mybatis configuration file (need to set hump naming)
<?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>
<settings>
<!-- 开启驼峰自动映射 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
<!-- 二级缓存的总开关,被redis替代 -->
<setting name="cacheEnabled" value="false" />
</settings>
</configuration>
Reasons for enabling automatic hump mapping:
Mybatis的全局配置 mybatis的优点:可以实现自动的对象关系映射(orm)
映射问题:
如果字段和对象的属性不一致时,使用resultType是不能实现自动映射的(数据库中的字段经常会有_ [下划线])
那么就必须使用按照要求编辑resultMap
但是编辑resultMap的格式比较繁琐和负载,所以除非特殊的环境要求(多表关联查询)
否则很少使用resultMap
解决方案:使用驼峰规则映射
说明:如果mybatis开启了驼峰映射规则,那么可以将
column = user_name 和 User(username)
实现自动的映射
1.根据sql语句获取结果集对象,之后通过反射规则进行对象的赋值操作
2.将字段中的"_"去掉,动态匹配对象总的属性,进行赋值操作
3.驼峰映射的现象; column = user_name ~~~userName | userNAME|username...
只要字母相同即可,都可以进行匹配
通过resultMap来手动映射:(映射实体类属性跟数据库中表的字段不一样的)
<select id="findAll" resultMap="userRM">
select * from user
</select>
<resultMap type="User" id="userRM">
<id column="user_id" property="userId"/>
<result column="user_name" property="username"/>
</resultMap>
7.3 springMVC configuration file: (applicationContext-mvc.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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 启用mvc注解扫描 -->
<mvc:annotation-driven />
<!-- 配置内部资源视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
7.4 Spring's core configuration file: (applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置包扫描 注意要有common里面的 -->
<context:component-scan base-package="com.jt" />
<!-- 加载外部的配置文件 -->
<bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/properties/jdbc.properties</value>
</list>
</property>
</bean>
<!-- 说明:
1.该标签可以导入外部的properties,但是只能导入一个或者一类文件
jdbc*.properties 表示导入以jdbc开头的配置文件
*.properties 表示所有的配置文件
如果想要导入几个指定的配置文件 就得用 PropertyPlaceholderConfigurer
-->
<!-- <context:property-placeholder location=""/> -->
<!-- 配置连接池 -->
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<!-- 数据库驱动 -->
<property name="driverClass" value="${jdbc.driver}" />
<!-- 相应驱动的jdbcUrl -->
<property name="jdbcUrl" value="${jdbc.url}" />
<!-- 数据库的用户名 -->
<property name="username" value="${jdbc.username}" />
<!-- 数据库的密码 -->
<property name="password" value="${jdbc.password}" />
<!-- 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!-- 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 -->
<property name="idleMaxAge" value="30" />
<!-- 每个分区最大的连接数 -->
<property name="maxConnectionsPerPartition" value="150" />
<!-- 每个分区最小的连接数 -->
<property name="minConnectionsPerPartition" value="5" />
</bean>
<!--
引入声明式的事务控制
1.注解形式 开启事务的注解 需要一个一个开启
@Transactional(propagation=Propagation.REQUIRED)
2.配置文件的方式 ~~~ 核心的思想就是AOP ~~~ 代理
通知+切入点(切入点表达式)
-->
<!-- 配置事务 -->
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 通知 -->
<!-- 3.1配置声明式事务处理的通知
transactionManager : 表示事务管理器 需要控制事务需要提交还是回滚
如果事务管理器的id是默认的,则可以省略
事务的管理策略: 1.增/删/改 需要事务的控制
2.查询不需要事务,配置只读操作
3.其他方法 不需要添加事务,配置只读操作
事务的传播属性:
propagation="REQUIRED" 必须添加事务
propagation="SUPPORTS" 事务支持的,事务可有可无 默认条件下是没有事务 原来有事务,就也加上事务
propagation="NEVER" 不使用事务
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 定义数据库的读的方法 -->
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
<!-- 更新数据库操作 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<!-- 其他方法 -->
<tx:method name="*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<!-- 3.2配置AOP的切面
proxy-target-class="false" 采用默认的代理的方式 接口-jdk 没接口 -cglib
proxy-target-class="true" 强制使用cglib实现动态代理
一般采用spring中默认的策略
-->
<aop:config>
<!-- 配置切入点 -->
<aop:pointcut expression="execution(* com.jt.manage.service..*.*(..))" id="pc"/>
<!-- 将切入点与通知加在一起 组成切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/>
</aop:config>
</beans>
7.5 Spring integrates the configuration file of mybatis: (applicationContext-mybatis.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- spring整合mybaits
整合步骤:
1.spring管理sqlSessionFactoryBean
2.配置数据源
3.添加核心配置文件
4.添加映射文件
5.配置别名包
6.为mapper文件生产代理对象(JDK代理)
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 添加mybatis的核心配置文件 -->
<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"/>
<!-- 添加映射文件 -->
<property name="mapperLocations" value="classpath:/mybatis/mapper/*.xml"/>
<!-- 配置别名 -->
<property name="typeAliasesPackage" value="com.jt.manage.pojo"/>
</bean>
<!-- 为mapper接口生成代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jt.manage.mapper"></property>
</bean>
</beans>