Java + Spring MVC + Hibernate持久性错误 - Cant Persist User

时间:2014-10-23 10:12:23

标签: java sql spring hibernate maven

好的,我正在使用java spring mvc,spring security,maven,hibernate和其他一些技术构建电子商务网站,但这些应该是唯一与我的问题相关的技术。我正在做所有没有XML的java配置(我正在考虑修改,因为我遇到了xml似乎更容易的情况)。

我想知道为什么我在maven安装时获得了无异常,但在服务器重启(tomcat 7)时获得了异常。

我试图在拥有用户和角色的同时尽可能简单地解决这个问题。当我查看代码时,它确实是非常直接的东西 - 我很想知道它为什么每次都出错。

主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;
}

}

UserRole类

@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;
}

}

UserDao界面

public interface UserDao {

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

}

在UserDAOImpl

@Repository
public class UserDaoImpl implements UserDao {

@Autowired
private SessionFactory sessionFactory;

@SuppressWarnings("unchecked")
public User findByUserName(String username) {

    List<User> users = new ArrayList<User>();

    users = sessionFactory.getCurrentSession().createQuery("from User where username=?").setParameter(0, username)
            .list();

    if (users.size() > 0) {
        return users.get(0);
    } else {
        return null;
    }

}

 @Override
 @Transactional
 public void addUser(User user) {
        sessionFactory.getCurrentSession().persist(user);           

 }

UserService接口

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;
}

}

使用数据库SQL

CREATE  TABLE users (
user_id int(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(45) NOT NULL UNIQUE,
PRIMARY KEY (user_id));

好的,我将这一点简化为持久用户的简单任务。我无法让服务器启动而没有错误。上面的代码中有一些错误。

在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

谢谢

1 个答案:

答案 0 :(得分:1)

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

错误消息是:

  

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

如果你有一个堆栈跟踪,你将能够确切地看到空引用发生在哪一行。如果没有,您必须启动调试器(或插入println语句)以查找。

无论哪种方式,您的AppConfig类似乎都有错误,或者您没有正确初始化它。查看sessionConfig()方法以查看NPE的原因,并在调用它之前确保相应的引用不为null。