当我尝试在数据库中保存角色时,出现“ springit.role表不存在”。
我没有在数据库中创建一个名称为“ role”的表,因为我正在学习的课程中的老师现在没有创建一个表。
当我在DatabaseLoader类方法中调用“ addUsersAndRoles()”时显示的异常
那么,有什么问题呢?
角色.java
@Entity
@RequiredArgsConstructor
@Getter
@Setter
@ToString
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue
private Long id;
@NonNull
private String name;
@ManyToMany( mappedBy = "roles")
private Collection<User> users;
}
User.java
@Entity
@RequiredArgsConstructor
@Getter
@Setter
@ToString
@NoArgsConstructor
public class User implements UserDetails {
@Id @GeneratedValue
private Long id;
@NonNull
@Size(min = 8, max = 20)
@Column(nullable = false, unique = true)
private String email;
@NonNull
@Column(length = 100)
private String password;
@NonNull
@Column(nullable = false)
private boolean enabled;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(name = "user_id",referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id",referencedColumnName = "id")
)
private Set<Role> roles = new HashSet<>();
public void addRole(Role role) {
roles.add(role);
}
public void addRoles(Set<Role> roles) {
roles.forEach(this::addRole);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
DatabaseLoader.java
@Component
public class DatabaseLoader implements CommandLineRunner {
private LinkRepository linkRepository;
private CommentRepository commentRepository;
private RoleRepository roleRepository;
private UserRepository userRepository;
public DatabaseLoader(LinkRepository linkRepository, CommentRepository commentRepository, RoleRepository roleRepository, UserRepository userRepository) {
this.linkRepository = linkRepository;
this.commentRepository = commentRepository;
this.roleRepository = roleRepository;
this.userRepository = userRepository;
}
@Override
public void run(String... args) {
addUsersAndRoles();
Map<String,String> links = new HashMap<>();
links.put("Securing Spring Boot APIs and SPAs with OAuth 2.0","https://auth0.com/blog/securing-spring-boot-apis-and-spas-with-oauth2/?utm_source=reddit&utm_medium=sc&utm_campaign=springboot_spa_securing");
links.put("Easy way to detect Device in Java Web Application using Spring Mobile - Source code to download from GitHub","https://www.opencodez.com/java/device-detection-using-spring-mobile.htm");
links.put("Tutorial series about building microservices with SpringBoot (with Netflix OSS)","https://medium.com/@marcus.eisele/implementing-a-microservice-architecture-with-spring-boot-intro-cdb6ad16806c");
links.forEach((k,v) -> {
linkRepository.save(new Link(k,v));
// we will do something with comments later
});
long linkCount = linkRepository.count();
System.out.println("Number of links in the database: " + linkCount );
}
private void addUsersAndRoles() {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String secret = "{bcrypt}" + encoder.encode("password");
Role userRole = new Role("ROLE_USER");
roleRepository.save(userRole);
Role adminRole = new Role("ROLE_ADMIN");
roleRepository.save(adminRole);
User user = new User("[email protected]",secret,true);
user.addRole(userRole);
userRepository.save(user);
User admin = new User("[email protected]",secret,true);
admin.addRole(adminRole);
userRepository.save(admin);
User master = new User("[email protected]",secret,true);
master.addRoles(new HashSet<>(Arrays.asList(userRole,adminRole)));
userRepository.save(master);
}
}
schema.sql
CREATE DATABASE IF NOT EXISTS `springit`;
USE `springit`;
DROP TABLE IF EXISTS `comment`;
CREATE TABLE `comment` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_by` varchar(255) DEFAULT NULL,
`creation_date` datetime DEFAULT NULL,
`last_modified_by` varchar(255) DEFAULT NULL,
`last_modified_date` datetime DEFAULT NULL,
`body` varchar(255) DEFAULT NULL,
`link_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FKoutxw6g1ndh1t6282y0fwvami` (`link_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `link`;
CREATE TABLE `link` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created_by` varchar(255) DEFAULT NULL,
`creation_date` datetime DEFAULT NULL,
`last_modified_by` varchar(255) DEFAULT NULL,
`last_modified_date` datetime DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
我是springboot的新手,请帮助。
例外情况:
NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)〜[na:na]在java.base / jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)〜java.base / java处的[na:na]。 lang.reflect.Method.invoke(Method.java:564)〜[na:na]在org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)〜[spring-boot-devtools-2.4 .2.jar:2.4.2]原因:org.springframework.dao.InvalidDataAccessResourceUsageException:无法执行语句;SQL [n / a];嵌套的异常是org.hibernate.exception.SQLGrammarException:无法在org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)〜[spring-orm-5.3.3.jar:5.3。执行语句。 3],网址为org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect。
当然,您将需要由您自己或由Hibernate创建的表。
您可以使用JPA将配置添加到Spring Boot应用程序中,以自动生成数据库架构(或缺少的部分)。在这里看看https://docs.spring.io/spring-boot/docs/1.1.0.M1/reference/html/howto-database-initialization.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句