本文原文版权归 CSDN Hgihness 所有,此处为转载+技术收藏,如有再转请自觉于篇头处标明原文作者及出处,这是大家对作者劳动成果的自觉尊重!!

作者:Hgihness

原文:http://blog.csdn.net/javahighness/article/details/53055149

一、maven的pom文件

  1.  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.zsx</groupId>
  6. <artifactId>demo</artifactId>
  7. <packaging>war</packaging>
  8. <version>0.0.1</version>
  9. <name>zsx Maven Webapp</name>
  10. <url>http://maven.apache.org</url>
  11.  
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <jdk.version>1.7</jdk.version>
  15. <tomcat.version>7.0.69</tomcat.version>
  16. </properties>
  17.  
  18. <parent>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-parent</artifactId>
  21. <version>1.4.0.RELEASE</version>
  22. </parent>
  23.  
  24. <dependencies>
  25.  
  26. <!-- 添加对jsp视图解析的支持 -->
  27. <dependency>
  28. <groupId>org.apache.tomcat.embed</groupId>
  29. <artifactId>tomcat-embed-jasper</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>javax.servlet</groupId>
  33. <artifactId>jstl</artifactId>
  34. </dependency>
  35.  
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-web</artifactId>
  39. </dependency>
  40.  
  41. <!-- 下面两个引入为了操作数据库 -->
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-data-jpa</artifactId>
  45. </dependency>
  46. <dependency>
  47. <groupId>mysql</groupId>
  48. <artifactId>mysql-connector-java</artifactId>
  49. </dependency>
  50.  
  51. <dependency>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-starter-tomcat</artifactId>
  54. <scope>provided</scope>
  55. </dependency>
  56.  
  57. <!-- 只需引入spring-boot-devtools 即可实现热部署 -->
  58. <dependency>
  59. <groupId>org.springframework.boot</groupId>
  60. <artifactId>spring-boot-devtools</artifactId>
  61. </dependency>
  62.  
  63. <!-- Json包 -->
  64. <dependency>
  65. <groupId>com.alibaba</groupId>
  66. <artifactId>fastjson</artifactId>
  67. <version>1.2.16</version>
  68. </dependency>
  69.  
  70. <!-- 为了监控数据库 -->
  71. <dependency>
  72. <groupId>com.alibaba</groupId>
  73. <artifactId>druid</artifactId>
  74. <version>1.0.25</version>
  75. </dependency>
  76.  
  77. <dependency>
  78. <groupId>org.apache.poi</groupId>
  79. <artifactId>poi</artifactId>
  80. <version>3.14</version>
  81. </dependency>
  82.  
  83. <!-- Junit 单元测试 -->
  84. <dependency>
  85. <groupId>org.springframework.boot</groupId>
  86. <artifactId>spring-boot-starter-test</artifactId>
  87. <scope>test</scope>
  88. </dependency>
  89.  
  90. <dependency>
  91. <groupId>io.springfox</groupId>
  92. <artifactId>springfox-swagger2</artifactId>
  93. <version>2.6.0</version>
  94. </dependency>
  95. <dependency>
  96. <groupId>io.springfox</groupId>
  97. <artifactId>springfox-swagger-ui</artifactId>
  98. <version>2.6.0</version>
  99. </dependency>
  100.  
  101. </dependencies>
  102. <build>
  103. <finalName>/</finalName>
  104.  
  105. <plugins>
  106.  
  107. <plugin>
  108. <groupId>org.springframework.boot</groupId>
  109. <artifactId>spring-boot-maven-plugin</artifactId>
  110. <dependencies>
  111. <!-- 热部署 -->
  112. <dependency>
  113. <groupId>org.springframework</groupId>
  114. <artifactId>springloaded</artifactId>
  115. <version>1.2.6.RELEASE</version>
  116. </dependency>
  117. </dependencies>
  118. </plugin>
  119.  
  120. </plugins>
  121.  
  122. </build>
  123.  
  124. <repositories>
  125. <repository>
  126. <id>ali</id>
  127. <name>ali Repository</name>
  128. <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  129. <snapshots>
  130. <enabled>false</enabled>
  131. </snapshots>
  132. </repository>
  133. </repositories>
  134. </project>
  1.  

  

  1.  

