1、在resource目錄下新建一個application.properties文件(或者yml文件),命名與位置爲Spring boot默認的配置文件。在文件中記錄着所有的模塊配置內容。例如:Tomcat的端口(默認8080)以及編碼方式等
#設置端口號
server.port=8088
#設置上下文
#server.servlet.context-path=/demo-test
server.tomcat.uri-encoding=utf-8
2、引入本項目中所需要的相關依賴(Oracle連接驅動以及Spring Data JPA,thymeleaf模板引擎)
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
3、在application.properties中配置Oracle數據庫連接信息。
#配置oracle驅動以及數據庫用例
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/test
spring.datasource.username=CORE
spring.datasource.password=APP
4、在application.properties中配置Spring Data JPA。
#配置Spring Data JPA
spring.jpa.database=oracle
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
5、編寫一個實體類User
@Table標籤:指定數據庫中的表名,id配置爲主鍵,生成策略爲字段生成。
package com.example.entity;
import javax.persistence.*;
/**
* 用戶表
*/
@Entity
@Table(name = "TS_USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String password;
private String userName;
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
@Column(name = "USER_NAME")
public void setUserName(String userName) {
this.userName = userName;
}
}
6、基於JPA,實現DAO層(即數據庫數據的增刪改查操作),新建UserRepository.java接口文件。
package com.example.dao;
import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
//正確實例
@Query("select t from User t where t.userName= :userName")
User findByUserName(@Param("userName") String userName);
}
解釋一下:Spring Data JPA提供了很多持久層接口,例如:Repository、CrudRepositoty、PagingAndSortingRepository 以及JpaRepository 接口。其Repository爲基類,JpaRepository繼承PagingAndSortingRepository接口,兩個泛型參數分別代表Java pojo類以及主鍵數據類型。因此在自己的數據庫操作接口時,只需要繼承JPA提供的某一個接口,即可自動繼承相關數據操作方法,而不需要再次實現。
7、設計Service類業務代碼,新建UserService類,其源代碼如下:
package com.example.service;
import com.example.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.entity.User;
import org.springframework.ui.Model;
import java.util.List;
/**
* 業務邏輯層
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User findUserByName(String userName) {
User user = null;
try {
user = userRepository.findByUserName(userName);
} catch (Exception e) {
}
return user;
}
}
8、設計Controller層,新建UserController.java,提供兩個接口,/user/index返回頁面,/user/show返回數據。
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@EnableAutoConfiguration
@RequestMapping(value ="/user")
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value ="/index")
public String index(){
return "user/index";
}
@RequestMapping(value ="/show")
@ResponseBody
public String show(@RequestParam(value = "userName")String name){
User user = userService.findUserByName(name);
if(null!=user){
return user.getId()+"/"+user.getUserName()+"/"+user.getPassword();
}else {
return "null";
}
}
}
9、在application.properties文件中配置頁面引擎。這裏採用SpringMvc(SpringBoot提供thymeleaf、freemarker等)這裏需要配置其靜態資源(css,js,圖片文件等)路徑,以及html頁面文件路徑。參考SpringMvc在Spring下的配置。
#視圖層配置
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/templates/,classpath:/view/,classpath:/public,classpath:/resources,classpath:/META-INF/resources
spring.thymeleaf.prefix = classpath:/templates/
10、在resource目錄下新建templates以及static目錄,分別存放於html文件以及(js,css,圖片)由於在第8點的時候定義了“user/index”頁面,所以在templates目錄下定義一個user目錄,在user目錄中新建index.html頁面。
user/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../../static/scripts/jquery-1.9.1.min.js"></script>
<script src="../../static/scripts/test.js"></script>
<title>title</title>
</head>
<body>
<h1>test page</h1>
</body>
</html>
static/scripts/test.js
$(document).ready(function () {
alert("ok test");
});
11、配置JPA,新建一個Configuration包,用於存放項目配置類,類似SSM架構下,spring需要配置Java POJO類包路徑以及DAO層接口路徑,以及自動掃描相關注解。這裏同樣需要配置這兩項,不同的是Spring採用的是xml配置方式。這裏用java代碼+註解方式配置。新建一個JpaConfiguration.java類。
package com.example.configuration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//代表這個過濾器在衆多過濾器中級別最高,也就是過濾高的時候最先執行
//@Order(Ordered.LOWEST_PRECEDENCE)恰恰相反,表示級別最低,最後執行過濾操作
@Order(Ordered.HIGHEST_PRECEDENCE)
//標註在類上,相當於把該類作爲spring的xml配置文件中的,作用爲:配置spring容器(應用上下文)
@Configuration
//開啓spring事務管理,等同於xml配置方式的 <tx:annotation-driven />(注意:1項目中只需配置一次,2需要配置proxyTargetClass = true)
@EnableTransactionManagement(proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "com.example.dao")
//會自動掃描指定包下的全部標有@Component的類,並註冊成bean
@EntityScan(basePackages = "com.example.entity")
public class JpaConfiguration {
//標註在方法上(返回某個實例的方法),等價於spring的xml配置文件中的,作用爲:註冊bean對象
@Bean
PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
12、配置項目啓動入口。由於我們的工程結構發生改變,需要告訴SpringBoot框架去掃描哪些包從而加載對應類,所以這裏重新編寫main函數,所以這裏重新編寫main函數。新建一個Entry.java類,其代碼如下(其中@SpringBootApplication是一個複合註解,就理解爲自動配置吧):
package com.example.configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
*
*項目啓動入口,配置包根路徑
**/
@SpringBootApplication
@ComponentScan(basePackages = "com.example")
public class Entry {
public static void main(String[] args) throws Exception{
SpringApplication.run(Entry.class,args);
}
}
13、運行main函數,訪問http://localhost:8088/user/index會顯示測試頁面,並彈出alert()。訪問http://localhost:8088/user/show?name=**(數據表裏存在的數據)會顯示user信息。
14、附上整個demo文件目錄
15、搭建過程中遇到的問題:
1.訪問數據庫時,JPA查詢回來爲空。
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
//正確實例
@Query("select t from User t where t.userName= :userName")
User findByUserName(@Param("userName") String userName);
//錯誤實例:
//https://www.cnblogs.com/xiaoluo501395377/p/3376256.html
//原因是:基於投影查詢,返回的是多個值,值實質上是保存在是object[]
@Query("select t.userName as username,t.password as password,t.id as id from User t where t.userName= :userName")
User findByUserName2(@Param("userName") String userName);
//錯誤實例糾正
@Query("select t.userName as username,t.password as password,t.id as id from User t where t.userName= :userName")
Object findByUserName3(@Param("userName") String userName);
@Query("select t from User t")
List<User> findAll();
}
原因:投影存在的是一個object[]數組中,並非是一個user對象 導致沒轉換回來
//www.cnblogs.com/xiaoluo501395377/p/3376256.html