gpt4 book ai didi

java - 使用 EJB 和 JPA 持久保存到数据库时遇到问题

转载 作者:行者123 更新时间:2023-12-01 14:09:22 25 4
gpt4 key购买 nike

这是实体

  package com.ose.bookstore.model.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
* Entity implementation class for Entity: Login
*
*/
@Entity
public class Login implements Serializable {


private static final long serialVersionUID = 1L;

public Login() {
super();
}
@Id
@GeneratedValue
private int loginId;
private String userEmail;
private String password;
private String secPassword;



public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSecPassword() {
return secPassword;
}
public void setSecPassword(String secPassword) {
this.secPassword = secPassword;
}
public int getLoginId() {
return loginId;
}
public void setLoginId(int loginId) {
this.loginId = loginId;
}
}

这是 Controller /测试类

package com.ose.bookstore.model.test;

import javax.ejb.EJB;
import javax.faces.bean.SessionScoped;

import com.ose.bookstore.model.ejb.LoginDao;
import com.ose.bookstore.model.entity.Login;

/**
* @author nishant
*
*/
@SessionScoped
public class LoginTest1 {

@EJB
private static LoginDao loginDao;

public static void main(String[] args) {
// TODO Auto-generated method stub
Login login = new Login();
login.setLoginId(2);
login.setPassword("asdf");
login.setSecPassword("asdfsadF");
login.setUserEmail("email");
loginDao.writeToDb(login);
}
}

这是 EJB 类

package com.ose.bookstore.model.ejb;

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.ose.bookstore.model.entity.Login;

/**
* @author nishant
*
*/
@Remote
@Stateless
public class LoginDao {

public LoginDao() {
super();
// TODO Auto-generated constructor stub
}
@PersistenceContext
private EntityManager entityManager;
public void writeToDb(Login login){
entityManager.persist(login);
}

}

我收到此错误loginDao.writeToDb(login);

线程“main”中出现异常 java.lang.NullPointerException 在 com.ose.bookstore.model.test.LoginTest1.mainLoginTest1是Controller/Test类的类名

最佳答案

您需要在Application client container内执行客户端代码。否则 @EJB 本地注入(inject)不起作用(您的测试代码像 javastandalone 一样执行,但它需要一个注入(inject) EJB 的容器)

关于java - 使用 EJB 和 JPA 持久保存到数据库时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com