目录
com.itbignyi
config
DataSource
MapperConfig(方式1)
MapperConfigNew(方式2-推荐)
WebMvcConfig
ServiceConfig
SpringIoCInit
controller
service
serviceImpl
mapper
pojo
employee
utils
PageBean
R
resources
com/itbignyi/mapper
EmployeeMapper.xml
jdbc.propertise
logback.xml
mybatis-config.xml(方式1)
webapp
WEB-INF
views(包)
web.xml
pom.xml
package com.itbignyi.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import javax.sql.DataSource; /** * 连接池配置类 */ @Configuration @PropertySource("classpath:jdbc.properties") public class DataSourceConfig { @Value("${jdbc.user}") private String user; @Value("${jdbc.password}") private String password; @Value("${jdbc.url}") private String url; @Value("${jdbc.driver}") private String driver; // druid连接池配置 @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUsername(user); dataSource.setPassword(password); dataSource.setUrl(url); dataSource.setDriverClassName(driver); return dataSource; } }
package com.itbignyi.config; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.annotations.Mapper; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import javax.sql.DataSource; /** * 持久层配置类:连接池,sqlSessionFactory,mapper代理对象 * 方式1.保留外部配置文件 * TODO:如果将dataSour和mybatis组件连接在一起,会触发@Value注解不生效的问题 * 原因就是mybatis的文件优先于@Value注解读取 * 解决:分开配置,写到不同的类中即可 */ @Configuration public class MappingConfig { @Bean // sqlSessionFactory 加入ioc容器 public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); // 指定外部mybatis文件 Resource resource=new ClassPathResource("mybatis-config.xml"); // 外部 sqlSessionFactoryBean.setConfigLocation(resource); return sqlSessionFactoryBean; } @Bean // mapper代理对象加入到ioc容器 public MapperScannerConfigurer mapperScannerConfigurer() { // Mapper代理工厂 MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.itbignyi.mapper"); return mapperScannerConfigurer; } }
package com.itbignyi.config; import com.alibaba.druid.support.logging.SLF4JImpl; import com.github.pagehelper.PageInterceptor; import org.apache.ibatis.logging.slf4j.Slf4jImpl; import org.apache.ibatis.session.AutoMappingBehavior; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import javax.sql.DataSource; import java.util.Properties; /** * 持久层配置类:连接池,sqlSessionFactory,mapper代理对象 * TODO:方式2 * 保留外部配置文件 * 全部mybatis的属性在代码中实现 */ @Configuration public class MappingConfigNew { // sqlSessionFactory 加入ioc容器 @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 连接池 sqlSessionFactoryBean.setDataSource(dataSource); // mybatis配置设置 org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(); // 驼峰命名 configuration.setMapUnderscoreToCamelCase(true); // 记录日志 configuration.setLogImpl(Slf4jImpl.class); // 自动映射 configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL); // 别名设置 sqlSessionFactoryBean.setTypeAliasesPackage("com.itbignyi.pojo"); // 添加插件 PageInterceptor pageInterceptor = new PageInterceptor(); Properties properties = new Properties(); properties.setProperty("helperDialect", "mysql"); pageInterceptor.setProperties(properties); sqlSessionFactoryBean.addPlugins(pageInterceptor); sqlSessionFactoryBean.setConfiguration(configuration); return sqlSessionFactoryBean; } // mapper代理对象加入到ioc容器 @Bean public MapperScannerConfigurer mapperScannerConfigurer() { // Mapper代理工厂 MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.itbignyi.mapper"); return mapperScannerConfigurer; } }
package com.itbignyi.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
/**
* 配置类
*/
@EnableWebMvc//json处理器 HandlerMapping和HandlerAdapter
@Configuration//配置类
@ComponentScan({"com.itbignyi.controller", "com.itbignyi.exceptionHandler"})//包扫描
public class MvcConfig implements WebMvcConfigurer {
// 静态资源处理
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// 视图解析器
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/","jsp");
}
// 拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
}
}
package com.itbignyi.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; /** * service,aop,tx */ @Configuration @EnableAspectJAutoProxy @EnableTransactionManagement @ComponentScan("com.itbignyi.service") public class ServiceConfig { // 事务管理的实现 @Bean public TransactionManager transactionManager(DataSource dataSource) { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource); return dataSourceTransactionManager; } }
package com.itbignyi.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * spring的初始化类 */ public class SpringIoCInit extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class>[] getRootConfigClasses() { return new Class[]{DataSourceConfig.class, ServiceConfig.class, MappingConfigNew.class}; } @Override protected Class>[] getServletConfigClasses() { return new Class[]{MvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
package com.itbignyi.controller; import com.itbignyi.pojo.Employee; import com.itbignyi.service.EmployeeService; import com.itbignyi.utils.R; import jakarta.persistence.criteria.CriteriaBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("emp") @Slf4j public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping("/{pageSize}/{currentPage}") public R page(@PathVariable int pageSize, @PathVariable int currentPage) { R r=employeeService.page(pageSize,currentPage); log.info("查询的数据为:{}",r); return r; } @DeleteMapping("/{id}") public R remove(@PathVariable Integer id) { R r = employeeService.remove(id); return r; } @PostMapping public R save(@PathVariable @RequestBody Employee employee, BindingResult result) { if (result.hasErrors()) { return R.fail("参数为null,不能保存!"); } R r = employeeService.save(employee); return r; } @PutMapping public R update(@PathVariable @RequestBody Employee employee, BindingResult result) { if (result.hasErrors()) { return R.fail("参数为null,不能修改!"); } R r = employeeService.updata(employee); return r; } }
package com.itbignyi.service; import com.itbignyi.pojo.Employee; import com.itbignyi.utils.R; import java.util.List; public interface EmployeeService { R page(int pageSize, int currentPage); R remove(Integer id); R save(Employee employee); R updata(Employee employee); }
package com.itbignyi.service.Impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.itbignyi.mapper.EmployeeMapper; import com.itbignyi.pojo.Employee; import com.itbignyi.service.EmployeeService; import com.itbignyi.utils.PageBean; import com.itbignyi.utils.R; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeMapper employeeMapper; @Override public R page(int pageSize, int currentPage) { // 分页 PageHelper.startPage(currentPage,pageSize); // 查询 Listemployees = employeeMapper.queryList(); // 分页数据装配 PageInfo info=new PageInfo<>(employees); // 装配pageBean PageBean pageBean = new PageBean<>(currentPage,pageSize,info.getTotal(),info.getList()); R ok=R.ok(pageBean); return ok; } @Override public R remove(Integer id) { int rows= employeeMapper.deleteById(id); if (rows > 0) { return R.ok(null); } return R.fail(null); } @Override public R save(Employee employee) { int rows= employeeMapper.insert(employee); if (rows > 0) { return R.ok(null); } return R.fail(null); } @Override public R updata(Employee employee) { if (employee.getId() == null) { return R.fail("核心参数为null,无法修改!"); } int rows = employeeMapper.update(employee); if (rows > 0) { return R.ok(null); } return R.fail(null); } }
package com.itbignyi.mapper; import com.itbignyi.pojo.Employee; import java.util.List; public interface EmployeeMapper { ListqueryList(); int deleteById(Integer id); int insert(Employee employee); int update(Employee employee); }
package com.itbignyi.pojo; import lombok.Data; @Data public class Employee { private Integer id; private String title; private Boolean completed; }
package com.itbignyi.utils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @NoArgsConstructor @AllArgsConstructor public class PageBean{ private int currentPage;//当前页码 private int pageSize;//每页显示的数据量 private long total;//总数居条数 private List data;//当前页的数据集合 }
package com.itbignyi.utils; public class R { private int code = 200;//成功状态码 private boolean flag=true;//返回状态 private Object data;//返回具体数据 public static R ok(Object data) { R r = new R(); r.data = data; return r; } public static R fail(Object data) { R r = new R(); r.code = 500;//错误码 r.flag=false;//错误状态 r.data = data; return r; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
jdbc.user=root jdbc.password=1234 jdbc.url=jdbc:mysql:///mybatis-example jdbc.driver=com.mysql.cj.jdbc.Driver
[%d{HH:mm:ss.SSS}][%-5leve][%thread][%logger][%smg]%n
4.0.0 com.itbignyi ssm-integration-part 1.0-SNAPSHOT pom ssm-integration-01 ssm-integration-02 org.springframework spring-context ${spring-context.version} jakarta.annotation jakarta.annotation-api ${jakarta.annotation-api.version} org.springframework spring-aop ${spring-aop.version} org.springframework spring-aspects ${spring-aspects.version} org.springframework spring-tx ${spring-tx.version} org.springframework spring-jdbc ${spring-jdbc.version} org.springframework spring-webmvc ${spring-webmvc.version} jakarta.platform jakarta.jakartaee-web-api ${jakarta.jakartaee-web-api.version} provided jakarta.servlet.jsp.jstl jakarta.servlet.jsp.jstl-api ${jakarta.servlet.jsp.jstl-api.version} com.fasterxml.jackson.core jackson-databind ${jackson-databind.version} org.hibernate.validator hibernate-validator ${hibernate-validator.version} org.hibernate.validator hibernate-validator-annotation-processor ${hibernate-validator-annotation-processor.version} org.mybatis mybatis ${mybatis.version} mysql mysql-connector-java ${mysql-connector-java.version} com.github.pagehelper pagehelper ${pagehelper.version} org.springframework spring-web ${spring-web.version} org.mybatis mybatis-spring ${mybatis-spring.version} ch.qos.logback logback-classic ${logback-classic.version} org.projectlombok lombok ${lombok.version} com.alibaba druid ${druid.version} 17 17 UTF-8 6.0.12 2.1.1 6.0.12 6.0.11 6.0.11 6.0.11 6.0.12 9.1.0 3.0.0 2.15.2 6.0.18.Final 8.0.1.Final 3.5.13 8.0.30 5.3.2 6.0.11 3.0.2 1.4.11 1.18.28 1.2.1