EntityManagerFactory实例通过PersistenceUnit注释注入

时间:2017-08-22 12:27:02

标签: java hibernate jpa

请解释它为什么不起作用。我希望使用EntityManagerFactory注释来获取@PersistenceUnit实例。无论我尝试什么,它仍然是空的。

我没有使用任何Java EE,我通过Java main方法运行我的程序。这就是我使用RESOURCE LOCAL交易的原因。据我了解,它无法使用@PersistenceContext但能够使用@PersistenceUnit

它是这样的,但我想弄清楚为什么通过注释注入不起作用

 EntityManager em = 
     Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();

我的代码:

persistence.xml

    <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">

    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
        <property name="hibernate.connection.url" value="jdbc:postgresql://127.0.0.1:5432/shua"/>
        <property name="javax.persistence.jdbc.user" value="postgres" />
        <property name="javax.persistence.jdbc.password" value="postgres" />
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
    </properties>
</persistence-unit>

public class UserDaoImpl {
@PersistenceUnit(name = "persistenceUnit")
EntityManagerFactory emf;

public List<UsersEntity> getAll(){

    EntityManager em = emf.createEntityManager();

    EntityTransaction et = em.getTransaction();
    et.begin();
    Query query = em.createQuery("FROM UsersEntity u");
    List<UsersEntity> users = query.getResultList();
    et.commit();
    em.close();
    return users;

}}

实体

@Entity
@Table(name = "users", schema = "public", catalog = "shua")
public class UsersEntity {
    private long userId;
    private String userName;
    private String userPassword;
    private String userEmail;

        @Id
        @Column(name = "user_id")
        public long getUserId() {
            return userId;
        }

        public void setUserId(long userId) {
            this.userId = userId;
        }

        @Basic
        @Column(name = "user_name")
        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        @Basic
        @Column(name = "user_password")
        public String getUserPassword() {
            return userPassword;
        }

        public void setUserPassword(String userPassword) {
            this.userPassword = userPassword;
        }

        @Basic
        @Column(name = "user_email")
        public String getUserEmail() {
            return userEmail;
        }

        public void setUserEmail(String userEmail) {
            this.userEmail = userEmail;
        }  

0 个答案:

没有答案