WebSphere没有为查询类找到持久化类

时间:2015-05-18 21:59:17

标签: java hibernate websphere environment entitymanager

我是WebSphere的新手,我正在尝试托管一个可以使用Oracle数据库登录的简单网站。

我可以访问我的网站,但是当我尝试登录时,我收到以下警告,但无法登录:

[WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null.
[WARNING ] HHH000183: no persistent classes found for query class: select a FROM com.model.User a where username = 'user'
 No entity found for query

当我尝试创建查询以在我的CommonServiceImple.java中登录时,会抛出警告no persistent classes found for query class:Query query = getEntityManager().createQuery("select a FROM " + className + " a where username = '" + username + "'");

No entity found for query是在尝试运行查询的下一行中引起的。这是因为query对象因前面的警告而为空:Object obj = query.getSingleResult();

server.xml中

<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
    <jdbcDriver id="oracle-driver" libraryRef="oracle-lib">
        <library></library>
    </jdbcDriver>
    <connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
    <properties.oracle URL="jdbc:oracle:thin:@crappie.ddvc.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
    <fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>

的web.xml

<resource-ref>
    <description>DataSource</description>
    <res-ref-name>jdbc/test</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    <mapped-name>jdbc/test</mapped-name>
</resource-ref>

IBM的Web-bnd.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-bnd 
    xmlns="http://websphere.ibm.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
    version="1.0">

    <virtual-host name="default_host" />
    <resource-ref name="jdbc/test" binding-name="jdbc/test"/>
</web-bnd>

的persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="pu1">  
    </persistence-unit>
</persistence>

的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="commonService" class="com.service.CommonServiceImpl"/>
    <bean id="mainMenuService" class="com.service.MainMenuServiceImpl"/>
    <bean id="storeFilterService" class="com.service.StoreFilterServiceImpl"/>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean
                class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="ORACLE" />
                <property name="showSql" value="true" />
            </bean>
        </property>
        <property name="persistenceUnitManager" ref="pum"/>
        <property name="persistenceUnitName" value="pu1" />
        <property name="jpaProperties">
            <props>
                <prop key="org.hibernate.envers.store_data_at_delete">true</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>jdbc/test</value>
        </property>
        <property name="cache" 
            value="true"/>
        <property name="lookupOnStartup"
            value="true"/>
        <property name="resourceRef"
            value="true"/>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="pum"
        class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="persistenceXmlLocations">
            <list>
                <value>classpath:META-INF/persistence.xml</value>
            </list>
        </property>
        <property name="defaultDataSource" ref="dataSource"></property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="loginAction" scope="prototype" class="com.action.LoginAction">
        <constructor-arg ref="commonService" />
    </bean>

    <bean id="userAction" scope="prototype" class="com.action.UserAction">
        <constructor-arg ref="commonService" />
    </bean>
</beans>

User.java没有什么有趣的东西

@Entity
@Table(name="WEB_PAGE_USERS")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO, generator="seq")
    @SequenceGenerator(name="seq", sequenceName="WEB_PAGE_USERS_ID_SEQ")
    private Integer id;
    private String username;
    private String password;
    private String name;
//...
}

或ComonServiceImpl.java

@Transactional
public class CommonServiceImpl implements CommonService{
    private EntityManager em;

    @PersistenceContext(unitName="pu1")
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    // MTD added for explicit order by
    @SuppressWarnings("unchecked")
    public List<Object> findAll(String name) {
        getEntityManager().clear();
        String sql = "select a FROM " + name + " a";

        Query query = getEntityManager().createQuery(sql);

        return query.getResultList();
    }
//...(other sql selects, updates, inserts)
}

LoginAction.java

public class LoginAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private CommonService service;

    private String username;
    private String password;

    private String environment;

    public LoginAction(CommonService service) {
        this.service = service;
    }

    public String execute() throws Exception {
        return Action.SUCCESS;
    }

    @SuppressWarnings({ "unchecked", "static-access" })
    public String login() throws Exception {
        //Encrypt input password
        CEncrypt cEncrypt = new CEncrypt();
        String encryptedPwd = cEncrypt.encryptString(password);

        //Get user by Username
        User user = (User) service.findUser(username, User.class.getName());

        //Check if input password is the same as the password in the database & login
        if (user!=null && user.getPassword().equals(encryptedPwd)) {
            @SuppressWarnings("rawtypes")
            Map session = ActionContext.getContext().getSession();
            session.put("logged-in","true");
            session.put("loggedIn", "true");
            session.put("WebAdminUserID", user.getUsername());
            session.put("WebAdminUsername", user.getName());
            session.put("WebAdminID", user.getRole_id());

            return Action.SUCCESS;
        } else {
            return Action.ERROR;
        }
    }
