JPA查询未返回数据

时间:2016-11-30 20:00:44

标签: java spring hibernate jpa

我使用的是spring 4.3.4和JPA / hibernate 5.2.5。我正在尝试一个简单的查询select u from AppUser u它不会返回任何结果。我正在使用容器管理实体管理器。我可以在这里列出没有例外。 我不确定这是设置问题还是代码的其余部分。

这里是JpaConfig:

@Configuration
@EnableTransactionManagement
public class JpaConfig {

    @Bean
    public DataSource getDataSource() throws Exception {
        Context context = new InitialContext();


        DataSource source = (DataSource) context.lookup("java:/comp/env/jdbc/mydb");
        return source;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {

        final String[] packageToScan = new String[] { "entity" };

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

        factory.setPersistenceProvider(new HibernatePersistenceProvider());
        factory.setPackagesToScan(packageToScan);
        factory.setJpaProperties(additionalProperties());
        try {
            factory.setDataSource(getDataSource());
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (Exception e){}
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

    Properties additionalProperties() {
        Properties properties = new Properties();

        return properties;
    }

}

实体类:

@Entity
public class AppUser {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String firstName;
    private String lastName;
    private String middleName;
    @OneToOne
    private Email email;

    private boolean isActive;

    // getters and setters

}


@Entity
public class Email {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String emailAddress; 

    // getters and setters

}

在控制器中:

@Controller
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
    private static byte count = 0;

    @PersistenceContext
    private EntityManager entityManager;

    @RequestMapping("/")
    public String indexPage(Model model) {

        TypedQuery<AppUser> query = entityManager.createQuery("select u from AppUser u", AppUser.class);

        List<AppUser> users =  query.getResultList();
        for(AppUser u : users) {
            u.getFirstName();
            u.getLastName();
            u.getEmail().getEmailAddress();
            u.getId();

        }
        return "index";
    }
}

最后一些日志可能对知识渊博有用:

  2016 Nov 30 14:17:30,635 254628 [tomcat-http--3] DEBUG org.hibernate.hql.internal.ast.QueryTranslatorImpl  - --- SQL AST ---
 \-[SELECT] QueryNode: 'SELECT'  querySpaces (AppUser)
    +-[SELECT_CLAUSE] SelectClause: '{select clause}'
    |  +-[ALIAS_REF] IdentNode: 'appuser0_.id as id1_0_' {alias=u, className=com.ups.iam.isrs.entity.AppUser, tableAlias=appuser0_}
    |  \-[SQL_TOKEN] SqlFragment: 'appuser0_.email_id as email_id6_0_, appuser0_.firstName as firstNam2_0_, appuser0_.isActive as isActive3_0_, appuser0_.lastName as lastName4_0_, appuser0_.middleName as middleNa5_0_'
    \-[FROM] FromClause: 'from' FromClause{level=1, fromElementCounter=1, fromElements=1, fromElementByClassAlias=[u], fromElementByTableAlias=[appuser0_], fromElementsByPath=[], collectionJoinFromElementsByPath=[], impliedElements=[]}
       \-[FROM_FRAGMENT] FromElement: 'AppUser appuser0_' FromElement{explicit,not a collection join,not a fetch join,fetch non-lazy properties,classAlias=u,role=null,tableName=AppUser,tableAlias=appuser0_,origin=null,columns={,className=com.ups.iam.isrs.entity.AppUser}}

2016 Nov 30 14:17:30,635 254628 [tomcat-http--3] DEBUG org.hibernate.hql.internal.ast.ErrorCounter  - throwQueryException() : no errors
2016 Nov 30 14:17:30,655 254648 [tomcat-http--3] DEBUG org.hibernate.hql.internal.ast.QueryTranslatorImpl  - HQL: select u from com.ups.iam.isrs.entity.AppUser u
2016 Nov 30 14:17:30,655 254648 [tomcat-http--3] DEBUG org.hibernate.hql.internal.ast.QueryTranslatorImpl  - SQL: select appuser0_.id as id1_0_, appuser0_.email_id as email_id6_0_, appuser0_.firstName as firstNam2_0_, appuser0_.isActive as isActive3_0_, appuser0_.lastName as lastName4_0_, appuser0_.middleName as middleNa5_0_ from AppUser appuser0_
2016 Nov 30 14:17:30,655 254648 [tomcat-http--3] DEBUG org.hibernate.hql.internal.ast.ErrorCounter  - throwQueryException() : no errors
2016 Nov 30 14:19:41,525 385518 [tomcat-http--3] DEBUG org.hibernate.SQL  - select appuser0_.id as id1_0_, appuser0_.email_id as email_id6_0_, appuser0_.firstName as firstNam2_0_, appuser0_.isActive as isActive3_0_, appuser0_.lastName as lastName4_0_, appuser0_.middleName as middleNa5_0_ from AppUser appuser0_
2016 Nov 30 14:19:41,571 385564 [tomcat-http--3] DEBUG org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl  - Initiating JDBC connection release from afterTransaction
2016 Nov 30 14:19:59,099 403092 [tomcat-http--3] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils  - Closing JPA EntityManager
2016 Nov 30 14:20:13,721 417714 [tomcat-http--3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory  - Invoking afterPropertiesSet() on bean with name 'index'
2016 Nov 30 14:20:13,721 417714 [tomcat-http--3] DEBUG org.springframework.web.servlet.DispatcherServlet  - Rendering view [org.springframework.web.servlet.view.InternalResourceView: name 'index'; URL [/WEB-INF/views/index.jsp]] in DispatcherServlet with name 'dispatcher'
2016 Nov 30 14:20:13,722 417715 [tomcat-http--3] DEBUG org.springframework.web.servlet.view.InternalResourceView  - Added model object 'message' of type [java.lang.Byte] to request in view with name 'index'

0 个答案:

没有答案