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