软件环境
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/java com.zns.config DruidDataSourceConfig.java MyBatisConfig.java MyBatisMapperScannerConfig.java com.zns.controller ProductController.java com.zns.service ProductService.java impl ProductServiceImpl.java com.zns.dao.mapper ProductMapper.java com.zns.model Product.java Application.java src/main/resources mybatis mapper ProductMapper.xml mybatis-config.xml application.yml banner.txt
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- mybatis 包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!--mybatis和spring整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!--mybatis分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.2.0</version> </dependency> <!-- mybatis通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.3.0</version> </dependency> <!-- mysql连接驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <!-- druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.20</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <!-- java编译插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
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; @Configuration public 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()); Map<String, String> initParams = new HashMap<String, String>(); // 设置忽略请求 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
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 返回resultType为map时,如果数据为空的字段,则该字段会省略不显示, 可以通过添加该配置,返回null --> <settings> <setting name="callSettersOnNulls" value="true" /> </settings> <plugins> <!-- 配置分页插件 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 --> <property name="dialect" value="mysql" /> </plugin> </plugins> </configuration>
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<Product> { public Product getById(Integer id); public Page<Product> getPagerList(); }
ProductMapper.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.zns.dao.mapper.ProductMapper"> <select id="getById" parameterType="int" resultType="com.zns.model.Product"> select id,name from product where id=#{id} </select> <select id="getPagerList" resultType="com.zns.model.Product"> select id,name from product </select> </mapper>
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 Page<Product> getPagerList(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 Page<Product> getPagerList(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() { Page<Product> pageInfo = productService.getPagerList(1, 10); List<Product> 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,需要此处添加该注解 @SpringBootApplication public 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