Quarkus持久性异常和Java空指针异常

时间:2019-12-27 19:32:57

标签: java quarkus

终点类:

    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Transactional
    @ApplicationScoped
    public class UserEndPoint {

        @Inject
        private UserRepository UserDao;

        @GET
        @Path("user")
        public List<Utilisateur> all() {
            return UserDao.findAllUsers();
        }

        @GET
        @Path("user/by-name")
        public List<Utilisateur> findByName(@PathParam String name, @PathParam String firstName) {
            return UserDao.findbyName(name, firstName);
        }

        @GET
        @Path("user/create-after")
        public List<Utilisateur> findCreateAfter(@PathParam Date date) {
            return UserDao.findByCreate_Date(date);
        }

        @GET
        @Path("User/{userId}")
        public Utilisateur findById(@PathParam Long id) {
            Utilisateur p = UserDao.findById(id);
            if (p == null)
                throw new WebApplicationException(Status.NOT_FOUND);
            return p;
        }

        @PUT
        @Path("User/{userId}")
        public void updateUser(@PathParam Long id, Utilisateur newUser) {
            Utilisateur p = UserDao.findById(id);
            if (p == null)
                throw new WebApplicationException(Status.NOT_FOUND);
            p.setBirth_date(newUser.getBirth_date());
            p.setFirtName(newUser.getFirtName());
            p.setLastname(newUser.getLastname());
        }

        @DELETE
        @Path("User/{userId}")
        public void deleteUser(@PathParam Long id) {
            Utilisateur p = UserDao.findById(id);
            if (p == null)
                throw new WebApplicationException(Status.NOT_FOUND);
            UserDao.delete(p);
        }

        @POST
        @Path("user")
        public Response newUser(@Context UriInfo uriInfo, Utilisateur newUser) {
            Utilisateur p = new Utilisateur();
            p.setBirth_date(newUser.getBirth_date());
            p.setFirtName(newUser.getFirtName());
            p.setLastname(newUser.getLastname());
            UserDao.persist(p);

            URI uri = uriInfo.getAbsolutePathBuilder().path(UserEndPoint.class).path(UserEndPoint.class, "findById")
                    .build(p.getUserId());
            return Response.created(uri).build();
        }

    }