二、项目架构

想想还是介绍一下项目的目录结构,这样方便梳理整体的架构配置

  1.  
  1. src
  2. ├─main
  3. ├─java
  4. └─com
  5. └─zsx
  6. Application.java
  7. SpringBootStartApplication.java

  8. ├─common
  9. ├─config
  10. DruidDBConfig.java
  11. MultipartConfig.java

  12. ├─filter
  13. DruidStatFilter.java

  14. ├─interceptors
  15. AuthInterceptor.java
  16. WebAppConfigurer.java

  17. ├─servlet
  18. DruidStatViewServlet.java

  19. └─swagger
  20. Swagger2.java

  21. ├─controller
  22. LoginController.java
  23. TestController.java
  24. UserController.java

  25. ├─dao
  26. TUserDao.java

  27. └─impl
  28. ├─entity
  29. BaseEntity.java

  30. ├─model
  31. Tree.java

  32. ├─service
  33. UserService.java

  34. └─impl
  35. UserServiceImpl.java

  36. └─util
  37. GeneratePageable.java

  38. ├─resources
  39. application.properties
  40. logback-test.xml

  41. └─static
  42. ├─css
  43. ├─img
  44. └─js

  45. └─webapp
  46. index.jsp

  47. └─WEB-INF
  48. web.xml

  49. └─view
  50. login.jsp

  51. ├─error
  52. 500.jsp
  53. ├─jsp
  54. main.jsp

  55. └─test
  56. └─java
  57. UtilTest.java
  1.  

  

  1.  

标准的maven项目结构,其中Java下是daoservicecontroller ,还有实体类映射entity,其他配置config

三、resources下的应用配置文件application.properties

  1.  
  1. #server.port=9090
  2.  
  3. # 数据库访问配置
  4. # 主数据源,默认的
  5. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  6. spring.datasource.url=jdbc:mysql://localhost:3306/test
  7. spring.datasource.username= root
  8. spring.datasource.password= root
  9. spring.datasource.driverClassName = com.mysql.jdbc.Driver
  10.  
  11. # 下面为连接池的补充设置,应用到上面所有数据源中
  12. # 初始化大小,最小,最大
  13. spring.datasource.initialSize=5
  14. spring.datasource.minIdle=5
  15. spring.datasource.maxActive=20
  16. # 配置获取连接等待超时的时间
  17. spring.datasource.maxWait=60000
  18. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  19. spring.datasource.timeBetweenEvictionRunsMillis=60000
  20. # 配置一个连接在池中最小生存的时间,单位是毫秒
  21. spring.datasource.minEvictableIdleTimeMillis=300000
  22. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  23. spring.datasource.testWhileIdle=true
  24. spring.datasource.testOnBorrow=false
  25. spring.datasource.testOnReturn=false
  26. # 打开PSCache,并且指定每个连接上PSCache的大小
  27. spring.datasource.poolPreparedStatements=true
  28. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  29. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  30. spring.datasource.filters=stat,wall,log4j
  31. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  32. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  33. # 合并多个DruidDataSource的监控数据
  34. spring.datasource.useGlobalDataSourceStat=true
  35.  
  36. #JPA Configuration:
  37. spring.jpa.database=MYSQL
  38. # Show or not log for each sql query
  39. spring.jpa.show-sql=false
  40. spring.jpa.generate-ddl=true
  41. # Hibernate ddl auto (create, create-drop, update)
  42. spring.jpa.hibernate.ddl-auto=create
  43. #spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
  44. spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
  45. #spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect
  46. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
  47.  
  48. spring.mvc.view.prefix=/WEB-INF/view/
  49. spring.mvc.view.suffix=.jsp
  50. #spring.resources.static-locations=classpath:/resources/,classpath:/static/
  1.  

  

  1.  

