Spring Boot 整合 Spring Data JPA
Spring Data JPA 是 Spring Data ?家族的?员
JPA 和 Spring Data JPA 的关系
JPA (Java Persistence API)Java 持久层规范,定义了?系列 ORM 接?,它本身是不能直接使?,接 ?必须实现才能使?,Hibernate 框架就是?个实现了 JPA 规范的框架。 Spring Data JPA 是 Spring 框架提供的对 JPA 规范的抽象,通过约定的命名规范完成持久层接?的编写,在不需要实现接?的情况下,就可以完成对数据库的操作。 简单理解,通过 Spring Data JPA 只需要定义接??不需要实现,就能完成 CRUD 操作。 Spring Data JPA 本身并不是?个具体的实现,它只是?个抽象层,底层还是需要 Hibernate 这样的 JPA来提供?持。
Spring Data JPA 和 Spring JdbcTemplate 的关系
Spring JdbcTemplate 是 Spring 框架提供的?套操作数据库的模版,Spring Data JPA 是 JPA 的抽象。
- pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- 实体类,完成实体类与数据表的映射
package com.southwind.jpa.entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity(name = "t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String username;
@Column
private String password;
@Column
private Integer age; }
- ?@Entity 将实体类与数据表进?映射
- ?@Id 将实体类中的成员变量与数据表的主键进?映射,?般都是 id
- ?@GeneratedValue 表示?动?成主键,strategy 为主键选择?成策略
- ?@Column 将实体类中的成员变量与数据表的普通字段进?映射
- 创建 UserRepository
package com.southwind.jpa.repository;
import com.southwind.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> {
}
- 创建Handler
package com.southwind.controller.jpa;
import com.southwind.jpa.entity.User;
import com.southwind.jpa.repository.JpaUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController("/jpaHandler")
@RequestMapping("/jpauser")
public class UserHandler {
@Autowired
private JpaUserRepository userRepository;
@GetMapping("/findAll")
public List<User> findAll(){
return userRepository.findAll();
}
@GetMapping("/findById/{id}")
public User findById(@PathVariable("id") Integer id){
return userRepository.findById(id).get();
}
@PostMapping("/save")
public void save(@RequestBody User user){
userRepository.save(user);
}
@PutMapping("/update")
public void update(@RequestBody User user){
userRepository.save(user);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") Integer id){
userRepository.deleteById(id);
}
}
- application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?
useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
jpa:
show-sql: true
properties:
hibernate:
format_sql: true
- 在继承 JpaRepsitory 的基础上,开发者也可以?定义?法。
@GetMapping("/findByUserName/{username}")
public User findByUserName(@PathVariable("username") String username){
return userRepository.findByUsername(username);
}
Spring Boot 整合 Spring Security
- 创建 Maven ?程,pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
- Handler
package com.southwind.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SecurityHandler {
@GetMapping("/index")
public String index(){
return "index";
}
}
- HTML
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Title</title>
</head> <body>
<p>index</p>
<form method="post" action="/logout">
<input type="submit" value="退出"/>
</form>
</body>
</html>
- application.yml
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
- Application
package com.southwind;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
输??户名、密码才可以进?访问,默认的?户名是 user,密码是启动 Spring Security ?动?成的随机密码。
?定义?户密码
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
security:
user:
name: admin
password: 123123
权限管理
定义两个资源
- ?index.html
- ?admin.html
定义两个?? - ?ADMIN 访问 index.html 和 admin.html
- ?USER 访问 index.html
- 创建 SecurityConfig类
package com.southwind.config;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.Authent
icationManagerBuilder;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecu
rity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityCo
nfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/index").access("hasRole('ADMIN') or
hasRole('USER')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.csrf()
.disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
.withUser("user").password(new MyPasswordEncoder()
.encode("000")).roles("USER")
.and()
.withUser("admin").password(new MyPasswordEncoder()
.encode("123")).roles("ADMIN","USER");
}
}
- ?定义 MyPassowrdEncoder
package com.southwind.config;
import org.springframework.security.crypto.password.PasswordEncoder;
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
- Handler
package com.southwind.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SecurityHandler {
@GetMapping("/index")
public String index(){
return "index";
}
@GetMapping("/admin")
public String admin(){
return "admin";
}
@GetMapping("/login")
public String login(){
return "login";
}
}
- login.html
<!DOCTYPE html>
<html lang="en"> <html xmlns:th="http://www.thymeleaf.org"> <head>
<meta charset="UTF-8">
<title>Title</title>
</head> <body>
<p th:if="${param.error}">
?户名或密码错误
</p>
<form th:action="@{/login}" method="post">
?户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
- index.html
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Title</title>
</head> <body>
<p>欢迎回来</p>
<form method="post" action="/logout">
<input type="submit" value="退出"/>
</form>
</body>
</html>
- admin.html
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>Title</title>
</head> <body>
<p>后台管理系统</p>
<form method="post" action="/logout">
<input type="submit" value="退出"/>
</form>
</body>
</html>
|