随着spring版本迭代更新,现在越来越倡导不使用复杂繁琐的配置文件来配置项目,下面介绍纯粹使用java 配置类来配置spring、springmvc、mybatis;
环境:java 8 + maven + IDEA + mysql
新建maven web项目:(这个就不介绍了,网上一大堆的教程),下面进入正题;
一、项目所需依赖jar
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.open.ssm</groupId> <artifactId>ssm-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!-- 版本 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <junit.version>4.12</junit.version> <spring.version>4.3.0.RELEASE</spring.version> <jackson.version>2.5.0</jackson.version> <mysql-connector-java.version>5.1.37</mysql-connector-java.version> <fastjson.version>1.2.3</fastjson.version> <slf4j.version>1.7.12</slf4j.version> <commons-io.version>2.4</commons-io.version> <commons-fileupload.version>1.3.2</commons-fileupload.version> <commons-collections.version>3.2.2</commons-collections.version> <commons-lang3.version>3.3.2</commons-lang3.version> <commons-codec.version>1.10</commons-codec.version> <javax.servlet-api.version>3.1.0</javax.servlet-api.version> <druid.version>1.0.16</druid.version> <!-- <mybatis.version>3.4.0</mybatis.version> <mybatis-spring.version>1.3.0</mybatis-spring.version> --> <mybatis-plus.version>2.0.5</mybatis-plus.version> <beetl.version>2.7.18</beetl.version> </properties> <!-- 依赖管理 --> <dependencies> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- spring start--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</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-tx</artifactId> <version>${spring.version}</version> </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-jdbc</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-aspects</artifactId> <version>${spring.version}</version> </dependency> <!--sprint end--> <!-- jackson start--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- jackson end--> <!-- jdbc驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> <!--common 组件 start--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>${commons-collections.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency> <!--common 组件 end--> <!-- log --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- servlet start--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- servlet end--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.ibeetl/beetl --> <dependency> <groupId>com.ibeetl</groupId> <artifactId>beetl</artifactId> <version>${beetl.version}</version> </dependency> <!--可以不用写 get、set方法--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.12</version> </dependency> </dependencies> <build> <finalName>ssm-demo</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.5</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <port>8088</port> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
二、在maven项目中新建几个基本包
三、spring配置类
1、webconfig 配置类,继承 WebMvcConfigurerAdapter
package com.study.ssm.config; import org.beetl.ext.spring.BeetlGroupUtilConfiguration; import org.beetl.ext.spring.BeetlSpringViewResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Web Configuration Class * * @author EnzoLuo * @date 2018/10/22 */ @Configuration @EnableWebMvc @ComponentScan("com.study.ssm.controller") public class WebConfig extends WebMvcConfigurerAdapter { @Bean(initMethod = "init") public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() { BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration(); ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader()); beetlGroupUtilConfiguration.setConfigFileResource(patternResolver.getResource("classpath:beetl.properties")); return beetlGroupUtilConfiguration; } @Bean(name = "viewResolver") public BeetlSpringViewResolver getBeetlSpringViewResolver() { BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver(); beetlSpringViewResolver.setContentType("text/html;charset=UTF-8"); beetlSpringViewResolver.setOrder(0); return beetlSpringViewResolver; }//静态资源的处理 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
2、RootConfig 配置类 功能:配置基本的扫描包
package com.study.ssm.config; import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * Root Configuration Class * * @author EnzoLuo * @date 2018/10/22 */ @Configuration @ComponentScan(basePackages={ "com.study.ssm.config", "com.study.ssm.repository", "com.study.ssm.service" })public class RootConfig { @Bean public BeanNameAutoProxyCreator proxycreate(){ BeanNameAutoProxyCreator proxycreate = new BeanNameAutoProxyCreator(); proxycreate.setProxyTargetClass(true); proxycreate.setBeanNames("*ServiceImpl"); proxycreate.setInterceptorNames("transactionInterceptor"); return proxycreate; } }
3、新建 WebAppInitializer类 继承 AbstractAnnotationConfigDispatcherServletInitializer
这里是把刚才写的两个配置类加载进来
package com.study.ssm.config; import org.apache.log4j.Logger; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * Application gateway and load config class * * @author EnzoLuo * @date 2018/10/22 */ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { private final static Logger LOG = Logger.getLogger(WebAppInitializer.class); @Override protected Class<?>[] getRootConfigClasses() { LOG.info("------root配置类初始化------"); return new Class<?>[] { RootConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { LOG.info("------web配置类初始化------"); return new Class<?>[] { WebConfig.class }; } @Override protected String[] getServletMappings() { LOG.info("------映射根路径初始化------"); return new String[]{ "/" };//请求路径映射,根路径 } }
四、新建 beetl.properties 用来配置视图解析器
这个文件的引入是在WebConfig 里面
#classpath 根路径,即模板资源路径 RESOURCE.root=/WEB-INF/view/ #是否检测文件变化,开发用true合适,但线上要改为false RESOURCE.autoCheck= true
五、加上一个 log4j.properties
### set log levels ###
log4j.rootLogger = INFO , C , D , E
### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [ssm-demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/ssm-demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [ssm-demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/ssm-demo_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [ssm-demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
暂时写一个 indexController 测试一下;
package com.study.ssm.controller; import java.io.File; import java.io.IOException; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; /** * index * * @author EnzoLuo * @date 2018/10/22 */ @Controller public class IndexController { @SuppressWarnings("unused") private final static Logger LOG = Logger.getLogger(IndexController.class); @GetMapping("/index") public String index(){ return "ssm.html"; } }
记得在WEB-INF 下新建一个view目录,然后随便加一个 ssm.html 文件
启动项目访问 、如果正确访问到ssm.html 则说明配置成功
注:别忘了install 一下,我之前又一次出错了,怎么都不到原因,最后突然想起来,忘记install了
第二阶段:配置mybatis
一:jdbc.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/zhidevelop spring.datasource.username=root spring.datasource.password=root #连接池配置 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 #连接等待超时时间 spring.datasource.maxWait=60000 #配置隔多久进行一次检测(检测可以关闭的空闲连接) spring.datasource.timeBetweenEvictionRunsMillis=60000 #配置连接在池中的最小生存时间 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙 spring.datasource.filters=stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
二、新建 DruidDataSourceConfig 配置类
package com.study.ssm.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
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.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
/**
* DataSource Configuration Class
*
* @author EnzoLuo
* @date 2018/10/22
*/
@Configuration
@PropertySource("classpath:/jdbc.properties")
@MapperScan(basePackages="com.study.ssm.repository")
public class DruidDataSourceConfig {
private final static Logger LOG = Logger.getLogger(DruidDataSourceConfig.class);
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("{spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean //声明其为Bean实例
public DataSource dataSource(){
LOG.info("Initialize the data source...");
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
LOG.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
/*
//JdbcTemplate的配置
@Bean
public JdbcTemplate jdbcTemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(){
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource());
return namedParameterJdbcTemplate;
}*/
//全局配置
public GlobalConfiguration globalConfigurationBean(){
GlobalConfiguration globalConfiguration = new GlobalConfiguration();
globalConfiguration.setIdType(2);//AUTO->`0`("数据库ID自增")、INPUT->`1`(用户输入ID")、ID_WORKER->`2`("全局唯一ID")、UUID->`3`("全局唯一ID")
globalConfiguration.setDbColumnUnderline(true);//全局表为下划线命名设置 true
return globalConfiguration;
}
//mybatis的配置
@Bean
public MybatisSqlSessionFactoryBean sqlSessionFactoryBean() throws IOException{
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
//SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();//mybatis-plus插件类
sqlSessionFactoryBean.setDataSource(dataSource());//数据源
sqlSessionFactoryBean.setGlobalConfig(globalConfigurationBean());//MP全局注入
sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:mybatis/mappers/*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.study.ssm.entity");//别名,让*Mpper.xml实体类映射可以不加上具体包名
return sqlSessionFactoryBean;
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager dataSourceTransactionManager(){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource());
return dataSourceTransactionManager;
}
@Bean(name="transactionInterceptor")
public TransactionInterceptor interceptor(){
TransactionInterceptor interceptor = new TransactionInterceptor();
interceptor.setTransactionManager(dataSourceTransactionManager());
Properties transactionAttributes = new Properties();
transactionAttributes.setProperty("save*", "PROPAGATION_REQUIRED");
transactionAttributes.setProperty("del*", "PROPAGATION_REQUIRED");
transactionAttributes.setProperty("update*", "PROPAGATION_REQUIRED");
transactionAttributes.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
transactionAttributes.setProperty("find*", "PROPAGATION_REQUIRED,readOnly");
transactionAttributes.setProperty("*", "PROPAGATION_REQUIRED");
interceptor.setTransactionAttributes(transactionAttributes);
return interceptor;
}
/*
//放这里会导致@value注解获取不到配置的值,移到RootConfig
@Bean
public BeanNameAutoProxyCreator proxycreate(){
BeanNameAutoProxyCreator proxycreate = new BeanNameAutoProxyCreator();
proxycreate.setProxyTargetClass(true);
proxycreate.setBeanNames("*ServiceImpl");
proxycreate.setInterceptorNames("transactionInterceptor");
return proxycreate;
}*/
}
三、再次启动项目,如果正常启动则项目配置dataSource配置正确
第三阶段:测试mybatis继承情况:
一、新建UserDTO 实体类
注:我这里使用lombok 插件,如果没有的话可以下一个或者,自己手动增加get、set方法
package com.study.ssm.entity;
import lombok.Getter;
import lombok.Setter;
/**
* 用户实体类
*
* @author EnzoLuo
* @date 2018/10/22
*/
@Getter
@Setter
public class UserDTO {
private Integer id;
private String name;
private String password;
@Override
public String toString() {
return super.toString();
}
}
二、添加mapper文件:这里注意路径,在DruidDataSourceConfig 会加载进去
<?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.study.ssm.repository.UserRepository"> <resultMap type="com.study.ssm.entity.UserDTO" id="UserResult"> <result column="id" property="id" /> <result column="name" property="name" /> <result column="password" property="password" /> </resultMap> <select id="findById" parameterType="Integer" resultMap="UserResult"> select * from user where id =#{id} </select> <update id="updateUser" parameterType="com.study.ssm.entity.UserDTO"> UPDATE user SET name=#{name} WHERE id=#{id} </update> </mapper>
三、UserRepository
package com.study.ssm.repository; import com.study.ssm.entity.UserDTO; import org.apache.ibatis.annotations.Param; /** * UserRepository * * @author EnzoLuo * @date 2018/10/22 */ public interface UserRepository { UserDTO findById(@Param("id") Integer id); void updateUser(UserDTO userDTO); }
四、UserService和UserServiceImpl
package com.study.ssm.service; import com.study.ssm.entity.UserDTO; /** * UserService * * @author EnzoLuo * @date 2018/10/22 */ public interface UserService { UserDTO findById(Integer id); void updateUserById(UserDTO userDTO); }
package com.study.ssm.service.spring; import com.study.ssm.entity.UserDTO; import com.study.ssm.repository.UserRepository; import com.study.ssm.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * UserServiceImpl * * @author EnzoLuo * @date 2018/10/22 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public UserDTO findById(Integer id) { UserDTO userDTO = userRepository.findById(id); return userDTO; } @Override public void updateUserById(UserDTO userDTO) { userRepository.updateUser(userDTO); } }
五、写一个UserController 测试一下
package com.study.ssm.controller; import com.study.ssm.entity.UserDTO; import com.study.ssm.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * UserController * * @author EnzoLuo * @date 2018/10/22 */ @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/getUserById") public UserDTO getUserById(@RequestParam(name = "id") Integer id) { UserDTO userDTO = userService.findById(id); return userDTO; } @PostMapping("/updateUserById") public String updateUser(){ try{ UserDTO userDTO = new UserDTO(); userDTO.setId(1); userDTO.setName("enzoluo"); userDTO.setPassword("456"); userService.updateUserById(userDTO); }catch(Exception e){ e.printStackTrace(); return "update failed"; } return "update success"; } }
结果:查询
修改:
再次查询:
打完收工,谢谢阅读!
githup出了点问题,稍后会将代码放上去。