四、启动应用主类文件 Application.java

  1. package com.zsx;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.boot.web.servlet.ServletComponentScan;
  5.  
  6. @SpringBootApplication
  7. @ServletComponentScan // 扫描使用注解方式的servlet
  8. public class Application {
  9.  
  10. public static void main(String[] args) {
  11. SpringApplication.run(Application.class, args);
  12. }
  13. }
  14. 若需要部署到外部的tomcat容器中,则添加下面类即可。
  15.  
  16. package com.zsx;
  17.  
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import org.springframework.boot.SpringApplication;
  21. import org.springframework.boot.builder.SpringApplicationBuilder;
  22. import org.springframework.boot.context.web.SpringBootServletInitializer;
  23. /**
  24. * 修改启动类,继承 SpringBootServletInitializer 并重写 configure 方法
  25. * @author ZSX
  26. *
  27. */
  28. public class SpringBootStartApplication extends SpringBootServletInitializer {
  29.  
  30. private static final Logger logger = LoggerFactory.getLogger(SpringBootStartApplication.class);
  31.  
  32. @Override
  33. protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  34. return builder.sources(Application.class);
  35. }
  36.  
  37. }

  

五、数据库连接池Druid的配置

  1. package com.zsx.common.config;
  2.  
  3. import java.sql.SQLException;
  4.  
  5. import javax.sql.DataSource;
  6.  
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.Primary;
  11.  
  12. import com.alibaba.druid.pool.DruidDataSource;
  13.  
  14. /**
  15. * DruidDBConfig类被@Configuration标注,用作配置信息;
  16. * DataSource对象被@Bean声明,为Spring容器所管理,
  17. * @Primary表示这里定义的DataSource将覆盖其他来源的DataSource。
  18. * @author ZSX
  19. *jdbc.url=${jdbc.url}
  20. *最新的支持方式如下:
  21. *jdbc.url=@jdbc.url@
  22. */
  23. @Configuration
  24. public class DruidDBConfig {
  25. // private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
  26.  
  27. @Value("${spring.datasource.url}")
  28. private String dbUrl;
  29.  
  30. @Value("${spring.datasource.username}")
  31. private String username;
  32.  
  33. @Value("${spring.datasource.password}")
  34. private String password;
  35.  
  36. @Value("${spring.datasource.driverClassName}")
  37. private String driverClassName;
  38.  
  39. @Value("${spring.datasource.initialSize}")
  40. private int initialSize;
  41.  
  42. @Value("${spring.datasource.minIdle}")
  43. private int minIdle;
  44.  
  45. @Value("${spring.datasource.maxActive}")
  46. private int maxActive;
  47.  
  48. @Value("${spring.datasource.maxWait}")
  49. private int maxWait;
  50.  
  51. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  52. private int timeBetweenEvictionRunsMillis;
  53.  
  54. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  55. private int minEvictableIdleTimeMillis;
  56.  
  57. @Value("${spring.datasource.validationQuery}")
  58. private String validationQuery;
  59.  
  60. @Value("${spring.datasource.testWhileIdle}")
  61. private boolean testWhileIdle;
  62.  
  63. @Value("${spring.datasource.testOnBorrow}")
  64. private boolean testOnBorrow;
  65.  
  66. @Value("${spring.datasource.testOnReturn}")
  67. private boolean testOnReturn;
  68.  
  69. @Value("${spring.datasource.poolPreparedStatements}")
  70. private boolean poolPreparedStatements;
  71.  
  72. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  73. private int maxPoolPreparedStatementPerConnectionSize;
  74.  
  75. @Value("${spring.datasource.filters}")
  76. private String filters;
  77.  
  78. @Value("{spring.datasource.connectionProperties}")
  79. private String connectionProperties;
  80.  
  81. @Bean // 声明其为Bean实例
  82. @Primary // 在同样的DataSource中,首先使用被标注的DataSource
  83. public DataSource dataSource() {
  84. DruidDataSource datasource = new DruidDataSource();
  85.  
  86. datasource.setUrl(this.dbUrl);
  87. datasource.setUsername(username);
  88. datasource.setPassword(password);
  89. datasource.setDriverClassName(driverClassName);
  90.  
  91. // configuration
  92. datasource.setInitialSize(initialSize);
  93. datasource.setMinIdle(minIdle);
  94. datasource.setMaxActive(maxActive);
  95. datasource.setMaxWait(maxWait);
  96. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  97. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  98. datasource.setValidationQuery(validationQuery);
  99. datasource.setTestWhileIdle(testWhileIdle);
  100. datasource.setTestOnBorrow(testOnBorrow);
  101. datasource.setTestOnReturn(testOnReturn);
  102. datasource.setPoolPreparedStatements(poolPreparedStatements);
  103. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  104. try {
  105. datasource.setFilters(filters);
  106. } catch (SQLException e) {
  107.  
  108. }
  109. datasource.setConnectionProperties(connectionProperties);
  110.  
  111. return datasource;
  112. }
  113. }
  114. springboot里默认使用tomcat的上传文件大小限制,即1MB
  115. 修改用下面的配置类:
  116.  
  117. import javax.servlet.MultipartConfigElement;
  118.  
  119. import org.springframework.boot.web.servlet.MultipartConfigFactory;
  120. import org.springframework.context.annotation.Bean;
  121. import org.springframework.context.annotation.Configuration;
  122.  
  123. @Configuration
  124. public class MultipartConfig {
  125.  
  126. @Bean
  127. public MultipartConfigElement multipartConfigElement(){
  128. MultipartConfigFactory factory = new MultipartConfigFactory();
  129. factory.setMaxFileSize("10MB");
  130. factory.setMaxRequestSize("10MB");
  131. return factory.createMultipartConfig();
  132. }
  133.  
  134. }

  