道类:

    @ApplicationScoped
    public class UserRepository implements PanacheRepository<Utilisateur> {

        @Inject
        protected EntityManager entityManager;

        @Transactional
        public List<Utilisateur> findbyName(String lastname, String firstName) {

            List<Utilisateur> users = new ArrayList<>();
            try {
                users = entityManager.createQuery("FROM User WHERE lastName = :lastName and firstName", Utilisateur.class)
                        .setParameter("lastName", lastname).getResultList();

            } catch (Exception e) {
                // TODO: handle exception
            }
            return users;

        }

        @Transactional
        public List<Utilisateur> findByCreate_Date(Date date) {

            List<Utilisateur> users = new ArrayList<>();

            try {
                users = entityManager.createQuery("FROM User WHERE create_date> :date", Utilisateur.class)
                        .setParameter("date", date).getResultList();
            } catch (Exception e) {
                // TODO: handle exception
            }
            return users;
        }

        @Transactional
        public void persist(Utilisateur person) {
            try {
                entityManager.persist(person);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        @Transactional
        public void delete(Utilisateur person) {
            try {
                entityManager.remove(person);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        @Transactional
        public Utilisateur findByUserId(Long id) {
            Utilisateur userid = null;
            try {
                userid = entityManager.find(Utilisateur.class, id);
            } catch (Exception e) {
                // TODO: handle exception
            }
            return userid;
        }

        @Transactional
        public List<Utilisateur> findAllUsers() {
            List<Utilisateur> users = new ArrayList<Utilisateur>();
            try {
                users = entityManager.createQuery("FROM User", Utilisateur.class).getResultList();
            } catch (Exception e) {
                // TODO: handle exception
            }
            return users;
        }

    }

实体类:

    @Slf4j
    @Data
    @Entity
    @Table(name = "Utilisateur")
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    @DiscriminatorValue("P_")
    @RegisterForReflection
    public class Utilisateur extends PanacheEntity implements Serializable {

        /**
         * 
         */
        private static final long serialVersionUID = 461991388948874292L;

        // ------------------------proprieties----------------------------------------
        Date date = null;
        protected static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "USER_ID")
        protected Long userId;

        @NotNull
        @Size(min = 3, max = 50)
        @Column(name = "firstName", length = 50)
        protected String firtName;

        @NotNull
        @Size(min = 3, max = 50)
        @Column(name = "lastName", length = 50)
        protected String lastname;

        @Column(name = "userName", length = 50)
        protected String userName;

        @Column(name = "login", length = 20)
        protected String login;

        @Column(name = "password", length = 50)
        protected String password;

        @Column(name = "email")
        private String email;

        @Column
        private String confirm_pass;

        @Column
        private Long group_id;

        @Column(name = "photo")
        protected String photo;

        @Column(name = "sex", length = 1)
        protected String sex;

        @Column(name = "nationality", length = 50)
        protected String nationality;

        @Column
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
        protected Date birth_date;

        @Column
        protected boolean authenticated;

        @Column
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm a z")
        protected Date create_date;

        @Column
        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm a z")
        protected Date modify_date;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = CascadeType.ALL)
        private List<UserRole> roles;

        @Embedded
        @AttributeOverrides({

                @AttributeOverride(name = "phone", column = @Column(name = "P_phone", nullable = false, updatable = true)),
                @AttributeOverride(name = "homePhone", column = @Column(name = "P_homePhone", nullable = false, updatable = true)),
                @AttributeOverride(name = "country", column = @Column(name = "P_country", nullable = false, updatable = true)),
                @AttributeOverride(name = "city", column = @Column(name = "P_city", nullable = false, updatable = true)),
                @AttributeOverride(name = "street", column = @Column(name = "P_street", nullable = false, updatable = true)),
                @AttributeOverride(name = "zipCode", column = @Column(name = "P_zipCode", nullable = false, updatable = true)) })
        Adress adress;

        public Long getUserId() {
            return userId;
        }

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

        public String getFirtName() {
            return firtName;
        }

        public void setFirtName(String firtName) {
            this.firtName = firtName;
        }

        public String getLastname() {
            return lastname;
        }

        public void setLastname(String lastname) {
            this.lastname = lastname;
        }

        public String getLogin() {
            return login;
        }

        public void setLogin(String login) {
            this.login = login;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getPhoto() {
            return photo;
        }

        public void setPhoto(String photo) {
            this.photo = photo;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getNationality() {
            return nationality;
        }

        public void setNationality(String nationality) {
            this.nationality = nationality;
        }

        public Date getBirth_date() {
            return birth_date;
        }

        public void setBirth_date(Date birth_date) {
            simpleDateFormat.format(birth_date);
            this.birth_date = birth_date;
        }

        public boolean isAuthenticated() {
            return authenticated;
        }

        public void setAuthenticated(boolean authenticated) {
            this.authenticated = authenticated;
        }

        public Date getCreate_date() {
            return create_date;
        }

        public void setCreate_date(Date date) {

            simpleDateFormat.format(date);
            this.create_date = date;
        }

        public Date getModify_date() {
            return modify_date;
        }

        public void setModify_date(Date modify_date) {
            simpleDateFormat.format(modify_date);
            this.modify_date = modify_date;
        }

        public Adress getAdress() {
            return adress;
        }

        public void setAdress(Adress adress) {
            this.adress = adress;
        }

        public String getUserName() {
            return userName;
        }

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

        public List<UserRole> getRoles() {
            return roles;
        }

        public void setRoles(List<UserRole> roles) {
            this.roles = roles;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getConfirm_pass() {
            return confirm_pass;
        }

        public void setConfirm_pass(String confirm_pass) {
            this.confirm_pass = confirm_pass;
        }

        public Long getGroup_id() {
            return group_id;
        }

        public void setGroup_id(Long group_id) {
            this.group_id = group_id;
        }

        public Utilisateur() {
            super();

        }

        public Utilisateur(String userName) {
            super();
            this.userName = userName;
        }

        public Utilisateur(String userName, String password) {
            super();
            this.userName = userName;
            this.password = password;
        }

        public Utilisateur(@NotNull @Size(min = 3, max = 50) String firtName,
                @NotNull @Size(min = 3, max = 50) String lastname, String userName, String login, String password,
                String email, String confirm_pass, Long group_id, String photo, String sex, String nationality,
                Date birth_date, boolean authenticated, Date create_date, Date modify_date, List<UserRole> roles,
                Adress adress) {
            super();
            this.firtName = firtName;
            this.lastname = lastname;
            this.userName = userName;
            this.login = login;
            this.password = password;
            this.email = email;
            this.confirm_pass = confirm_pass;
            this.group_id = group_id;
            this.photo = photo;
            this.sex = sex;
            this.nationality = nationality;
            this.birth_date = birth_date;
            this.authenticated = authenticated;
            this.create_date = create_date;
            this.modify_date = modify_date;
            this.roles = roles;
            this.adress = adress;
        }

    }

我在命令行中启动应用程序,但出现了以下异常:

javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
        at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.persistenceException(FastBootEntityManagerFactoryBuilder.java:113)
        at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.build(FastBootEntityManagerFactoryBuilder.java:67)
        at io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:54)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at io.quarkus.hibernate.orm.runtime.JPAConfig$LazyPersistenceUnit.get(JPAConfig.java:109)
        at io.quarkus.hibernate.orm.runtime.JPAConfig.startAll(JPAConfig.java:57)
        at io.quarkus.hibernate.orm.runtime.HibernateOrmRecorder.startAllPersistenceUnits(HibernateOrmRecorder.java:77)
        at io.quarkus.deployment.steps.HibernateOrmProcessor$startPersistenceUnits37.deploy_0(HibernateOrmProcessor$startPersistenceUnits37.zig:70)
        at io.quarkus.deployment.steps.HibernateOrmProcessor$startPersistenceUnits37.deploy(HibernateOrmProcessor$startPersistenceUnits37.zig:36)
        at io.quarkus.runner.ApplicationImpl1.doStart(ApplicationImpl1.zig:145)
        at io.quarkus.runtime.Application.start(Application.java:94)
        at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:143)
        at io.quarkus.dev.DevModeMain.doStart(DevModeMain.java:180)
        at io.quarkus.dev.DevModeMain.start(DevModeMain.java:94)
        at io.quarkus.dev.DevModeMain.main(DevModeMain.java:66)
Caused by: java.lang.NullPointerException
        at org.hibernate.search.mapper.orm.mapping.impl.HibernateOrmMetatadaContributor.configure(HibernateOrmMetatadaContributor.java:59)
        at org.hibernate.search.mapper.pojo.mapping.spi.AbstractPojoMappingInitiator.configure(AbstractPojoMappingInitiator.java:89)
        at org.hibernate.search.mapper.orm.mapping.impl.HibernateOrmMappingInitiator.configure(HibernateOrmMappingInitiator.java:129)
        at org.hibernate.search.engine.common.impl.SearchIntegrationBuilderImpl$MappingBuildingState.collect(SearchIntegrationBuilderImpl.java:310)
        at org.hibernate.search.engine.common.impl.SearchIntegrationBuilderImpl.prepareBuild(SearchIntegrationBuilderImpl.java:192)
        at org.hibernate.search.mapper.orm.bootstrap.impl.HibernateOrmIntegrationBooterImpl.doBootFirstPhase(HibernateOrmIntegrationBooterImpl.java:249)
        at org.hibernate.search.mapper.orm.bootstrap.impl.HibernateOrmIntegrationBooterImpl.bootNow(HibernateOrmIntegrationBooterImpl.java:194)
        at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:616)
        at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:591)
        at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:488)
        at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1975)
        at org.hibernate.search.mapper.orm.bootstrap.impl.HibernateSearchSessionFactoryObserver.sessionFactoryCreated(HibernateSearchSessionFactoryObserver.java:41)
        at org.hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:389)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
        at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.build(FastBootEntityManagerFactoryBuilder.java:65)

您能帮我解决此异常吗?

1 个答案:

答案 0 :(得分:0)

在Hibernate Search中看起来像是一个问题,但是您的实体看起来并没有使用它。您是否有使用Hibernate Search的实体?您是在尝试自己初始化Hibernate Search而不是让Quarkus这样做吗?您是否使用了Quarkus Hibernate Search + Elasticsearch扩展?因为仅添加Hibernate Search依赖项将无法工作:您需要使用扩展名。

NPE始终是一个错误,因为如果不支持某些内容,您至少应该有一个更有意义的例外。因此,我们需要深入了解造成这种意外情况的原因。

无论如何,发布完整的复制者(即最小化该问题的应用)可能会有所帮助。