我正在使用Spring,Maven,Tomcat,mySQL为我的学习做一个项目。我想创建一个网站,用户可以登录并更新他们的设置,并根据这些设置生成内容。
目前登录工作正常,新用户可以注册并保存到数据库中。现在我创建了一个新实体并在两个表之间进行了一对一的关联 - 一个是登录详细信息的表,如密码和用户名,另一个是包含该用户的设置。我面临的问题:
当SQL尝试保存对象时,它会抛出错误: 引起:java.sql.SQLException:字段'user_login_id'没有默认值
以下是实体:
@Entity
@Table(name = "USERLOGIN")
public class UserLogin implements UserDetails {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@OneToOne(mappedBy = "userlogin")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
**Other getters and setters**
}
@Entity
@Table(name = "USER")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer id;
@Column(name = "meal")
private Integer meal;
@OneToOne
@JoinColumn(name = "userlogin_id")
private UserLogin userlogin;
public UserLogin getUserLogin() {
return userlogin;
}
public void setUserLogin(UserLogin userLogin) {
this.userlogin = userLogin;
userLogin.setUser(this);
**Other getters and setters**
}
保存设置的服务:
@Service
public class AddUserServiceImpl implements AddUserService{
@Autowired
private UserRepository userRepository;
@Autowired
private CurrentUserService currentUserService;
public void saveUser(User userDAO) {
User user = new User();
user.setMeal(userDAO.getMeal());
user.setUserLogin(currentUserService.getCurrentUser());
userRepository.save(user);
}
}
存储库扩展了JPArepository:
@Repository
public interface UserRepository extends JpaRepository<User, Integer>{
}
最后是加载当前登录用户的服务和存储库:
@Service
public class CurrentUserServiceImpl implements CurrentUserService {
@Autowired
UserLoginRepository userLoginRepository;
public String getCurrentUsername() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
public UserLogin getCurrentUser() {
return userLoginRepository.findByUserName(getCurrentUsername());
}
}
@Repository
public interface UserLoginRepository extends JpaRepository<UserLogin,
Integer> {
@Query("select u from UserLogin u where u.username=:username")
UserLogin findByUserName( @Param("username") String username);
}
任何帮助将不胜感激我对这个主题真的很新。 所以主要目标是我想拥有一个存储当前登录用户属性的表 - 这些设置应该能够随时更新。有没有最佳做法?
谢谢!