六、开启Druid的数据库监控配置

  • 1、配置Filter

    1.  
    1. import javax.servlet.annotation.WebFilter;
    2. import javax.servlet.annotation.WebInitParam;
    3.  
    4. import com.alibaba.druid.support.http.WebStatFilter;
    5.  
    6. /**
    7. * 配置druid监控统计功能
    8. * 配置Filter
    9. * @author ZSX
    10. *
    11. */
    12.  
    13. @WebFilter(filterName = "druidWebStatFilter", urlPatterns = "/*",
    14. initParams = {
    15. @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
    16. }
    17. )
    18.  
    19. public class DruidStatFilter extends WebStatFilter {
    20.  
    21. }
    1.  

      

    1.  
  • 2、 配置web访问的servlet

    1.  
    1. import javax.servlet.annotation.WebInitParam;
    2. import javax.servlet.annotation.WebServlet;
    3.  
    4. import com.alibaba.druid.support.http.StatViewServlet;
    5.  
    6. /**
    7. * 配置druid监控统计功能
    8. * 在SpringBoot项目中基于注解的配置,如果是web.xml配置,按规则配置即可
    9. * @author ZSX
    10. *
    11. */
    12.  
    13. @WebServlet(urlPatterns = "/druid/*",
    14. initParams = {
    15. // @WebInitParam(name = "allow", value = "192.168.16.110,127.0.0.1"), // IP白名单 (没有配置或者为空,则允许所有访问)
    16. // @WebInitParam(name="deny",value="192.168.16.111"), // IP黑名单 (存在共同时,deny优先于allow)
    17. @WebInitParam(name="loginUsername",value="druid"),// 用户名
    18. @WebInitParam(name="loginPassword",value="druid"),// 密码
    19. @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
    20. }
    21. )
    22. public class DruidStatViewServlet extends StatViewServlet {
    23.  
    24. }
    1.  

      

    1.  

这样启动项目后在浏览器中输入地址:端口/druid,就可以看到druid的监控web页面了