//...
}

更新

我能够通过手动调用查找来测试我与数据源的连接。但由于我的网站建立在持久性单元上,我想修复该错误,而不是重新编写项目以直接调用连接:

public String getEnvironment() {
    try
    {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource test = (DataSource)envCtx.lookup("jdbc/test");

        Connection con = test.getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("select * from WEB_PAGE_USERS where username = 'user'");

        while(rs.next()){
            System.out.println("username="+rs.getString("username")+", password="+rs.getString("password")+", role id="+rs.getString("role_id"));
        }

        //            environment = "[" + (String)envCtx.lookup("Environment") + "]";
    } catch (Exception e)
    {
        System.out.println("Environment Exception: " + e.getMessage());
    }
    return environment;
}

哪个会返回正确的数据username=user, password=password, role id=1

1 个答案:

答案 0 :(得分:0)

为了解决我的问题,我必须将我使用@Entity注释的每个模型类添加到我的persistence.xml文件中。似乎即使我使用的是entityManager,我仍然需要指定所有@Entity类(通常在Tomcat中,entityManager会自动找到所有类)。

此外,我收到[WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null.警告,导致我的会话在每次加载页面时被清除(使得难以保持登录状态)。所以我在WebSphere上的server.xml中将长度增加到了28。

server.xml中

<server description="new server">

    <!-- Enable features -->
    <featureManager>
        <feature>jsp-2.2</feature>
        <feature>jndi-1.0</feature>
        <feature>jdbc-4.0</feature>
        <feature>localConnector-1.0</feature>
        <feature>servlet-3.0</feature>
        <feature>jaxrs-1.1</feature>
    </featureManager>

    <!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
    <httpEndpoint host="localhost" httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>

    <dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
        <jdbcDriver id="oracle-driver" libraryRef="oracle-lib"/>
        <connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
        <properties.oracle URL="jdbc:oracle:thin:@crappie.local:1521:STILOG" password="password" user="user"/>
    </dataSource>

    <library id="oracle-lib">
        <fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
    </library>


    <applicationMonitor updateTrigger="mbean"/>

    <webApplication id="WebAdmin" location="WebAdmin.war" name="WebAdmin"/>

    <httpSession idLength="28"></httpSession>
</server>

的persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="pu1">
        <class>com.model.App</class>
        <class>com.model.AudioType</class>
        <class>com.model.AuditRevisionEntity</class>
        <class>com.model.ClosedGroup</class>
        <class>com.model.ClosedSchedule</class>
        <class>com.model.ClosedScheduleGroup</class>
        <class>com.model.Department</class>
        <class>com.model.Dnis</class>
        <class>com.model.DnisVoiceTalent</class>
        <class>com.model.GlobalXferGroupTemplate</class>
        <class>com.model.Language</class>
        <class>com.model.Location</class>
        <class>com.model.MainMenu</class>
        <class>com.model.NameValue</class>
        <class>com.model.NameValueFunction</class>
        <class>com.model.NameValueType</class>
        <class>com.model.Peg</class>
        <class>com.model.PegType</class>
        <class>com.model.PharmacyConfig</class>
        <class>com.model.Promo</class>
        <class>com.model.PromoMessage</class>
        <class>com.model.PromoSchedule</class>
        <class>com.model.PromoType</class>
        <class>com.model.Role</class>
        <class>com.model.Schedule</class>
        <class>com.model.ScheduleHours</class>
        <class>com.model.ScheduleRecording</class>
        <class>com.model.ScheduleType</class>
        <class>com.model.Server</class>
        <class>com.model.SpecialSchedule</class>
        <class>com.model.SpecialScheduleRecording</class>
        <class>com.model.Store</class>
        <class>com.model.StoreAudio</class>
        <class>com.model.StoreClosedGroup</class>
        <class>com.model.StoreDepartment</class>
        <class>com.model.StorePromo</class>
        <class>com.model.StoreSchedule</class>
        <class>com.model.StoreSpcSchedule</class>
        <class>com.model.StoreType</class>
        <class>com.model.StoreXferGroup</class>
        <class>com.model.SystemMaintenance</class>
        <class>com.model.TargetSystem</class>
        <class>com.model.Timezone</class>
        <class>com.model.Title</class>
        <class>com.model.User</class>
        <class>com.model.UserWebPage</class>
        <class>com.model.UserWebPageAccess</class>
        <class>com.model.UserWebPageClassType</class>
        <class>com.model.VoiceTalent</class>
    </persistence-unit>
</persistence>