我正在尝试创建一个Web服务,该服务将通过休眠从数据库中获取一些结果。

@Path("/book")
public class BookService {

    @Inject
    private dbController db;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getBookTitle() {
        return "H2G2";
    }

    @GET
    @Path("/users")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUsers(){

        List<UserEntity> users = db.getUsers();


        return Response.ok(users,MediaType.APPLICATION_JSON).build();
    }
}


每当我调用http://localhost/book/users时,db变量始终为null。

dbController是:

public class dbController {

    @Inject
    private HibernateUtil util;

    public List<UserEntity> getUsers(){

        List<UserEntity> result = null;
        try{
            result = (List<UserEntity>) this.util.createQuery("select e from UserEntity e");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return result;
    }
}


而HibernateUtil是:

public class HibernateUtil {

    private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("NewPersistenceUnit");
    private EntityManager entityManager = null;


    private void createEntityManager(){
        if (this.entityManager==null){
            this.entityManager = entityManagerFactory.createEntityManager(); // here is your persistence unit name
        }


    }

    private void closeConnection(){
        this.entityManager.close();
        this.entityManager = null;
    }

    public List createQuery(String query) throws Exception{
        this.createEntityManager();
        List result;

        try{
            result = this.entityManager.createQuery(query).getResultList();
        }catch (Exception e){
            throw new Exception(e.getMessage());
        }

        return result;
    }


}


我正在使用intellij,并在db.getUsers()处添加了一个断点,并通过添加新的dbController()来设置变量db。但是,Intellij给我错误“类未加载:controller.dbController”。

休眠肯定可以正常工作...因此问题不存在。这是我第一次尝试使用依赖注入,但是我不确定自己做错了什么。

谢谢

最佳答案

您不能注入POJO,它必须是Bean。因此,使其成为bean需要注释,例如:

@Stateful
@LocalBean
public class dbController {..} // Should be DbController, start with CAPS




@Stateful // or maybe @Stateless ?
@LocalBean
public class HibernateUtil {..}


然后,当您拥有Bean时,不允许使用static final,因此需要进行如下更改:

private EntityManagerFactory entityManagerFactory =
            Persistence.createEntityManagerFactory("NewPersistenceUnit");


但是实际上,获取EntityManager的最简单方法就是同时注入它。喜欢:

@PersistenceContext// maybe also with unit name (unitName = "whatever_the_unit_name_is")
private EntityManager em;

07-25 22:42