七、 拦截器配置

  1.  
  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  3. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  5.  
  6. @Configuration
  7. public class WebAppConfigurer extends WebMvcConfigurerAdapter {
  8.  
  9. /**
  10. * 配置拦截器
  11. */
  12. @Override
  13. public void addInterceptors(InterceptorRegistry registry) {
  14. // TODO Auto-generated method stub
  15. // 多个拦截器组成一个拦截器链
  16. // addPathPatterns 用于添加拦截规则
  17. // excludePathPatterns 用户排除拦截
  18.  
  19. registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**");
  20.  
  21. super.addInterceptors(registry);
  22. }
  23.  
  24. /**
  25. * 添加自定义的静态资源映射
  26. 这里使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。
  27. */
  28. @Override
  29. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  30.  
  31. // registry.addResourceHandler("/new/**").addResourceLocations("classpath:/new/");
  32. // registry.addResourceHandler("/**").addResourceLocations("/");
  33. super.addResourceHandlers(registry);
  34. }
  35.  
  36. }
  1.  

  

  1.  

八、swagger发布api测试配置(可忽略)

  1.  
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3.  
  4. import springfox.documentation.builders.ApiInfoBuilder;
  5. import springfox.documentation.builders.PathSelectors;
  6. import springfox.documentation.builders.RequestHandlerSelectors;
  7. import springfox.documentation.service.ApiInfo;
  8. import springfox.documentation.spi.DocumentationType;
  9. import springfox.documentation.spring.web.plugins.Docket;
  10. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  11.  
  12. @Configuration
  13. @EnableSwagger2
  14. public class Swagger2 {
  15.  
  16. @Bean
  17. public Docket createRestApi(){
  18. return new Docket(DocumentationType.SWAGGER_2)
  19. .apiInfo(apiInfo())
  20. .select()
  21. .apis(RequestHandlerSelectors.basePackage("com.zsx.controller.api"))
  22. .paths(PathSelectors.any())
  23. .build();
  24. }
  25.  
  26. private ApiInfo apiInfo(){
  27. return new ApiInfoBuilder()
  28. .title("Spring Boot中使用Swagger2构建RESTful APIs")
  29. .description("描述")
  30. .termsOfServiceUrl("http://zsx.com.cn")
  31. .version("1.0")
  32. .build();
  33. }
  34.  
  35. }
  1.  

  

  1.  

至此,所有的配置已完成,下面是一个操作数据的简单demo

九、实体类

  1.  
  1. @Entity
  2. @Table(name = "t_user")
  3. public class Tuser implements java.io.Serializable {
  4.  
  5. /**
  6. *
  7. */
  8. private static final long serialVersionUID = 1L;
  9.  
  10. @Id
  11. @GeneratedValue(strategy=GenerationType.IDENTITY)
  12. private Long id;
  13.  
  14. @Column(name = "username")
  15. private String userName;
  16.  
  17. @Column(name = "password")
  18. private String passWord;
  19.  
  20. @Column(name = "email")
  21. private String email;
  22.  
  23. @Column(name = "mobile")
  24. private String mobile;
  25.  
  26. @Column(name = "nickname")
  27. private String nickName;
  28.  
  29. // 省略getter 和 setter
  30.  
  31. }
  1.  

  

  1.  

十、dao层

1、使用jpa基本可以实现不写sql,(但实际开发中,业务逻辑会很复杂,一点不写sql完全不现实)

2、注意添加@Repository注解, 添加JpaSpecificationExecutor继承可以方便分页

3、 看些jpa的查询语法资料

  1.  
  1. import java.util.List;
  2. import java.util.Map;
  3.  
  4. import org.springframework.data.domain.Pageable;
  5. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  6. import org.springframework.data.jpa.repository.Query;
  7. import org.springframework.data.repository.PagingAndSortingRepository;
  8. import org.springframework.data.repository.query.Param;
  9. import org.springframework.stereotype.Repository;
  10.  
  11. @Repository
  12. public interface TuserDao extends PagingAndSortingRepository<Tuser, Long>, JpaSpecificationExecutor<Tuser> {
  13.  
  14. Tuser findByUserName(String userName);
  15.  
  16. @Query("from Tuser t where id = :id")
  17. List<Tuser> queryFamilyList(@Param("id") Long id, Pageable pageable);
  18.  
  19. }
  1.  

  

  1.  

