我有JPA实体类:
@XmlRootElement(name = "actor")
@Entity
@Table
@NamedQueries({
@NamedQuery(name = "Actor.getByName", query = "SELECT v FROM Actor v WHERE v.name = :name"),
@NamedQuery(name = "Actor.getAll", query = "SELECT e FROM Actor e")})
public class Actor implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@Column
private String name;
@Column
private String birthDate;
@Column
private String email;
@Column
private String image;
//getters and setters here
//no argument constructor and all arguments constructor
}
DAO Local:
@Local
public interface ActorDaoLocal {
Actor getActor(int actorId);
public List<Actor> getAllActors();
}
和DAO:
@Stateless
public class ActorDao implements ActorDaoLocal {
@PersistenceContext
private EntityManager em ;
@Override
public Actor getActor(int actorId) {
return em.find(Actor.class, actorId);
}
@Override
public List<Actor> getAllActors() {
Query named = em.createNamedQuery("Actor.getAll", Actor.class);
return named.getResultList();
}
在MainController中,我正在调用这些方法:
@Path("/actors")
public class MainController {
@EJB
private ActorDaoLocal actorDao;
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<Actor> getAllActors() {
System.out.println("Getting all actors...");
List<Actor> actorList = actorDao.getAllActors();
Actor actor = actorDao.getActor(1);
System.out.println("actor " + actor); //this is null
return actorList; //this is empty list
}
我的问题是Dao方法为getActor
方法返回null,为getAllActors
方法返回空列表。
我在GlassFish工作。与数据库的连接似乎没问题,在Glassfish控制台中我没有看到任何例外情况。当然,我有一些行数据库。
编辑:persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ZajacPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/actordb"/>
<property name="javax.persistence.jdbc.user" value="app"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.password" value="app"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>