Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java+;Spring MVC+;休眠持久化错误-无法持久化用户_Java_Sql_Spring_Hibernate_Maven - Fatal编程技术网

Java+;Spring MVC+;休眠持久化错误-无法持久化用户

Java+;Spring MVC+;休眠持久化错误-无法持久化用户,java,sql,spring,hibernate,maven,Java,Sql,Spring,Hibernate,Maven,好的,我正在使用JavaSpringMVC、SpringSecurity、maven、hibernate和其他一些技术构建一个电子商务站点,但是这些应该是与我的问题相关的唯一技术。顺便说一句,我正在做所有java配置,没有XML(我目前正在考虑修改,因为我遇到了XML似乎更容易的情况) 我想知道为什么我在maven安装时没有异常,但在服务器重新启动时出现异常(Tomcat7) 我已经试着在仍然有一个用户和一个角色的情况下尽可能地简化这个过程。当我看代码时,它真的是非常直截了当的东西——我渴望找到

好的,我正在使用JavaSpringMVC、SpringSecurity、maven、hibernate和其他一些技术构建一个电子商务站点,但是这些应该是与我的问题相关的唯一技术。顺便说一句,我正在做所有java配置,没有XML(我目前正在考虑修改,因为我遇到了XML似乎更容易的情况)

我想知道为什么我在maven安装时没有异常,但在服务器重新启动时出现异常(Tomcat7)

我已经试着在仍然有一个用户和一个角色的情况下尽可能地简化这个过程。当我看代码时,它真的是非常直截了当的东西——我渴望找到它每次出错的原因

主Appconfig类

@EnableWebMvc
@Configuration
@ComponentScan({ "com.crutchsf.*" })
@EnableTransactionManagement
@Import({ SecurityConfig.class })
public class AppConfig {

@Bean
public SessionFactory sessionFactory() {
    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
    builder
        .scanPackages("com.crutchsf.users.model")
        .addProperties(getHibernateProperties());

    return builder.buildSessionFactory(); 
}

private Properties getHibernateProperties() {
    Properties prop = new Properties();
    prop.put("hibernate.format_sql", "true");
    prop.put("hibernate.show_sql", "true");
    prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    return prop;
}

@Bean(name = "dataSource")
public BasicDataSource dataSource() {

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/test");
    ds.setUsername("bobby");
    ds.setPassword("password");
    return ds;
}

@Bean
public HibernateTransactionManager txManager() {
    return new HibernateTransactionManager(sessionFactory());
}

@Bean
public UserService userService() {

    UserService userService = new MyUserDetailsService();
    userService.setUserDao(new UserDaoImpl());
    return userService;
}

@Bean
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("validation");
    return messageSource;
}   

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

 public void addResourceHandlers(ResourceHandlerRegistry registry) {
         registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
    }

 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}
SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/admin/**")
        .access("hasRole('ROLE_ADMIN')").and().formLogin()
        .loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and().logout().logoutSuccessUrl("/login?logout")
            .and().csrf()
            .and().exceptionHandling().accessDeniedPage("/403");    
}
}
用户类

@Entity
@Table(name = "users", catalog = "test")
public class User {

private Integer user_id;
private String username;
private String password;
private String passwordConf;

public User() {
}


public User(String username, String password) {

    this.username = username;
    this.password = password;
}


@Id
@Column(name = "user_id")
@GeneratedValue
public Integer getUserId() {
    return this.user_id;
}

@Column(name = "username", unique = true, nullable = false, length = 45)
public String getUsername() {
    return this.username;
}

public void setUsername(String username) {
    this.username = username;
}

@Column(name = "password", nullable = false, length = 60)
public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}

@Transient
public String getPasswordConf() {
    return this.passwordConf;
}

public void setPasswordConf(String passwordConf) {
    this.passwordConf = passwordConf;
}

}
用户角色类

@Entity
@Table(name = "user_roles", catalog = "test", 
uniqueConstraints = @UniqueConstraint(
    columnNames = { "role", "username" }))
public class UserRole{

private Integer userRoleId;
private User user;
private String role;

public UserRole() {
}

public UserRole(User user, String role) {
    this.user = user;
    this.role = role;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "user_role_id", 
    unique = true, nullable = false)
public Integer getUserRoleId() {
    return this.userRoleId;
}

public void setUserRoleId(Integer userRoleId) {
    this.userRoleId = userRoleId;
}

public User getUser() {
    return this.user;
}

public void setUser(User user) {
    this.user = user;
}

@Column(name = "role", nullable = false, length = 45)
public String getRole() {
    return this.role;
}

public void setRole(String role) {
    this.role = role;
}

}
用户DAO接口

public interface UserDao {

User findByUserName(String username);
List<User> findAllUsers();
void addUser(User user);

}
public interface UserService {

UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException;
void setUserDao(UserDao userDao);
void addUser(com.crutchsf.model.users.User user);
}
用户服务Impl

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService, UserService {

@Autowired
private UserDao userDao;


@Transactional(readOnly=true)
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    com.crutchsf.model.users.User user = userDao.findByUserName(username);
    List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());

    return buildUserForAuthentication(user, authorities);

}

private User buildUserForAuthentication(com.crutchsf.model.users.User user, List<GrantedAuthority> authorities) {
    return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
}

private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {

    Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

    // Build user's authorities
    for (UserRole userRole : userRoles) {
        setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
    }

    List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

    return Result;
}   

@Override
@Transactional
public void addUser(com.crutchsf.model.users.User user) {
    this.userDao.addUser(user);
}

public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}

}
好的,我把它简化为一个简单的任务,即持久化用户。我无法让服务器无错误地启动。上面的代码一定有问题

在AppConfig.java中,如果我将行“scanPackages…”更改为实际的类名

com.crutchsf.users.model.User
然后我的服务器正常启动,但当它到达要持久化的userDao中的行时

sessionFactory.getCurrentSession().persist(user);
我从hibernate中得到一个不同的错误“找不到实体com.crutchsf.users.model.User”

这是我得到的主要错误。基本上我可以选择我现在想要得到的错误


    [public org.hibernate.SessionFactory com.crutchsf.config.AppConfig.sessionFactory()] threw exception; nested exception is java.lang.NullPointerException

谢谢

表面上看,这似乎与Spring MVC或Hibernate无关

错误消息是:

工厂方法[public org.hibernate.SessionFactory com.crutchsf.config.AppConfig.SessionFactory()]引发异常;嵌套异常是java.lang.NullPointerException

如果您有stacktrace,您将能够准确地看到空引用发生在哪一行。如果没有,则必须启动调试器(或插入
println
语句)才能找到答案


无论如何,您的
AppConfig
类似乎有一个bug,或者您没有正确初始化它。查看
sessionConfig()
方法以了解它为何会出现NPE,并确保在调用它之前适当的引用不为null。

感谢您的快速响应!好的,我启动了调试器,并在AppConfig类的sessionFactory()方法的返回行上设置了一个断点,它不会出错,当我选择“单步执行”选项时,它会将我带到一个白色屏幕(代码通常会在那里),它会显示“找不到源代码”。红色字母,带有一个“编辑源代码查找路径”选项这将导致一个spring对话框弹出,询问我是否要添加或删除源查找路径。谢谢。我想这个错误是因为我的服务类中有一个不应该出现的autowire,现在出现了一个新错误。很抱歉我的问题不够清楚,我想知道为什么在运行我的项目之前尝试启动服务器时会出现错误/异常。我不知道怎么说得更清楚?这就是为什么我把我所有的代码都放了出来,包括堆栈跟踪——我还需要什么?谢谢你,我想你真的需要少发帖。现在,这是一个巨大的代码转储。您的问题应该是,这样其他人就不必阅读无关的代码来帮助您。另外,创建一个MCVE示例可能会导致您自己找到一个解决方案,因为您必须隔离问题。好吧,我明白您的意思,我在发布之前确实阅读了规则-我将所有代码发布到了,因为我知道它必须在某个地方-我将致力于对其进行精简,以不包含太多内容。谢谢,我个人仍然觉得它太冗长,但其他人可能不同意。但是你显然已经在努力改进你的帖子,现在确实更好了。而且,虽然它很长,但它的结构很好,问题也很明显。我投票赞成重新开放,其他两位用户也是如此……让我们看看你是否能再得到两位对你投赞成票。;)顺便说一句,如果你现在遇到一个新的错误(如下面的评论所示),也许你可以写一个新的问题来关注这个错误(发布堆栈跟踪等),然后关闭/删除这个错误。
sessionFactory.getCurrentSession().persist(user);

    [public org.hibernate.SessionFactory com.crutchsf.config.AppConfig.sessionFactory()] threw exception; nested exception is java.lang.NullPointerException