十一、service和controller没啥好说的,跟原先的一样,下面再提供一个单元测试的demo

  1.  
  1. import java.util.List;
  2. import javax.persistence.EntityManager;
  3.  
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.SpringApplicationConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. import org.springframework.test.context.web.WebAppConfiguration;
  10.  
  11. import com.alibaba.fastjson.JSON;
  12. import com.golden.Application;
  13. import com.golden.dao.TUserDao;
  14. import com.golden.entity.Tuser;
  15. import com.golden.util.GeneratePageable;
  16.  
  17. @RunWith(SpringJUnit4ClassRunner.class)
  18.  
  19. //指定我们SpringBoot工程的Application启动类
  20. @SpringApplicationConfiguration(classes = Application.class)
  21.  
  22. //由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration
  23. @WebAppConfiguration
  24. public class UtilTest {
  25.  
  26. @Autowired
  27. private TUserDao dao;
  28.  
  29. @Autowired
  30. private EntityManager em;
  31.  
  32. @Test
  33. public void test1(){
  34. dao.findByUserName("admin");
  35. }
  36.  
  37. @Test
  38. public void test2(){
  39. // 使用jpa提供的分页类
  40. java.util.List<Order> list = new ArrayList<Sort.Order>();
  41. Order order = new Order(Direction.DESC, "createTime");
  42.  
  43. list.add(order);
  44.  
  45. Sort sort = new Sort(list);
  46.  
  47. Pageable pageable = new PageRequest(0, 10, sort);
  48.  
  49. Page<Tuser> findAll = dao.findAll(pageable);
  50.  
  51. }
  52.  
  53. @Test
  54. public void test3(){
  55.  
  56. EntityManager em = dao.getEntityManager();
  57. Query query = em.createNativeQuery("select * from t_user limit 1");
  58. Object singleResult = query.getSingleResult();
  59. System.out.println(singleResult);
  60. }
  61.  
  62. /*
  63. //执行原生SQL
  64. Query nativeQuery = em.createNativeQuery(String sql);
  65. //指定返回对象类型
  66. nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean( Class resultType));
  67. //返回对象
  68. List<T> resultList = nativeQuery.getResultList();
  69. */
  70. }
  1.  

  

  1.  

后记:

  • 不用Druid的可以把有关Druid的配置全部删掉,swagger的同理

  • 这里没有使用hibernate.cfg.xml配置文件,主要习惯了在实体类里配置字段了,不怎么用hibernate的映xml文件了,但其实配置起来跟springmvc项目一样

  • 说实话这里使用jpa操作数据库,没感觉有多方便,因为总有各种奇葩的需求,当然也可能是我没深入研究,所以建议改用Mybatis,这个我会再写一篇springboot加mybatis的配置教程的,最后,还可以使用原生的sql查询,即使用单元测试里的EntityManager对象去执行sql,返回结果可以指定对象类型,也很方便

  • 还需要注意的一个点是静态文件的存放位置,这个跟原先的项目不一样,原先是在webapp下,但springboot是默认放在resources下的static目录下的,还有其他默认目录和配置,自行搜索

  • 时间仓促,以后再补充

