spring整合ORM框架
注:本文篇幅有点长,总字数3万多,所以建议各位下载源码学习。(如需要请收藏!转载请声明来源,谢谢!)代码下载:https://gitee.com/hong99/spring/issues...
注:本文篇幅有点长,总字数3万多,所以建议各位下载源码学习。(如需要请收藏!转载请声明来源,谢谢!)
代码下载:https://gitee.com/hong99/spring/issues/I1N1DF
主要内容:
版本:spring:4.x
日志:log4j2
整合 :
spring+springmvc+jdbcTemplate
spring+springmvc+hibernate
spring+springmvc+mybatis
spring+springmvc+mybatis_plus
已经实现了基本的功能,可以在此基础上继续完善!如有疑问,请私聊或留言,谢谢!
什么是ORM框架?
ORM全称是:Object Relation Mapping 简称:对象关系映射。
参考文章:https://baike.baidu.com/item/ORM%E6%A1%86%E6%9E%B6/15541111?fr=aladdin
解决了什么问题?
解决了面向对象与关系数据库存在的互不匹配的现象的技术。
个人理解:就如家里的插座,统一了电器入口标准,使我们家里的电器直接插上去就可以用了。
优缺点?
优点:
提升开发效率,降低系统维护成本;
可移值、拓展性更高;
缺点:
一定程序牺牲了系统性能;
联表查询,实现复杂...
ORM框架有哪些?
mybatis
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
官网:https://mybatis.org/mybatis-3/zh/index.html
mybatis-plus
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网:https://mybatis.plus/guide/#%E7%89%B9%E6%80%A7
hibernate
Hibernate是一种Java语言下的对象关系映射(ORM)解决方案。它是使用GNU宽通用公共许可证发行的自由、开源的软件。它为面向对象的领域模型到传统的关系型数据库的映射,提供了一个使用方便的持久化框架。
官网:https://hibernate.org/
其它:这里就不一一列出,只列流行和常用的。
实现源码
spring+springmvc+jdbcTemplate
项目结构
maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring</artifactId>
<groupId>com.hong</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.hong.spring</groupId>
<artifactId>spring_jdbc</artifactId>
<properties>
<logback.version>1.2.3</logback.version>
<over-slf4j.version>1.7.25</over-slf4j.version>
<spring.version>4.3.11.RELEASE</spring.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<slf4j.version>1.7.12</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!--引入连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!--引入AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--该包的主要作用是会去自动查找合适的日志记录框架进行记录-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--引入日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
<optional>true</optional>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<build>
<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>
application.properties
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
applicationContext-jdbc.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启注解 -->
<context:annotation-config />
<!--开启注解事务-->
<tx:annotation-driven />
<!--放行静态资源-->
<mvc:default-servlet-handler />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- 后缀 -->
<property name="suffix" value=".html" />
<property name="contentType" value="text/html"/>
</bean>
<!--开启mvc注解事务-->
<!-- 定义注解驱动 -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- 设置支持中文 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 配置组件扫描 -->
<context:component-scan base-package="com.hong.spring"></context:component-scan>
<!--加载配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 基础配置 -->
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 关键配置 -->
<!-- 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 -->
<property name="initialSize" value="3" />
<!-- 最小连接池数量 -->
<property name="minIdle" value="2" />
<!-- 最大连接池数量 -->
<property name="maxActive" value="15" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
<!-- 性能配置 -->
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 其他配置 -->
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
执行validationQuery检测连接是否有效。-->
<property name="testWhileIdle" value="true" />
<!-- 这里建议配置为TRUE,防止取到的连接不可用 ,申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
<property name="testOnBorrow" value="true" />
<!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->
<property name="testOnReturn" value="false" />
</bean>
<!-- 配置JdbcTempalte -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg index="0" ref="dataSource" /> <!-- ref属性值是DataSource的id -->
</bean>
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
jdbc.properties
config.properties:
#数据库驱动
jdbc.driver=com.mysql.jdbc.Driver
#数据库连接url
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
#数据库用户名
jdbc.user=root
#数据库密码
jdbc.password=123456
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="INFO">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout pattern="%d{yyyy.MM.dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
<SizeBasedTriggeringPolicy size="5 MB"/>
</RollingFile>
</appenders>
<loggers>
<root level="DEBUG">
<appender-ref ref="Console"/>
<appender-ref ref="RollingFile"/>
</root>
</loggers>
</configuration>
logging.properties
org.apache.catalina.core.ContainerBase.[Catalina].level=INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers=java.util.logging.ConsoleHandler
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ../logs
org.apache.juli.FileHandler.prefix = error-debug.
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
具体代码
com.hong.spring.utils.DataResponse
package com.hong.spring.utils;
import java.io.Serializable;
/**
*
* 功能描述:返回工具类
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:15
*/
public class DataResponse<T> implements Serializable {
/** 默认为0*/
public static final Integer SUCCESS = 0;
/** 错误标识*/
public static final Integer FAIL = 1;
/** 编码*/
private int code;
/** 返回消息*/
private String msg;
/** 数据*/
private T data;
/** 总条数*/
private int total;
public DataResponse() {
this.code = SUCCESS;
}
public DataResponse(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public DataResponse(Integer code, String msg, Boolean isNeedTry) {
this.code = code;
this.msg = msg;
}
public DataResponse(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public DataResponse(Integer code, String msg, T data, Boolean isNeedTry) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static DataResponse BuildFailResponse() {
return BuildFailResponse((String)null);
}
public static DataResponse BuildFailResponse(String msg) {
return BuildFailResponse(msg, (Object)null);
}
public static <T> DataResponse BuildFailResponse(String msg, T data) {
DataResponse rtv = new DataResponse();
rtv.setCode(FAIL);
rtv.setMsg(msg);
rtv.setData(data);
return rtv;
}
public static DataResponse BuildSuccessResponse() {
return BuildSuccessResponse((Object)null);
}
public static <T> DataResponse BuildSuccessResponse(T data) {
DataResponse rtv = new DataResponse();
rtv.setCode(SUCCESS);
rtv.setData(data);
return rtv;
}
public static <T> DataResponse BuildSuccessResponse(T data,int total) {
DataResponse rtv = new DataResponse();
rtv.setCode(SUCCESS);
rtv.setTotal(total);
rtv.setData(data);
return rtv;
}
public Integer getCode() {
return this.code;
}
public void setCode(Integer code) {
this.code = code;
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotal() {
return total;
}
}
package com.hong.spring.entity;
import java.io.Serializable;
/**
* @Auther: csh
* @Date: 2020/8/3 18:12
* @Description:用户实体
*/
public class User implements Serializable {
private Integer id;
private String username;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
}
public User(Integer id, String username, Integer age) {
this.id = id;
this.username = username;
this.age = age;
}
}
package com.hong.spring.entity;
import java.io.Serializable;
/**
* @Auther: csh
* @Date: 2020/8/4 18:27
* @Description:角色
*/
public class UserRole implements Serializable {
//主键
private Integer id;
// 用户id
private Integer userId;
//角色id
private Integer roleId;
public UserRole(Integer id, Integer userId, Integer roleId) {
this.id = id;
this.userId = userId;
this.roleId = roleId;
}
public UserRole() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
}
package com.hong.spring.dao;
import com.hong.spring.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:04
* @Description:用户dao层
*/
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
*
* 功能描述:查询总条数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:31
*/
public List<User> findAllUserList(){
String sql = "select id,user_name as username,age from user";
List<User> userList = jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<User>(User.class));
return userList;
}
/**
*
* 功能描述:获取总数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
public int findAllTotal(){
String sql = "select count(1) from user";
return jdbcTemplate.queryForObject(sql,Integer.class);
}
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
public int update(User user){
if(user==null || user.getId()==null){
return 0;
}
String sql = "update user set user_name =?,age=? where id=?";
RowMapper<User> rowMapper = new BeanPropertyRowMapper(User.class);
return jdbcTemplate.update(sql,user.getUsername(),user.getAge(),user.getId());
}
public int save(User user){
if(user==null){
return 0;
}
String sql = "insert into user(user_name,age) values(?,?)";
return jdbcTemplate.update(sql,user.getUsername(),user.getAge());
}
public User findById(int id) {
String sql = "select * from user where id=?";
return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class), id);
}
}
package com.hong.spring.service;
import com.hong.spring.entity.User;
import com.hong.spring.utils.DataResponse;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:07
* @Description:用户服务层
*/
public interface IUserService {
/**
*
* 功能描述:查询全部
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<List<User>> findByAll();
/**
*
* 功能描述:添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> save(User user);
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> update(User user);
/**
*
* 功能描述:通过id查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:42
*/
DataResponse<User> findById(int i);
}
package com.hong.spring.service.impl;
import com.hong.spring.dao.UserDao;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:16
* @Description:用户实现
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserDao userDao;
public DataResponse<List<User>> findByAll() {
List <User> allUserList = userDao.findAllUserList();
int allTotal = userDao.findAllTotal();
return DataResponse.BuildSuccessResponse(allUserList,allTotal);
}
@Transactional
public DataResponse <Boolean> save(User user) {
if(null==user){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int save = userDao.save(user);
return DataResponse.BuildSuccessResponse(save>0?true:false);
}
@Transactional
public DataResponse <Boolean> update(User user) {
if(null==user || user.getId()==null){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int update = userDao.update(user);
return DataResponse.BuildSuccessResponse(update>0?true:false);
}
public DataResponse <User> findById(int i) {
User byId = userDao.findById(i);
return DataResponse.BuildSuccessResponse(byId);
}
}
package com.hong.spring.controller;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Auther: csh
* @Date: 2020/8/18 17:36
* @Description:
*/
@Controller
@RequestMapping("/")
@Log4j2
public class IndexController {
@RequestMapping
public String index(){
log.info("首页");
return "index";
}
}
package com.hong.spring.controller;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 16:11
* @Description:
*/
@RestController
@RequestMapping("/user/")
@Log4j2
public class UserController extends BaseController {
@Autowired
private IUserService userService;
@RequestMapping("findByAll")
public DataResponse<List<User>> findByAll(){
try {
return userService.findByAll();
} catch (Exception e){
log.error("查询出错{}",e);
}
return DataResponse.BuildFailResponse("查询出错!");
}
}
junit测试
package com.hong.test;
import com.alibaba.fastjson.JSONObject;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:23
* @Description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-jdbc.xml")
@Slf4j
public class UserTest {
@Autowired
private IUserService userService;
@Test
public void save(){
User user = new User();
user.setAge(11);
user.setUsername("hong");
DataResponse <Boolean> save = userService.save(user);
System.out.println(JSONObject.toJSONString(save));
}
@Transactional
@Test
@Rollback(value = false)
public void update(){
DataResponse <User> byId = userService.findById(45);
User data = byId.getData();
if(data!=null){
data.setUsername("测试32");
data.setAge(100);
userService.update(data);
// throw new RuntimeException();
}
}
@Test
public void findAll(){
DataResponse <List <User>> byAll = userService.findByAll();
System.out.println(JSONObject.toJSONString(byAll));
}
@Test
public void findById(){
DataResponse <User> byId = userService.findById(1);
System.out.println(JSONObject.toJSONString(byId));
}
}
WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>jdbc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-jdbc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>jdbc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/pages/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
123456789
</body>
</html>
测试结果
save
21:08:30.610 [main] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
21:08:30.672 [main] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
{"code":0,"data":true,"total":0}
21:08:30.734 [Thread-1] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} closing ...
21:08:30.735 [Thread-1] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt exit cache
21:08:30.736 [Thread-1] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} closed
update
09:59:15.889 [main] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
09:59:15.896 [main] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
09:59:15.903 [main] INFO com.hong.test.UserTest - update结果:{"code":0,"data":true,"total":0}
findAll
{"code":0,"data":[{"age":100,"id":1,"username":"333"},{"age":100,"id":2,"username":"测试32"},{"age":100,"id":3,"username":"updateHong"},{"age":0,"id":4,"username":"hong0"},{"age":1,"id":5,"username":"hong1"},{"age":2,"id":6,"username":"hong2"},{"age":3,"id":7,"username":"hong3"},{"age":4,"id":8,"username":"hong4"},{"age":5,"id":9,"username":"hong5"},{"age":6,"id":10,"username":"hong6"},{"age":7,"id":11,"username":"hong7"},{"age":8,"id":12,"username":"hong8"},{"age":9,"id":13,"username":"hong9"},{"age":200,"id":14,"username":"mybatisPlus"},{"age":0,"id":15,"username":"mybatisPlus0"},{"age":1,"id":16,"username":"mybatisPlus1"},{"age":2,"id":17,"username":"mybatisPlus2"},{"age":3,"id":18,"username":"mybatisPlus3"},{"age":4,"id":19,"username":"mybatisPlus4"},{"age":5,"id":20,"username":"mybatisPlus5"},{"age":6,"id":21,"username":"mybatisPlus6"},{"age":7,"id":22,"username":"mybatisPlus7"},{"age":8,"id":23,"username":"mybatisPlus8"},{"age":9,"id":24,"username":"mybatisPlus9"},{"age":10,"id":25,"username":"mybatisPlus10"},{"age":11,"id":26,"username":"mybatisPlus11"},{"age":12,"id":27,"username":"mybatisPlus12"},{"age":13,"id":28,"username":"mybatisPlus13"},{"age":14,"id":29,"username":"mybatisPlus14"},{"age":15,"id":30,"username":"mybatisPlus15"},{"age":16,"id":31,"username":"mybatisPlus16"},{"age":17,"id":32,"username":"mybatisPlus17"},{"age":18,"id":33,"username":"mybatisPlus18"},{"age":19,"id":34,"username":"mybatisPlus19"},{"age":20,"id":35,"username":"mybatisPlus20"},{"age":21,"id":36,"username":"mybatisPlus21"},{"age":22,"id":37,"username":"mybatisPlus22"},{"age":23,"id":38,"username":"mybatisPlus23"},{"age":24,"id":39,"username":"mybatisPlus24"},{"age":25,"id":40,"username":"mybatisPlus25"},{"age":26,"id":41,"username":"mybatisPlus26"},{"age":27,"id":42,"username":"mybatisPlus27"},{"age":28,"id":43,"username":"mybatisPlus28"},{"age":29,"id":44,"username":"update44"},{"age":100,"id":45,"username":"测试32"}],"total":45}
findById
{"code":0,"data":{"age":100,"id":45},"total":0}
tomcat配置
[2020-08-25 10:43:40,113] Artifact spring_jdbc:Web exploded: Artifact is deployed successfully
[2020-08-25 10:43:40,113] Artifact spring_jdbc:Web exploded: Deploy took 5,382 milliseconds
10:43:40.436 [http-nio-8080-exec-1] INFO com.hong.spring.controller.IndexController - 首页
10:43:40.496 [http-nio-8080-exec-2] INFO com.hong.spring.controller.IndexController - 首页
10:43:40.824 [http-nio-8080-exec-4] INFO com.hong.spring.controller.IndexController - 首页
[2020-08-25 10:43:40,113] Artifact spring_jdbc:Web exploded: Artifact is deployed successfully
[2020-08-25 10:43:40,113] Artifact spring_jdbc:Web exploded: Deploy took 5,382 milliseconds
10:43:40.436 [http-nio-8080-exec-1] INFO com.hong.spring.controller.IndexController - 首页
10:43:40.496 [http-nio-8080-exec-2] INFO com.hong.spring.controller.IndexController - 首页
10:43:40.824 [http-nio-8080-exec-4] INFO com.hong.spring.controller.IndexController - 首页
spring+jdbctempalce end!
spring+springmvc+hibernate
项目结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring</artifactId>
<groupId>com.hong</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.hong.spring</groupId>
<artifactId>spring_hibernate</artifactId>
<properties>
<logback.version>1.2.3</logback.version>
<over-slf4j.version>1.7.25</over-slf4j.version>
<spring.version>4.3.11.RELEASE</spring.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<slf4j.version>1.7.12</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-jdbc</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!--引入连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!--引入AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--该包的主要作用是会去自动查找合适的日志记录框架进行记录-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--引入日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
<optional>true</optional>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<!--引入hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!--引入orm-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<build>
<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>
applicationContext-hibernate.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启注解 -->
<context:annotation-config />
<!--开启注解事务-->
<tx:annotation-driven />
<!--放行静态资源-->
<mvc:default-servlet-handler />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- 后缀 -->
<property name="suffix" value=".html" />
<property name="contentType" value="text/html"/>
</bean>
<!--开启mvc注解事务-->
<!-- 定义注解驱动 -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- 设置支持中文 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 配置组件扫描 -->
<context:component-scan base-package="com.hong.spring"></context:component-scan>
<!--加载配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 基础配置 -->
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 关键配置 -->
<!-- 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 -->
<property name="initialSize" value="3" />
<!-- 最小连接池数量 -->
<property name="minIdle" value="2" />
<!-- 最大连接池数量 -->
<property name="maxActive" value="15" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
<!-- 性能配置 -->
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 其他配置 -->
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
执行validationQuery检测连接是否有效。-->
<property name="testWhileIdle" value="true" />
<!-- 这里建议配置为TRUE,防止取到的连接不可用 ,申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
<property name="testOnBorrow" value="true" />
<!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->
<property name="testOnReturn" value="false" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:mappingDirectoryLocations="classpath:/com/hong/spring/entity">
<!-- 配置Hibernate的属性配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.hong.spring.entity</value>
</list>
</property>
</bean>
<!--事务管理器-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置hibernateTemplate -->
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate4.HibernateTemplate"
p:sessionFactory-ref="sessionFactory"/>
</beans>
其他配置与以上一样~
com.hong.spring.entity.User
package com.hong.spring.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
/**
* @Auther: csh
* @Date: 2020/8/3 18:12
* @Description:用户实体
*/
@Data
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "user_name")
private String username;
@Column(name = "age")
private Integer age;
}
com.hong.spring.dao.UserDao
package com.hong.spring.dao;
import com.hong.spring.entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:04
* @Description:用户dao层
*/
@Repository
public class UserDao {
@Autowired
private HibernateTemplate hibernateTemplate;
/**
*
* 功能描述:查询总条数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:31
*/
public List<User> findAllUserList(){
return (List <User>) hibernateTemplate.findByExample(new User());
}
/**
*
* 功能描述:获取总数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
public int findAllTotal(){
String hql = "select count(*) from User as user";
Long count = (Long) hibernateTemplate.find(hql).listIterator().next();
return count.intValue();
}
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
public int update(User user){
if(user==null || user.getId()==null){
return 0;
}
hibernateTemplate.update(user);
return 1;
}
public int save(User user){
if(user==null){
return 0;
}
Serializable save = hibernateTemplate.save(user);
return save!=null?1:0;
}
public User findById(int id) {
User user = hibernateTemplate.get(User.class, id);
return user;
}
}
com.hong.spring.service.IUserService
package com.hong.spring.service;
import com.hong.spring.entity.User;
import com.hong.spring.utils.DataResponse;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:07
* @Description:用户服务层
*/
public interface IUserService {
/**
*
* 功能描述:查询全部
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<List<User>> findByAll();
/**
*
* 功能描述:添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> save(User user);
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> update(User user);
/**
*
* 功能描述:通过id查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:42
*/
DataResponse<User> findById(int i);
}
com.hong.spring.service.impl.UserServiceImpl
package com.hong.spring.service.impl;
import com.hong.spring.dao.UserDao;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:16
* @Description:用户实现
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserDao userDao;
public DataResponse<List<User>> findByAll() {
List <User> allUserList = userDao.findAllUserList();
int allTotal = userDao.findAllTotal();
return DataResponse.BuildSuccessResponse(allUserList,allTotal);
}
@Transactional
public DataResponse <Boolean> save(User user) {
if(null==user){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int save = userDao.save(user);
return DataResponse.BuildSuccessResponse(save>0?true:false);
}
@Transactional
public DataResponse <Boolean> update(User user) {
if(null==user || user.getId()==null){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int update = userDao.update(user);
return DataResponse.BuildSuccessResponse(update>0?true:false);
}
public DataResponse <User> findById(int i) {
User byId = userDao.findById(i);
return DataResponse.BuildSuccessResponse(byId);
}
}
com.hong.spring.controller.IndexController
package com.hong.spring.controller;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Auther: csh
* @Date: 2020/8/18 17:36
* @Description:
*/
@Controller
@RequestMapping("/")
@Log4j2
public class IndexController {
@RequestMapping
public String index(){
log.info("首页");
return "index";
}
}
com.hong.spring.controller.UserController
package com.hong.spring.controller;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 16:11
* @Description:
*/
@RestController
@RequestMapping("/user/")
@Log4j2
public class UserController extends BaseController {
@Autowired
private IUserService userService;
@RequestMapping("findByAll")
public DataResponse<List<User>> findByAll(){
try {
return userService.findByAll();
} catch (Exception e){
log.error("查询出错{}",e);
}
return DataResponse.BuildFailResponse("查询出错!");
}
}
junit与tomcat配置与以上一致!
tomcat结果
spring+springmvc+mybatis
项目结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring</artifactId>
<groupId>com.hong</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.hong.spring</groupId>
<artifactId>spring_mybatis</artifactId>
<packaging>war</packaging>
<name>spring_mybatis Maven Webapp</name>
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<logback.version>1.2.3</logback.version>
<over-slf4j.version>1.7.25</over-slf4j.version>
<spring.version>4.3.11.RELEASE</spring.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<slf4j.version>1.7.12</slf4j.version>
<org.mybatis>3.5.0</org.mybatis>
<org.mybatis.spring>2.0.3</org.mybatis.spring>
</properties>
<dependencies>
<!--mybatis-->
<!-- Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${org.mybatis}</version>
</dependency>
<!--Mybatis Spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${org.mybatis.spring}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-jdbc</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!--引入连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!--引入AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--该包的主要作用是会去自动查找合适的日志记录框架进行记录-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--引入日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
<optional>true</optional>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<!--引入hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!--引入orm-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<build>
<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>
applicationContext-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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置组件扫描 -->
<context:component-scan base-package="com.hong.spring"></context:component-scan>
<!--加载配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 开启注解 -->
<context:annotation-config />
<!--开启注解事务-->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--放行静态资源-->
<mvc:default-servlet-handler />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- 后缀 -->
<property name="suffix" value=".html" />
<property name="contentType" value="text/html"/>
</bean>
<!--开启mvc注解事务-->
<!-- 定义注解驱动 -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- 设置支持中文 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 基础配置 -->
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 关键配置 -->
<!-- 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 -->
<property name="initialSize" value="3" />
<!-- 最小连接池数量 -->
<property name="minIdle" value="2" />
<!-- 最大连接池数量 -->
<property name="maxActive" value="15" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
<!-- 性能配置 -->
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 其他配置 -->
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
执行validationQuery检测连接是否有效。-->
<property name="testWhileIdle" value="true" />
<!-- 这里建议配置为TRUE,防止取到的连接不可用 ,申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
<property name="testOnBorrow" value="true" />
<!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->
<property name="testOnReturn" value="false" />
</bean>
<!--事务管理器-->
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载 MyBatis 的配置文件 -->
<property name="configLocation" value="classpath:mybatis.xml"/>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 所有配置的mapper文件 -->
<property name="mapperLocations" value="classpath*:com/hong/spring/mapper/*.xml" />
</bean>
<!-- Mapper 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描 包下的组件 -->
<property name="basePackage" value="com.hong.spring.dao" />
<!-- 关联mapper扫描器 与 sqlsession管理器 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!--事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
其他配置同上!
WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>mybatis</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mybatis.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>mybatis</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
用户实体与AO
/**
* @Auther: csh
* @Date: 2020/8/3 18:12
* @Description:用户实体
*/
@Data
public class User implements Serializable {
private Integer id;
private String username;
private Integer age;
}
package com.hong.spring.entity.ao;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Auther: csh
* @Date: 2020/8/21 16:01
* @Description:用户分页参数
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserAO implements Serializable {
/** 页码*/
private Integer page;
/** 页条数*/
private Integer pageSize;
}
package com.hong.spring.dao;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:04
* @Description:用户dao层
*/
public interface UserMapper {
/**
*
* 功能描述:查询总条数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:31
*/
List<User> findAllUserList();
/**
*
* 功能描述:获取总数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
int findAllTotal();
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
int update(User user);
/**
*
* 功能描述:添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/19 18:39
*/
int save(User user);
/**
*
* 功能描述:批量添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 15:46
*/
int insertBatch(@Param("list")List<User> list);
/**
*
* 功能描述:通过id查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/19 18:39
*/
User findById(int id);
/**
*
* 功能描述:通过分页查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 16:05
*/
List<User> findByPage(UserAO ao);
}
com/hong/spring/mapper/UserMapper.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.hong.spring.dao.UserMapper">
<resultMap type="com.hong.spring.entity.User" id="user">
<id column="id" property="id" />
<result column="user_name" property="username" />
<result column="age" property="age" />
</resultMap>
<select id="findById" resultType="com.hong.spring.entity.User">
SELECT * FROM user WHERE id = #{id,jdbcType=INTEGER}
</select>
<select id="findByPage" resultMap="user" parameterType="com.hong.spring.entity.ao.UserAO">
select * from user where 1=1 limit #{page},#{pageSize}
</select>
<select id="findAllUserList" resultMap="user">
SELECT * FROM user
</select>
<select id="findAllTotal" resultType="int">
SELECT count(*) FROM user
</select>
<insert id="save" >
INSERT INTO user ( user_name, age)
VALUES (#{username,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertBatch">
insert into user
( user_name, age)
values
<foreach collection="list" item="user" index="index"
separator=",">
(#{user.username,jdbcType=VARCHAR},#{user.age,jdbcType=INTEGER})
</foreach>
</insert>
<update id="update" >
update user
<set>
<if test="username !=null">
user_name=#{username,jdbcType=VARCHAR},
</if>
<if test="age !=null">
age =#{age,jdbcType=INTEGER}
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
服务接口与实现
package com.hong.spring.service;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import com.hong.spring.utils.DataResponse;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:07
* @Description:用户服务层
*/
public interface IUserService {
/**
*
* 功能描述:查询全部
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<List<User>> findByAll();
/**
*
* 功能描述:添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> save(User user);
/**
*
* 功能描述:批量添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 15:47
*/
DataResponse<Boolean> insertBatch(List<User> list);
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> update(User user);
/**
*
* 功能描述:通过id查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:42
*/
DataResponse<User> findById(int i);
/**
*
* 功能描述:通过分页查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 16:04
*/
DataResponse<List<User>> findByPage(UserAO ao);
}
package com.hong.spring.service.impl;
import com.hong.spring.dao.UserMapper;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:16
* @Description:用户实现
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userDao;
public DataResponse<List<User>> findByAll() {
List <User> allUserList = userDao.findAllUserList();
int allTotal = userDao.findAllTotal();
return DataResponse.BuildSuccessResponse(allUserList,allTotal);
}
@Transactional
public DataResponse <Boolean> save(User user) {
if(null==user){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int save = userDao.save(user);
return DataResponse.BuildSuccessResponse(save>0?true:false);
}
@Override
public DataResponse <Boolean> insertBatch(List <User> list) {
if(null==list){
return DataResponse.BuildFailResponse("参数不能为空!");
}
int batchSave = userDao.insertBatch(list);
return DataResponse.BuildSuccessResponse(batchSave>0?true:false);
}
@Transactional
public DataResponse <Boolean> update(User user) {
if(null==user || user.getId()==null){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int update = userDao.update(user);
return DataResponse.BuildSuccessResponse(update>0?true:false);
}
public DataResponse <User> findById(int i) {
User byId = userDao.findById(i);
return DataResponse.BuildSuccessResponse(byId);
}
@Override
public DataResponse <List <User>> findByPage(UserAO ao) {
if(ao==null){
ao.setPage(0);
ao.setPageSize(10);
}else{
ao.setPage(ao.getPageSize() * ao.getPage());
}
int allTotal = userDao.findAllTotal();
List <User> byPage = userDao.findByPage(ao);
return DataResponse.BuildSuccessResponse(byPage,allTotal);
}
}
控制器层
package com.hong.spring.controller;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Auther: csh
* @Date: 2020/8/18 17:36
* @Description:
*/
@Controller
@RequestMapping("/")
@Log4j2
public class IndexController {
@RequestMapping
public String index(){
log.info("首页");
return "index";
}
}
package com.hong.spring.controller;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 16:11
* @Description:
*/
@RestController
@RequestMapping("/user/")
@Log4j2
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("findByAll")
public DataResponse<List<User>> findByAll(){
try {
return userService.findByAll();
} catch (Exception e){
log.error("查询出错{}",e);
}
return DataResponse.BuildFailResponse("查询出错!");
}
}
junit
package com.hong.spring.service;
import com.alibaba.fastjson.JSONObject;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import com.hong.spring.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* @Auther: csh
* @Date: 2020/8/19 19:25
* @Description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-mybatis.xml")
@Log4j2
public class IUserServiceTest {
@Autowired
private IUserService iUserService;
@Test
public void findByAll() {
DataResponse <List <User>> byAll = iUserService.findByAll();
log.info("查出来的结果{}", JSONObject.toJSON(byAll));
}
@Test
public void save() {
User user = new User();
user.setAge(100);
user.setUsername("hong3");
DataResponse <Boolean> save = iUserService.save(user);
log.info(JSONObject.toJSONString(save));
}
@Test
public void insertBatch(){
List<User> list = new ArrayList <>();
int size =10;
for(int i=0;i<size;i++){
User user = new User();
user.setAge(i);
user.setUsername("hong"+i);
list.add(user);
}
DataResponse <Boolean> booleanDataResponse = iUserService.insertBatch(list);
log.info(JSONObject.toJSONString(booleanDataResponse));
}
@Test
public void update() {
User user = new User();
user.setId(3);
user.setUsername("updateHong");
DataResponse <Boolean> update = iUserService.update(user);
log.info(JSONObject.toJSONBytes(update));
}
@Test
public void findById() {
DataResponse <User> byId = iUserService.findById(3);
log.info(JSONObject.toJSONString(byId));
}
@Test
public void findByPage(){
int size = 10;
int page = 0;
UserAO ao = new UserAO(page,size);
DataResponse <List <User>> byPage = iUserService.findByPage(ao);
log.info(JSONObject.toJSONString(byPage));
}
}
结果
findByAll
11:31:45.792 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
11:31:45.798 [main] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2234078] was not registered for synchronization because synchronization is not active
11:31:46.049 [main] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
11:31:46.056 [main] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [com.mysql.jdbc.JDBC4Connection@21719a0] will not be managed by Spring
11:31:46.059 [main] DEBUG com.hong.spring.dao.UserMapper.findAllUserList - ==> Preparing: SELECT * FROM user
11:31:46.077 [main] DEBUG com.hong.spring.dao.UserMapper.findAllUserList - ==> Parameters:
11:31:46.096 [main] DEBUG com.hong.spring.dao.UserMapper.findAllUserList - <== Total: 45
11:31:46.099 [main] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
11:31:46.100 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2234078]
11:31:46.101 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
11:31:46.101 [main] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66596a88] was not registered for synchronization because synchronization is not active
11:31:46.102 [main] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [com.mysql.jdbc.JDBC4Connection@21719a0] will not be managed by Spring
11:31:46.102 [main] DEBUG com.hong.spring.dao.UserMapper.findAllTotal - ==> Preparing: SELECT count(*) FROM user
11:31:46.102 [main] DEBUG com.hong.spring.dao.UserMapper.findAllTotal - ==> Parameters:
11:31:46.104 [main] DEBUG com.hong.spring.dao.UserMapper.findAllTotal - <== Total: 1
11:31:46.104 [main] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
11:31:46.104 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@66596a88]
11:31:46.119 [main] INFO com.hong.spring.service.IUserServiceTest - 查出来的结果{msg=null, total=45, code=0, data=[{id=1, age=100, username=333}, {id=2, age=100, username=测试32}, {id=3, age=100, username=updateHong}, {id=4, age=0, username=hong0}, {id=5, age=1, username=hong1}, {id=6, age=2, username=hong2}, {id=7, age=3, username=hong3}, {id=8, age=4, username=hong4}, {id=9, age=5, username=hong5}, {id=10, age=6, username=hong6}, {id=11, age=7, username=hong7}, {id=12, age=8, username=hong8}, {id=13, age=9, username=hong9}, {id=14, age=200, username=mybatisPlus}, {id=15, age=0, username=mybatisPlus0}, {id=16, age=1, username=mybatisPlus1}, {id=17, age=2, username=mybatisPlus2}, {id=18, age=3, username=mybatisPlus3}, {id=19, age=4, username=mybatisPlus4}, {id=20, age=5, username=mybatisPlus5}, {id=21, age=6, username=mybatisPlus6}, {id=22, age=7, username=mybatisPlus7}, {id=23, age=8, username=mybatisPlus8}, {id=24, age=9, username=mybatisPlus9}, {id=25, age=10, username=mybatisPlus10}, {id=26, age=11, username=mybatisPlus11}, {id=27, age=12, username=mybatisPlus12}, {id=28, age=13, username=mybatisPlus13}, {id=29, age=14, username=mybatisPlus14}, {id=30, age=15, username=mybatisPlus15}, {id=31, age=16, username=mybatisPlus16}, {id=32, age=17, username=mybatisPlus17}, {id=33, age=18, username=mybatisPlus18}, {id=34, age=19, username=mybatisPlus19}, {id=35, age=20, username=mybatisPlus20}, {id=36, age=21, username=mybatisPlus21}, {id=37, age=22, username=mybatisPlus22}, {id=38, age=23, username=mybatisPlus23}, {id=39, age=24, username=mybatisPlus24}, {id=40, age=25, username=mybatisPlus25}, {id=41, age=26, username=mybatisPlus26}, {id=42, age=27, username=mybatisPlus27}, {id=43, age=28, username=mybatisPlus28}, {id=44, age=29, username=update44}, {id=45, age=100, username=测试32}]}
11:31:46.126 [Thread-1] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} closing ...
11:31:46.128 [Thread-1] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt exit cache
11:31:46.128 [Thread-1] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt exit cache
11:31:46.129 [Thread-1] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} closed
其他测试同上~
tomcat配置同上!
tomcat结果:
[2020-08-25 11:33:19,685] Artifact spring_mybatis:war exploded: Artifact is deployed successfully
[2020-08-25 11:33:19,686] Artifact spring_mybatis:war exploded: Deploy took 8,556 milliseconds
11:33:40.338 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
11:33:40.352 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a591324] was not registered for synchronization because synchronization is not active
11:33:40.853 [http-nio-8080-exec-3] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
11:33:40.866 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [com.mysql.jdbc.JDBC4Connection@1a1fb429] will not be managed by Spring
11:33:40.870 [http-nio-8080-exec-3] DEBUG com.hong.spring.dao.UserMapper.findAllUserList - ==> Preparing: SELECT * FROM user
11:33:40.901 [http-nio-8080-exec-3] DEBUG com.hong.spring.dao.UserMapper.findAllUserList - ==> Parameters:
11:33:40.942 [http-nio-8080-exec-3] DEBUG com.hong.spring.dao.UserMapper.findAllUserList - <== Total: 45
11:33:40.945 [http-nio-8080-exec-3] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
11:33:40.946 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a591324]
11:33:40.947 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
11:33:40.948 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6d1b1a66] was not registered for synchronization because synchronization is not active
11:33:40.948 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.transaction.SpringManagedTransaction - JDBC Connection [com.mysql.jdbc.JDBC4Connection@1a1fb429] will not be managed by Spring
11:33:40.949 [http-nio-8080-exec-3] DEBUG com.hong.spring.dao.UserMapper.findAllTotal - ==> Preparing: SELECT count(*) FROM user
11:33:40.949 [http-nio-8080-exec-3] DEBUG com.hong.spring.dao.UserMapper.findAllTotal - ==> Parameters:
11:33:40.950 [http-nio-8080-exec-3] DEBUG com.hong.spring.dao.UserMapper.findAllTotal - <== Total: 1
11:33:40.950 [http-nio-8080-exec-3] DEBUG com.alibaba.druid.pool.PreparedStatementPool - stmt enter cache
11:33:40.951 [http-nio-8080-exec-3] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6d1b1a66]
spring+springmvc+mybatis_plus
项目结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring</artifactId>
<groupId>com.hong</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.hong</groupId>
<artifactId>spring_mybatis_plus</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<logback.version>1.2.3</logback.version>
<over-slf4j.version>1.7.25</over-slf4j.version>
<spring.version>4.3.11.RELEASE</spring.version>
<commons-dbcp.version>1.4</commons-dbcp.version>
<slf4j.version>1.7.12</slf4j.version>
<org.mybatis>3.1.0</org.mybatis>
</properties>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${org.mybatis}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${org.mybatis}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-jdbc</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
<!--引入连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!--引入AOP-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--该包的主要作用是会去自动查找合适的日志记录框架进行记录-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--引入日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
<optional>true</optional>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<!--引入hibernate-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!--引入orm-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<build>
<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>
applicationContext-mybatis_plus.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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置组件扫描 -->
<context:component-scan base-package="com.hong.spring"></context:component-scan>
<!--加载配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 开启注解 -->
<context:annotation-config />
<!--开启注解事务-->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--放行静态资源-->
<mvc:default-servlet-handler />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/pages/" />
<!-- 后缀 -->
<property name="suffix" value=".html" />
<property name="contentType" value="text/html"/>
</bean>
<!--开启mvc注解事务-->
<!-- 定义注解驱动 -->
<mvc:annotation-driven>
<mvc:message-converters>
<!-- 设置支持中文 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 基础配置 -->
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- 关键配置 -->
<!-- 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 -->
<property name="initialSize" value="3" />
<!-- 最小连接池数量 -->
<property name="minIdle" value="2" />
<!-- 最大连接池数量 -->
<property name="maxActive" value="15" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
<!-- 性能配置 -->
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 其他配置 -->
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,
执行validationQuery检测连接是否有效。-->
<property name="testWhileIdle" value="true" />
<!-- 这里建议配置为TRUE,防止取到的连接不可用 ,申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。-->
<property name="testOnBorrow" value="true" />
<!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->
<property name="testOnReturn" value="false" />
</bean>
<!--事务管理器-->
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<!-- 加载 MyBatis 的配置文件 -->
<property name="configLocation" value="classpath:mybatis-plus.xml"/>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 所有配置的mapper文件 -->
<property name="mapperLocations" value="classpath*:com/hong/spring/mapper/*.xml" />
</bean>
<!-- Mapper 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描 包下的组件 -->
<property name="basePackage" value="com.hong.spring.dao" />
<!-- 关联mapper扫描器 与 sqlsession管理器 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!--事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
其他与以上一致!
实体
package com.hong.spring.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import java.io.Serializable;
/**
* @Auther: csh
* @Date: 2020/8/3 18:12
* @Description:用户实体
*/
@Data
@TableName("user")
public class User extends Model<User> implements Serializable {
@TableId(type= IdType.AUTO)
private Integer id;
@TableField("user_name")
private String username;
private Integer age;
}
package com.hong.spring.entity.ao;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @Auther: csh
* @Date: 2020/8/21 16:01
* @Description:用户分页参数
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserAO implements Serializable {
/** 页码*/
private Integer page;
/** 页条数*/
private Integer pageSize;
}
dao层及实现
package com.hong.spring.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:04
* @Description:用户dao层
*/
public interface UserMapper extends BaseMapper<User> {
/**
*
* 功能描述:查询总条数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:31
*/
List<User> findAllUserList();
/**
*
* 功能描述:获取总数
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
int findAllTotal();
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:30
*/
int update(User user);
/**
*
* 功能描述:添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/19 18:39
*/
int save(User user);
/**
*
* 功能描述:批量添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 15:46
*/
int insertBatch(@Param("list") List <User> list);
/**
*
* 功能描述:通过id查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/19 18:39
*/
User findById(int id);
/**
*
* 功能描述:通过分页查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 16:05
*/
List<User> findByPage(UserAO ao);
}
<?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.hong.spring.dao.UserMapper">
<resultMap type="com.hong.spring.entity.User" id="user">
<id column="id" property="id" />
<result column="user_name" property="username" />
<result column="age" property="age" />
</resultMap>
<select id="findById" resultType="com.hong.spring.entity.User">
SELECT * FROM user WHERE id = #{id,jdbcType=INTEGER}
</select>
<select id="findByPage" resultMap="user" parameterType="com.hong.spring.entity.ao.UserAO">
select * from user where 1=1 limit #{page},#{pageSize}
</select>
<select id="findAllUserList" resultMap="user">
SELECT * FROM user
</select>
<select id="findAllTotal" resultType="int">
SELECT count(*) FROM user
</select>
<insert id="save" >
INSERT INTO user ( user_name, age)
VALUES (#{username,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertBatch">
insert into user
( user_name, age)
values
<foreach collection="list" item="user" index="index"
separator=",">
(#{user.username,jdbcType=VARCHAR},#{user.age,jdbcType=INTEGER})
</foreach>
</insert>
<update id="update" >
update user
<set>
<if test="username !=null">
user_name=#{username,jdbcType=VARCHAR},
</if>
<if test="age !=null">
age =#{age,jdbcType=INTEGER}
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
服务层及实现
package com.hong.spring.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import com.hong.spring.utils.DataResponse;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:07
* @Description:用户服务层
*/
public interface IUserService extends IService<User> {
/**
*
* 功能描述:查询全部
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<List<User>> findByAll();
/**
*
* 功能描述:批量添加
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 15:47
*/
DataResponse<Boolean> insertBatch(List <User> list);
/**
*
* 功能描述:更新
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:26
*/
DataResponse<Boolean> update(User user);
/**
*
* 功能描述:通过id查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/18 15:42
*/
DataResponse<User> findById(int i);
/**
*
* 功能描述:通过分页查询
*
* @param:
* @return:
* @auther: csh
* @date: 2020/8/21 16:04
*/
DataResponse<List<User>> findByPage(UserAO ao);
}
package com.hong.spring.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hong.spring.dao.UserMapper;
import com.hong.spring.entity.User;
import com.hong.spring.entity.ao.UserAO;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 15:16
* @Description:用户实现
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public DataResponse<List<User>> findByAll() {
List <User> allUserList = userMapper.selectList(null);
Integer allTotal = userMapper.selectCount(null);
return DataResponse.BuildSuccessResponse(allUserList,allTotal);
}
@Override
public DataResponse <Boolean> insertBatch(List <User> list) {
if(null==list){
return DataResponse.BuildFailResponse("参数不能为空!");
}
boolean batchSave = this.saveBatch(list);
return DataResponse.BuildSuccessResponse(batchSave);
}
@Transactional
public DataResponse <Boolean> update(User user) {
if(null==user || user.getId()==null){
return DataResponse.BuildFailResponse("必传参数不能为空!");
}
int update = userMapper.update(user);
return DataResponse.BuildSuccessResponse(update>0?true:false);
}
public DataResponse <User> findById(int i) {
User byId = userMapper.findById(i);
return DataResponse.BuildSuccessResponse(byId);
}
@Override
public DataResponse <List <User>> findByPage(UserAO ao) {
if(ao==null){
ao.setPage(0);
ao.setPageSize(10);
}else{
ao.setPage(ao.getPageSize() * ao.getPage());
}
int allTotal = userMapper.findAllTotal();
List <User> byPage = userMapper.findByPage(ao);
return DataResponse.BuildSuccessResponse(byPage,allTotal);
}
}
控制器层
package com.hong.spring.controller;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Auther: csh
* @Date: 2020/8/18 17:36
* @Description:
*/
@Controller
@RequestMapping("/")
@Log4j2
public class IndexController {
@RequestMapping
public String index(){
log.info("首页");
return "index";
}
}
package com.hong.spring.controller;
import com.hong.spring.entity.User;
import com.hong.spring.service.IUserService;
import com.hong.spring.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Auther: csh
* @Date: 2020/8/18 16:11
* @Description:
*/
@RestController
@RequestMapping("/user/")
@Log4j2
public class UserController{
@Autowired
private IUserService userService;
@RequestMapping("findByAll")
public DataResponse<List<User>> findByAll(){
try {
return userService.findByAll();
} catch (Exception e){
log.error("查询出错{}",e);
}
return DataResponse.BuildFailResponse("查询出错!");
}
}
junit
package com.hong.spring.service;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hong.spring.entity.User;
import com.hong.spring.utils.DataResponse;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* @Auther: csh
* @Date: 2020/8/24 11:17
* @Description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext-mybatis_plus.xml")
@Log4j2
public class UserServiceTest {
@Autowired
private IUserService userService;
@Test
public void findByAll() {
System.out.println("111111111111111");
DataResponse <List <User>> byAll = userService.findByAll();
log.info("结果{}", JSONObject.toJSONString(byAll));
}
@Test
public void save() {
User user = new User();
user.setUsername("mybatisPlus");
user.setAge(200);
userService.save(user);
}
@Test
public void insertBatch() {
List<User> userList = new ArrayList <>();
User use;
for(int i=0;i<30;i++){
use = new User();
use.setAge(i);
use.setUsername("mybatisPlus"+i);
userList.add(use);
}
userService.insertBatch(userList);
}
@Transactional
@Rollback(value = false)
@Test
public void update() {
User user = userService.getById(44);
user.setUsername("update44");
userService.update(user);
}
@Test
public void findById() {
User byId = userService.getById(44);
log.info(JSONObject.toJSONString(byId));
}
@Test
public void findByPage() {
Page<User> page = new Page<>(2, 10);
QueryWrapper<User> queryWrapper = new QueryWrapper <>();
IPage <User> page1 = userService.page(page, queryWrapper);
log.info("结果{}",JSONObject.toJSONString(page1));
}
}
最后
junit:findByPage
11:50:16.229 [main] INFO com.hong.spring.service.UserServiceTest - 结果{"current":2,"pages":0,"records":[{"age":100,"id":1,"username":"333"},{"age":100,"id":2,"username":"测试32"},{"age":100,"id":3,"username":"updateHong"},{"age":0,"id":4,"username":"hong0"},{"age":1,"id":5,"username":"hong1"},{"age":2,"id":6,"username":"hong2"},{"age":3,"id":7,"username":"hong3"},{"age":4,"id":8,"username":"hong4"},{"age":5,"id":9,"username":"hong5"},{"age":6,"id":10,"username":"hong6"},{"age":7,"id":11,"username":"hong7"},{"age":8,"id":12,"username":"hong8"},{"age":9,"id":13,"username":"hong9"},{"age":200,"id":14,"username":"mybatisPlus"},{"age":0,"id":15,"username":"mybatisPlus0"},{"age":1,"id":16,"username":"mybatisPlus1"},{"age":2,"id":17,"username":"mybatisPlus2"},{"age":3,"id":18,"username":"mybatisPlus3"},{"age":4,"id":19,"username":"mybatisPlus4"},{"age":5,"id":20,"username":"mybatisPlus5"},{"age":6,"id":21,"username":"mybatisPlus6"},{"age":7,"id":22,"username":"mybatisPlus7"},{"age":8,"id":23,"username":"mybatisPlus8"},{"age":9,"id":24,"username":"mybatisPlus9"},{"age":10,"id":25,"username":"mybatisPlus10"},{"age":11,"id":26,"username":"mybatisPlus11"},{"age":12,"id":27,"username":"mybatisPlus12"},{"age":13,"id":28,"username":"mybatisPlus13"},{"age":14,"id":29,"username":"mybatisPlus14"},{"age":15,"id":30,"username":"mybatisPlus15"},{"age":16,"id":31,"username":"mybatisPlus16"},{"age":17,"id":32,"username":"mybatisPlus17"},{"age":18,"id":33,"username":"mybatisPlus18"},{"age":19,"id":34,"username":"mybatisPlus19"},{"age":20,"id":35,"username":"mybatisPlus20"},{"age":21,"id":36,"username":"mybatisPlus21"},{"age":22,"id":37,"username":"mybatisPlus22"},{"age":23,"id":38,"username":"mybatisPlus23"},{"age":24,"id":39,"username":"mybatisPlus24"},{"age":25,"id":40,"username":"mybatisPlus25"},{"age":26,"id":41,"username":"mybatisPlus26"},{"age":27,"id":42,"username":"mybatisPlus27"},{"age":28,"id":43,"username":"mybatisPlus28"},{"age":29,"id":44,"username":"update44"},{"age":100,"id":45,"username":"测试32"}],"searchCount":true,"size":10,"total":0}
其他与以上一致。
tomcat
代码下载:https://gitee.com/hong99/spring/issues/I1N1DF
最后
ORM可以用来比喻解放双手来形容,传统的jdbc,真的非常麻烦,代码冗长.....实际工作中,mybatis和mybatisplus用的是非常多的,毕竟容易上手和可维护性高,mybatisplus有点类似于hibernate高度封装,但是又不影响原来的mybatis功能,非常友好,也是兼容性非常高,当然使用的人数也越来越多,推荐。
相关文章:
https://mybatis.plus/guide/#%E7%89%B9%E6%80%A7
https://blog.csdn.net/AlbenXie/article/details/80223045
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)