博客
关于我
Spring Security集成Spring Data Jpa
阅读量:779 次
发布时间:2019-03-24

本文共 8643 字,大约阅读时间需要 28 分钟。

如何将用户数据存入数据库并使用Spring Data Jpa进行操作

1. 启动MySQL并创建数据库

首先,启动MySQL客户端并执行以下命令创建数据库:

mysql -u root -p

输入密码后,执行以下命令创建数据库:

CREATE DATABASE test;

2. 创建Spring Boot项目并添加必要依赖

创建一个新Spring Boot项目,添加以下依赖到项目的 pom.xml 中:

org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
runtime

3. 配置数据库连接信息

在应用.properties 文件中添加以下配置:

spring.datasource.username=rootspring.datasource.password=rootsspring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=falsespring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverjpa.hibernate.ddl-auto=updatejpa.show-sql=truejpa.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

4. 创建实体类

User 实体类

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import org.springframework.security.core.userdetails.UserDetails;@Entity(name = "t_user")public class User implements UserDetails {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    private String username;    private String password;    private boolean accountNonExpired = true;    private boolean accountNonLocked = true;    private boolean credentialsNonExpired = true;    private boolean enabled = true;    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)    private List
roles; @Override public String getUsername() { return username; } @Override public String getPassword() { return password; } @Override public boolean isAccountNonExpired() { return accountNonExpired; } @Override public boolean isAccountNonLocked() { return accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired; } @Override public boolean isEnabled() { return enabled; } @Override public Collection
getAuthorities() { List
authorities = new ArrayList<>(); for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return authorities; }}

Role 实体类

import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entity(name = "t_role")public class Role {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    private String name;    private String nameZh;    // Getters and Setters omitted for brevity}

5. 创建DAO和Service接口

UserDao 接口

import com.example.domain.User;import org.springframework.data.jpa.repository.JpaRepository;public interface UserDao extends JpaRepository
{ User findUserByUsername(String username);}

UserService implementing UserDetailsService

import com.example.dao.UserDao;import com.example.domain.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;@Servicepublic class UserService implements UserDetailsService {    @Autowired    private UserDao userDao;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        User user = userDao.findUserByUsername(username);        if (user == null) {            throw new UsernameNotFoundException("Username not found");        }        return user;    }}

6. 安全配置

SecurityConfig

import com.example.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.password.NoOpPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import java.io.PrintWriter;@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {    @Autowired    private UserService userService;    @Bean    public PasswordEncoder passwordEncoder() {        return NoOpPasswordEncoder.getInstance();    }    @Override    protected void configure(AuthenticationManagerBuilder auth) throws Exception {        auth.userDetailsService(userService);    }    @Override    public void configure(WebSecurity web) {        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");    }    @Override    protected void configure(HttpSecurity http) throws Exception {        http.authorizeRequests()                .antMatchers("/admin/**").hasRole("admin")                .antMatchers("/user/**").hasRole("user")                .anyRequest().authenticated()                .and()                .formLogin()                .loginPage("/login.html")                .loginProcessingUrl("/doLogin")                .successHandler((req, resp, authentication) -> {                    Object principal = authentication.getPrincipal();                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write(new ObjectMapper().writeValueAsString(principal));                    out.flush();                    out.close();                })                .failureHandler((req, resp, e) -> {                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write(e.getMessage());                    out.flush();                    out.close();                })                .permitAll()                .and()                .logout()                .logoutUrl("/logout")                .logoutSuccessHandler((req, resp, authentication) -> {                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write("Logout successful");                    out.flush();                    out.close();                })                .permitAll()                .and()                .csrf().disable()                .exceptionHandling()                .authenticationEntryPoint((req, resp, authException) -> {                    resp.setContentType("application/json;charset=utf-8");                    PrintWriter out = resp.getWriter();                    out.write("Please login first");                    out.flush();                    out.close();                });    }}

7. 测试类

UserDaoTest

import com.example.domain.Role;import com.example.domain.User;import org.junit.Test;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import static org.junit.Assert.*;@RunWith(SpringRunner.class)@SpringBootTestpublic class UserDaoTest {    @Autowired    private UserDao userDao;    @Test    public void insertUser() {        User user = new User();        user.setUsername("testuser");        user.setPassword("testpass");        user.setEnabled(true);                List
roles = new ArrayList<>(); Role role = new Role(); role.setName("ROLE_regular"); role.setNameZh("普通用户"); roles.add(role); user.setRoles(roles); userDao.save(user); assertEquals("testuser", userDao.findUserByUsername("testuser").getUsername()); }}

8. 测试接口

HelloController

import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController {    @GetMapping("/hello")    public String sayHello() {        return "Welcome to our application";    }    @GetMapping("/admin/hello")    public String sayHelloForAdmin() {        return "Hello, Admin!";    }    @GetMapping("/user/hello")    public String sayHelloForUser() {        return "Hello, User!";    }}

总结

通过以上步骤,我们成功将用户数据存入MySQL数据库,并使用Spring Data Jpa进行数据库操作。用户和角色之间建立了多对多关系,实现了用户的 CRUD 操作和权限管理。接下来可以根据项目需求添加更多功能,比如用户注册、角色管理等。

转载地址:http://gdvkk.baihongyu.com/

你可能感兴趣的文章
Mysql 自定义函数
查看>>
mysql 行转列 列转行
查看>>
Mysql 表分区
查看>>
mysql 表的操作
查看>>
mysql 视图,视图更新删除
查看>>
MySQL 触发器
查看>>
mysql 让所有IP访问数据库
查看>>
mysql 记录的增删改查
查看>>
MySQL 设置数据库的隔离级别
查看>>
MySQL 证明为什么用limit时,offset很大会影响性能
查看>>
Mysql 语句操作索引SQL语句
查看>>
MySQL 误操作后数据恢复(update,delete忘加where条件)
查看>>
MySQL 调优/优化的 101 个建议!
查看>>
mysql 转义字符用法_MySql 转义字符的使用说明
查看>>
mysql 输入密码秒退
查看>>
mysql 递归查找父节点_MySQL递归查询树状表的子节点、父节点具体实现
查看>>
mysql 通过查看mysql 配置参数、状态来优化你的mysql
查看>>
mysql 里对root及普通用户赋权及更改密码的一些命令
查看>>
Mysql 重置自增列的开始序号
查看>>
mysql 锁机制 mvcc_Mysql性能优化-事务、锁和MVCC
查看>>