0

所以我正在尝试在我的 web 项目中实现 Spring Framework 和 Hibernate。

我让休眠状态在某一时刻工作(注册用户并将其添加到数据库中),但过了一段时间没有任何工作。

INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sat Jul 20 22:45:19 EET 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.config.PropertyPlaceholderConfigurer - Loading properties file from ServletContext resource [/WEB-INF/jdbc.properties]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7b4dab69: defining beans [messageSource,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7b4dab69: defining beans [messageSource,propertyConfigurer,dataSource,sessionFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager]; root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/root-context.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
    at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
    at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:247)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:373)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
    ... 22 more

Caused by: java.lang.NullPointerException

根上下文.xml

<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/jdbc.properties" />
</bean>

<bean id="dataSource"
    class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url"             value="${jdbc.databaseurl}" />
    <property name="username"        value="${jdbc.username}" />
    <property name="password"        value="${jdbc.password}" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource"         ref="dataSource" />
    <property name="packagesToScan"     value="com.something.*" /> 
    <property name="configLocation"     value="classpath:hibernate.cfg.xml" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${jdbc.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<tx:annotation-driven />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

休眠.cfg.xml

<?xml version='1.0' encoding='utf-8'?> 

<session-factory>

    <!-- Database connection settings -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/imdb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="hibernate.connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Echo all executed SQL to stdout for debugging -->
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>

    <mapping class="springers.Model.Bean.UserAccount" />
    <mapping class="springers.Model.Bean.Movie" />
    <mapping class="springers.Model.Bean.TvShow" />
    <mapping class="springers.Model.Bean.Connector_User_TvShow" />
</session-factory>

数据对象示例:

@Entity
@Table(name = "USERS")

public class UserAccount {

    private int    user_pk;
    private String username;
    private String password;
    private String e_mail;
    private String country;

    @Id
    @GeneratedValue
    @Column(name = "USER_PK")
    public int    getUser_pk()  { return user_pk;  }

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

    @Column(name = "PASSWORD", nullable = false, length = 12)
    public String getPassword() { return password; }

    @Column(name = "E_MAIL", nullable = false, length = 50, unique = true)
    public String getE_mail()   { return e_mail;   }

    @Column(name = "COUNTRY", nullable = false, length = 25)
    public String getCountry()  { return country;  }

    public void setUser_pk (int    user_pk)  { this.user_pk = user_pk; }
    public void setUsername(String username) { this.username = username; }
    public void setPassword(String password) { this.password = password; }
    public void setCountry (String country)  { this.country = country;   }
    public void setE_mail  (String e_mail)   { this.e_mail = e_mail;     }

用户 tvshow 连接器 bean:

@Entity
@Table(name = "USER_TVSHOW_CONNECTOR",
uniqueConstraints = @UniqueConstraint(columnNames = {"user_fk", "tvShow_fk"}))

public class Connector_User_TvShow {

private int         utc_pk;
private boolean     toWatch  = false;
private boolean     favorite = false;
private boolean     reminder = false;
private UserAccount user_fk;
private TvShow      tvShow_fk;

@Id
@GeneratedValue
@Column(name = "UTC_PK")
public int         getUtc_pk()    { return utc_pk;    }

@Column(name = "TO_WATCH", nullable = false)
public boolean     isToWatch()    { return toWatch;   }

@Column(name = "FAVOURITE", nullable = false)
public boolean     isFavorite()   { return favorite;  }

@Column(name = "REMINDER", nullable = false)
public boolean     isReminder()   { return reminder;  }

@OneToOne(cascade = CascadeType.ALL)
public UserAccount getUser_fk()   { return user_fk;   }

@OneToOne(cascade = CascadeType.ALL)
public TvShow      getTvShow_fk() { return tvShow_fk; }

public void setUtc_pk    (int         utc_pk)    { this.utc_pk    = utc_pk;    }
public void setToWatch   (boolean     toWatch)   { this.toWatch   = toWatch;   }
public void setFavorite  (boolean     favorite)  { this.favorite  = favorite;  }
public void setReminder  (boolean     reminder)  { this.reminder  = reminder;  }
public void setUser_fk   (UserAccount user_fk)   { this.user_fk   = user_fk;   }
public void setTvShow_fk (TvShow      tvShow_fk) { this.tvShow_fk = tvShow_fk; }
4

2 回答 2

0

@JoinColumn(name="user_fk")将and添加@JoinColumn(name="tvShow_fk")到您的getUser_fkandgetTvShow_fk中。

于 2013-09-18T17:14:26.300 回答
0

我只是有同样的NullPointerException

如果@UniqueConstraint 注释的列名中有错字,您将获得此 NPE

您的异常的原因是相同的:

java.lang.NullPointerException
  at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:134)
  at org.hibernate.mapping.Constraint$ColumnComparator.compare(Constraint.java:130)
  at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
  at java.util.TimSort.sort(TimSort.java:189)
  at java.util.TimSort.sort(TimSort.java:173)
  at java.util.Arrays.sort(Arrays.java:659)
  at org.hibernate.mapping.Constraint.generateName(Constraint.java:82)
  at org.hibernate.cfg.Configuration.buildUniqueKeyFromColumnNames(Configuration.java:1572)
  at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1395)
  at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756)
  at ...

有针对此问题的错误报告。票已经修好了。如果更新到 hibernate 4.3 或更高版本,会有更好的异常消息。

PS:但在您的情况下,这只是因为您没有在连接注释上指定任何列名(请参阅@alex 的答案)。

于 2015-07-26T14:14:49.790 回答