- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我将文件作为 JUnit 测试运行时,UsersDAOImpl 类应该添加一个新用户,但当我调用 sessionFactory.getCurrentSession() 时,我不断收到 NullPointerException,我不知道为什么。
session 工厂放在 beans.xml 中。
由于显而易见的原因,数据库的凭据已被删除。
[bean.XML]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- enable autowiring -->
<context:component-scan base-package="src"></context:component-scan>
<!-- enable @Transactional -->
<tx:annotation-driven />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="username" value="{Master}"></property>
<property name="password" value="{password}"></property>
<property name="url" value="{url}"></property>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"></property>
<property name="packagesToScan" value="src"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory">
</property>
</bean>
<bean id="usersDAO" class="dao.UsersDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"> </property>
</bean>
</beans>
[UsersDAOImpl.java]
package dao;
import static org.junit.Assert.*;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import customExceptions.*;
import util.Debug;
import util.HibernateUtil;
import domain.Users;
@Transactional
public class UsersDAOImpl implements UsersDAO {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionfactory) {
this.sessionFactory = sessionfactory;
}
@Test
public void testPush() {
try {
push(new Users("username6", "email@gmail.com", "password", "firstName", "lastName", false));
} catch (UserNameTakenException e) {
e.printStackTrace();
fail();
} catch (InvalidNameException e) {
e.printStackTrace();
fail();
}
}
/**
* Adds a new user to the database
*
* @param newUser
* The user to be added
* @throws UserNameTakenException
* In the case a username is taken
* @throws InvalidNameException
* If a field is left blank, but front end should prevent that
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void push(Users newUser) throws UserNameTakenException, InvalidNameException {
// For debugging purposes:
Debug.printMessage(this.getClass(), "push()", "invoked");
// Check if there are any empty Strings
if (newUser.getUsername().isEmpty() || newUser.getPassword().isEmpty() || newUser.getFirstName().isEmpty()
|| newUser.getLastName().isEmpty()) {
throw new InvalidNameException("There is an empty String");
}
// Get the session
//THIS IS WHERE I GET THE EXCEPTION
Session sess = sessionFactory.getCurrentSession();
// Check to see if the username is taken
Users users = getUserByName(newUser.getUsername());
// If the list is not empty, a user with the name was found
if (users != null) {
sess.close();
throw new UserNameTakenException("The username was found in the database");
} else {
// Otherwise, add the new user
// Debug
Debug.printMessage(this.getClass(), "push()", "username available.");
Debug.printErrorMessage(this.getClass(), "push()", "saving " + newUser.getUsername());
sess.save(newUser);
sess.close();
}
}
/**
* Updates the User's password in the database
*
* @param user
* The user to change
* @param newVal
* The new password
*/
@Override
public void updatePassword(Users user, String newVal) {
Debug.printMessage(this.getClass(), "updatePassword()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setPassword(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Updates the User's first name in the database
*
* @param user
* The user to change
* @param newVal
* The new first name
*/
@Override
public void updateFirstName(Users user, String newVal) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "updateFirstName()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setFirstName(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Updates the User's last name in the database
*
* @param user
* The user to change
* @param newVal
* The new last name
*/
@Override
public void updateLastName(Users user, String newVal) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "updateLastName()", "invoked");
Session sess = HibernateUtil.getSession();
Transaction trans = sess.beginTransaction();
user.setLastName(newVal);
sess.update(user);
trans.commit();
sess.close();
}
/**
* Returns the user with the given username
*
* @param username
* The username to find
*/
@Override
public Users getUserByName(String username) {
// For debugging purposes:
Debug.printMessage(this.getClass(), "getUserByName()", "invoked");
Session sess = HibernateUtil.getSession();
Users user = (Users) sess.get(Users.class, username);
sess.close();
return user;
}
/**
* Returns a list of all users from A_USERS
*/
@Override
public List<Users> getAllUsers() {
// For debugging purposes:
Debug.printMessage(this.getClass(), "getAllUsers()", "invoked");
Session sess = HibernateUtil.getSession();
Query query = sess.getNamedQuery("getAllUsers");
List<Users> users = query.list();
sess.close();
return users;
}
}
另外,如果格式不正确,我深表歉意。这是我第一次发帖提问。
堆栈跟踪
java.lang.NullPointerException
at dao.UsersDAOImpl.push(UsersDAOImpl.java:65)
at dao.UsersDAOImpl.testPush(UsersDAOImpl.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
空
最佳答案
sessionFactory 字段为空。
至于为什么,我只能猜测。您既 Autowiring sessionFactory 字段,又通过 applicationContext.xml 中的配置将其作为属性注入(inject)。执行其中之一,而不是两者都执行,然后看看会发生什么。
关于java - sessionFactory.getCurrentSession() 导致 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45363290/
我正在尝试使用 Spark 从 Cassandra 读取数据。 DataFrame rdf = sqlContext.read().option("keyspace", "readypulse
这是代码: void i_log_ (int error, const char * file, int line, const char * fmt, ...) { /* Get erro
我必须调试一个严重依赖 Gtk 的程序。问题是由于某些原因,在使用 GtkWindow 对象时开始出现许多运行时警告。问题是,即使 Gtk 提示严重错误,它也不会因这些错误而中止。我没有代码库的更改历
我正在尝试从已有效编译和链接的程序中检索二进制文件。我已经通过 GL_PROGRAM_BINARY_LENGTH 收到了它的长度。该文档说有两个实例可能会发生 GL_INVALID_OPERATION
我有一个托管在 Azure 环境中的服务。我正在使用控制台应用程序使用该服务。这样做时,我得到了异常: "The requested service, 'http://xxxx-d.yyyy.be/S
我有以下代码,它被 SEGV 信号杀死。使用调试器表明它被 main() 中的第一个 sem_init() 杀死。如果我注释掉第一个 sem_init() ,第二个会导致同样的问题。我试图弄清楚是什么
目前我正在编写一个应用程序(目标 iOS 6,启用 ARC),它使用 JSON 进行数据传输,使用核心数据进行持久存储。 JSON 数据由 PHP 脚本通过 json_encode 从 MySQL 数
我对 Xamarin.Forms 还是很陌生。我在出现的主页上有一个非常简单的功能 async public Task BaseAppearing() { if (UserID
这是我的代码的简化版本。 public class MainActivity extends ActionBarActivity { private ArrayList entry = new Arr
我想弄明白为什么我的两个 Java 库很难很好地协同工作。这是场景: 库 1 有一个类 A,其构造函数如下: public A(Object obj) { /* boilerplate */ } 在以
如果网站不需要身份验证,我的代码可以正常工作,如果需要,则在打印“已创建凭据”后会立即出现 EXC_BAD_ACCESS 错误。我不会发布任何内容,并且此代码是直接从文档中复制的 - 知道出了什么问题
我在使用 NSArray 填充 UITableView 时遇到问题。我确信我正在做一些愚蠢的事情,但我无法弄清楚。当我尝试进行简单的计数时,我得到了 EXC_BAD_ACCESS,我知道这是因为我试图
我在 UITableViewCell 上有一个 UITextField,在另一个单元格上有一个按钮。 我单击 UITextField(出现键盘)。 UITextField 调用了以下方法: - (BO
我有一个应用程序出现间歇性崩溃。崩溃日志显示了一个堆栈跟踪,这对我来说很难破译,因此希望其他人看到了这一点并能为我指出正确的方向。 基本上,应用程序在启动时执行反向地理编码请求,以在标签中显示用户的位
我开发了一个 CGImage,当程序使用以下命令将其显示在屏幕上时它工作正常: [output_view.layer performSelectorOnMainThread:@selector(set
我正在使用新的 EncryptedSharedPreferences以谷歌推荐的方式上课: private fun securePrefs(context: Context): SharedPrefe
我有一个中继器,里面有一些控件,其中一个是文本框。我正在尝试使用 jquery 获取文本框,我的代码如下所示: $("#").click(function (event) {}); 但我总是得到 nu
在以下场景中观察到 TTS 初始化错误,太随机了。 已安装 TTS 引擎,存在语音集,并且可以从辅助功能选项中播放示例 tts。 TTS 初始化在之前初始化和播放的同一设备上随机失败。 在不同的设备(
maven pom.xml org.openjdk.jol jol-core 0.10 Java 类: public class MyObjectData { pr
在不担心冲突的情况下,可以使用 MD5 作为哈希值,字符串长度最多为多少? 这可能是通过为特定字符集中的每个可能的字符串生成 MD5 哈希来计算的,长度不断增加,直到哈希第二次出现(冲突)。没有冲突的
我是一名优秀的程序员,十分优秀!