Spring Boot 中使用 jpa的更多相关文章

  1. 初识在Spring Boot中使用JPA

    前面关于Spring Boot的文章已经介绍了很多了,但是一直都没有涉及到数据库的操作问题,数据库操作当然也是我们在开发中无法回避的问题,那么今天我们就来看看Spring Boot给我们提供了哪些疯狂 ...

  2. 使用spring boot中的JPA操作数据库

    前言 Spring boot中的JPA 使用的同学都会感觉到他的强大,简直就是神器一般,通俗的说,根本不需要你写sql,这就帮你节省了很多时间,那么下面我们来一起来体验下这款神器吧. 一.在pom中添 ...

  3. Spring Boot中使用Jpa的findOne方法不能传入id

    最近通过慕课网学习spring boot,视频中通过jpa的findOne方法以id为参数查询出对应的信息, 而当我自己做测试的时候却发现我的findOne方法的参数没有Integer类型的id,而是 ...

  4. spring boot 中使用 jpa以及jpa介绍

    1.什么是jpa呢?JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中.12.jpa具有什么 ...

  5. spring boot中注入jpa时报could not autowire.No beans of 'PersonRepository' type found

    解决方法,在repository加一个注解.如下图所示: @Component

  6. Spring boot中应用jpa jpa用法

    https://blog.csdn.net/u012582402/article/details/78717705

  7. 在Spring Boot中使用数据缓存

    春节就要到了,在回家之前要赶快把今年欠下的技术债还清.so,今天继续.Spring Boot前面已经预热了n篇博客了,今天我们来继续看如何在Spring Boot中解决数据缓存问题.本篇博客是以初识在 ...

  8. 在Spring Boot中使用数据库事务

    我们在前面已经分别介绍了如何在Spring Boot中使用JPA(初识在Spring Boot中使用JPA)以及如何在Spring Boot中输出REST资源(在Spring Boot中输出REST资 ...

  9. 在Spring Boot中输出REST资源

    前面我们我们已经看了Spring Boot中的很多知识点了,也见识到Spring Boot带给我们的各种便利了,今天我们来看看针对在Spring Boot中输出REST资源这一需求,Spring Bo ...

随机推荐

  1. JSP中系统Date的几点不符合中国时间观的地方

    正常调用系统时间的显示格式是Date date = new Date 显示出来的当前时间为Sun Nov 22 18:39:51 CST 2015 星期天的英文单词是Sun, 这个大家都是熟悉的, 这 ...

  2. svn版本分支及冲突解决笔记

    转载:http://blog.csdn.net/xuguiyi100/article/details/51966557 分支合并主干示例 1.主干工程右键选择merge合并下一步 2.选中merge ...

  3. mybatis框架入门程序:演示通过mybatis实现数据库的模糊查询操作

    1. mybatis的基本准备操作见我的上一篇博文:https://www.cnblogs.com/wyhluckdog/p/10149480.html 2. 根据用户名查询用户信息: (1)映射文件 ...

  4. Golang之匿名函数和闭包

    Go语言支持匿名函数,即函数可以像普通变量一样被传递或使用. 使用方法如下: main.go package main import ( "fmt" ) func main() { ...

  5. Java 设计模式系列(二十)状态模式

    Java 设计模式系列(二十)状态模式 状态模式,又称状态对象模式(Pattern of Objects for States),状态模式是对象的行为模式.状态模式允许一个对象在其内部状态改变的时候改 ...

  6. HDU 6065 RXD, tree and sequence (LCA+DP)

    题意:给定上一棵树和一个排列,然后问你把这个排列分成m个连续的部分,每个部分的大小的是两两相邻的LCA的最小深度,问你最小是多少. 析:首先这个肯定是DP,然后每个部分其实就是里面最小的那个LCA的深 ...

  7. 使用electron-packager electron-builder electron-updater 打包vue项目,支持在线更新

    1.如何用electron-packager electron-builder打包vue项目,打包成桌面程序. 步骤一. 执行npm run build 打包你的vue项目. 打包成功后,生成dist ...

  8. .NET基础 (20).NET中的数据库开发

    ADO NET和数据库程序基础1 什么是关系型数据库2 如何通过SQL语句来实现行列转换3 ADO NET支持哪几种数据源 ADO NET和数据库的连接1 请简要叙述数据库连接池的机制2 如何提高连接 ...

  9. Vivado 2017封装自定义IP Core

    使用Vivado2017.3自定义IP Core.通常情况下,我们做设计采用模块化设计,对于已经设计好的一部分模块功能,就可以直接拿来调用,IP Core就是这样来的,一般来说我们看不到IP Core ...

  10. 第二周leetcode

    4/4 这周莫名得忙,一天是做编译,一天是做模式识别作业,(一天刷魔兽皮肤),周末玩了两天,总的来说还是松懈了,大概只做了两天的leetcode,刷了10道题,羞愧羞愧. 决定每次把代码附上在这个总结 ...