软件环境
eclipse
jdk1.8
maven3.5
mysql5.6
SpringBoot1.5.0
增加一个maven工程
建立对应包名
com.zns.config
com.zns.controller
com.zns.service
com.zns.dao.mapper
com.zns.model
最终文件目录结构为
src/main/javacom.zns.config DruidDataSourceConfig.java MyBatisConfig.java MyBatisMapperScannerConfig.javacom.zns.controller ProductController.javacom.zns.service ProductService.java impl ProductServiceImpl.javacom.zns.dao.mapper ProductMapper.javacom.zns.model Product.javaApplication.javasrc/main/resourcesmybatis mapper ProductMapper.xml mybatis-config.xmlapplication.ymlbanner.txt
pom.xml
org.springframework.boot spring-boot-starter-parent 1.5.0.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-jdbc org.mybatis mybatis 3.2.8 org.mybatis mybatis-spring 1.2.2 com.github.pagehelper pagehelper 4.2.0 tk.mybatis mapper 3.3.0 mysql mysql-connector-java 5.1.34 com.alibaba druid 1.0.20 ${project.artifactId} org.apache.maven.plugins maven-compiler-plugin org.springframework.boot spring-boot-maven-plugin
application.yml
server: port: 8080 context-path: / #mysql数据源和连接池配置 spring: datasource: name: test url: jdbc:mysql://localhost:3306/mydb1 username: root password: 123456 #使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20
DruidDataSourceConfig.java
package com.zns.config;import java.sql.SQLException;import java.util.HashMap;import java.util.Map;import javax.sql.DataSource;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import org.springframework.transaction.PlatformTransactionManager;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;@Configurationpublic class DruidDataSourceConfig { /** * 配置DruidDataSource * * @return */ @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource() { DruidDataSource druidDataSource = new DruidDataSource(); return druidDataSource; } /** * 配置transactionManager * * @return */ @Bean public PlatformTransactionManager transactionManager() throws SQLException { return new DataSourceTransactionManager(druidDataSource()); } /** * 注册DruidServlet * * @return */ @Bean public ServletRegistrationBean druidServletRegistrationBean() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); servletRegistrationBean.setServlet(new StatViewServlet()); servletRegistrationBean.addUrlMappings("/druid/*"); //登录查看信息的账号密码. servletRegistrationBean.addInitParameter("loginUsername", "admin"); servletRegistrationBean.addInitParameter("loginPassword", "123456"); return servletRegistrationBean; } /** * 注册DruidFilter拦截 * * @return */ @Bean public FilterRegistrationBean duridFilterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); MapinitParams = new HashMap (); // 设置忽略请求 initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.setInitParameters(initParams); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; }}
MyBatisConfig.java
package com.zns.config; import javax.sql.DataSource;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver; @Configuration@MapperScan("com.zns.dao.mapper")//mapper扫描包路径public class MyBatisConfig { @Bean @ConditionalOnMissingBean // 当容器里没有指定的Bean的情况下创建该对象 public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // 设置数据源 sqlSessionFactoryBean.setDataSource(dataSource); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 设置mybatis的主配置文件 sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml")); // 设置mybatis的mapper文件路径 sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml")); // 设置别名包 // sqlSessionFactoryBean.setTypeAliasesPackage("com.zns.model"); // 代码方式配置PageHelper插件 /* * PageHelper pageHelper = new PageHelper(); Properties properties = new * Properties(); properties.setProperty("reasonable", "true"); * properties.setProperty("supportMethodsArguments", "true"); * properties.setProperty("returnPageInfo", "check"); * properties.setProperty("params", "count=countSql"); * pageHelper.setProperties(properties); * sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper}); */ return sqlSessionFactoryBean; }}
MyBatisMapperScannerConfig.java
package com.zns.config;import java.util.Properties;import org.springframework.boot.autoconfigure.AutoConfigureAfter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import tk.mybatis.mapper.common.BaseMapper;import tk.mybatis.spring.mapper.MapperScannerConfigurer;@Configuration@AutoConfigureAfter(MyBatisConfig.class)public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean"); // 设置mapper扫描包路径 mapperScannerConfigurer.setBasePackage("com.zns.dao.mapper"); // 继承了BaseMapper接口的才会被扫描 //mapperScannerConfigurer.setMarkerInterface(BaseMapper.class); // 配置通用mapper插件 Properties properties = new Properties(); // 通用mapper包路径 properties.setProperty("mappers", BaseMapper.class.getName()); properties.setProperty("notEmpty", "false"); properties.setProperty("IDENTITY", "MYSQL"); mapperScannerConfigurer.setProperties(properties); return mapperScannerConfigurer; }}
mybatis-config.xml
Product.java
package com.zns.model;import javax.persistence.Column;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Table(name = "product")public class Product { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ProductMapper.java
package com.zns.dao.mapper;import com.github.pagehelper.Page;import com.zns.model.Product;import tk.mybatis.mapper.common.BaseMapper;public interface ProductMapper extends BaseMapper{ public Product getById(Integer id); public Page getPagerList();}
ProductMapper.xml
ProductService.java
package com.zns.service;import com.github.pagehelper.Page;import com.zns.model.Product;public interface ProductService { public Product getById(Integer id); public PagegetPagerList(Integer pageIndex,Integer pageSize); public Product selectByPrimaryKey(Integer id);}
ProductServiceImpl.java
package com.zns.service.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.github.pagehelper.Page;import com.github.pagehelper.PageHelper;import com.zns.dao.mapper.ProductMapper;import com.zns.model.Product;import com.zns.service.ProductService;@Service public class ProductServiceImpl implements ProductService { @Autowired private ProductMapper productMapper; public Product getById(Integer id){ return productMapper.getById(id); } public PagegetPagerList(Integer pageIndex,Integer pageSize){ PageHelper.startPage(pageIndex, pageSize); return productMapper.getPagerList(); } public Product selectByPrimaryKey(Integer id){ return productMapper.selectByPrimaryKey(id); }}
ProductController.java
package com.zns.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.github.pagehelper.Page;import com.zns.model.Product;import com.zns.service.ProductService;@RestController@RequestMapping("/product")public class ProductController { @Autowired private ProductService productService; @RequestMapping("/get") public Product get(Integer id) { System.out.println("id为:" + id); return productService.getById(id); } @RequestMapping("/getPagerList") public Object getPagerList() { PagepageInfo = productService.getPagerList(1, 10); List list = pageInfo.getResult(); long totalCount = pageInfo.getTotal(); for (Product item : list) { System.out.println(item.getId() + "--" + item.getName()); } System.out.println(totalCount); return list; } @RequestMapping("/getByKey") public Product getByKey(Integer id) { System.out.println("id为:" + id); return productService.selectByPrimaryKey(id); }}
项目启动类Application.java
package com.zns;import org.springframework.boot.Banner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ComponentScan;import org.springframework.transaction.annotation.EnableTransactionManagement;@ComponentScan(basePackages="com.zns")@EnableTransactionManagement //如果service实现类中加入事务注解@Transactional,需要此处添加该注解@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication application = new SpringApplication(Application.class); //设置启动时是否显示banner图 application.setBannerMode(Banner.Mode.OFF); application.run(args); }}
浏览器访问测试
http://localhost:8080/product/get?id=1
druid监控后台地址
http://localhost:8080/druid/index.html