views:

63

answers:

1

I am new to hibernate and I am having some trouble with the named query annotation. My code is as follows and is more or less generated by NetBeans

The BasicUser class:

    package wmc.model;

    import java.io.Serializable;
    import javax.persistence.Basic;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import org.hibernate.annotations.NamedQueries;
    import org.hibernate.annotations.NamedQuery;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;

    @Entity
    @Table(name = "basic_user")
    @NamedQueries({
        @NamedQuery(name = "BasicUser.findAll", query = "SELECT b FROM BasicUser b"),
        @NamedQuery(name = "BasicUser.findByFirstName", query = "SELECT b FROM BasicUser b WHERE b.firstName = :firstName"),
        @NamedQuery(name = "BasicUser.findByLastName", query = "SELECT b FROM BasicUser b WHERE b.lastName = :lastName"),
        @NamedQuery(name = "BasicUser.findByEmail", query = "SELECT b FROM BasicUser b WHERE b.email = :email"),
        @NamedQuery(name = "BasicUser.findByPassword", query = "SELECT b FROM BasicUser b WHERE b.password = :password")})
    public class BasicUser implements Serializable {
        private static final long serialVersionUID = 1L;
        @Basic(optional = false)
        @Column(name = "First_Name")
        private String firstName;
        @Basic(optional = false)
        @Column(name = "Last_Name")
        private String lastName;
        @Id
        @Basic(optional = false)
        @Column(name = "Email")
        private String email;
        @Basic(optional = false)
        @Column(name = "Password")
        private String password;
        @OneToOne(cascade = CascadeType.ALL, mappedBy = "basicUser")
        private StatUser statUser;
        @JoinColumn(name = "Group_Name", referencedColumnName = "Group_Name")
        @ManyToOne(optional = false)
        private Groups groupName;

        public BasicUser() {
        }
...

And the hibernate.cfg.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://mysql.dinhost.net:3306/coffeedrinkers</property>
    <property name="hibernate.connection.username">bla</property>
    <property name="hibernate.connection.password">bla</property>
  </session-factory>
</hibernate-configuration>

This is where i try using the query:

public static boolean userExists(String email, String password) {
        Session session = null;

          try{

            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

            session =sessionFactory.openSession();

            Object object = session.getNamedQuery("wmc.model.BasicUser.findByEmail").
                    setString("email", email).uniqueResult();
            BasicUser user = (BasicUser) object;

            if(user != null && user.getPassword().equals(password)) {
                return true;
            }
          }
          catch(Exception e) {
              e.printStackTrace();
          }

          return false;

    }

As I understand it i do not have to make any mapping xml's as this information is in the annotations.

I appreciate any help. Thank you in advance:)

persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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"&gt;
  <persistence-unit name="WMCPU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>coffeee</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>
</persistence>

and the sun-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd"&gt;
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_coffeedrinkers_AnAmuserPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="mysql.dinhost.net"/>
        <property name="portNumber" value="3306"/>
        <property name="databaseName" value="coffeedrinkers"/>
        <property name="User" value="bla"/>
        <property name="Password" value="bla"/>
        <property name="URL" value="jdbc:mysql://mysql.dinhost.net:3306/coffeedrinkers"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" pool-name="mysql_coffeedrinkers_AnAmuserPool" jndi-name="coffeee"  object-type="user"/>
</resources>
+1  A: 

The name of you named query is really its name, don't prefix it when calling getNamedQuery

 BasicUser user = (BasicUser) session.getNamedQuery("BasicUser.findByEmail").
         setString("email", email).uniqueResult();

By the way, since you're using JPA annotations, you should favor the JPA API over Hibernate API (i.e. JPA's EntityManager over Hibernate's Session).

Pascal Thivent
Now I've done what you said and used EntityManager instead of Session. Now I get the following error:08-07-2010 16:49:25 org.hibernate.connection.DatasourceConnectionProvider configureSEVERE: Could not find datasource: coffeeejavax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
AnAmuser
@AnAmuser: Are you running this code inside GlassFish? If you're not, I guess you need to provide a `jndi.properties` file with the appropriate parameters, see [this previous answer](http://stackoverflow.com/questions/2759300/how-to-set-up-jndi-properties-for-datastore/2759542#2759542). But that's a very different question that I can't cover in the comment box. If you are, the initial factory should be set. But as I said, this is really a different problem. You should open a new question for the sake of clarity (one question = one problem).
Pascal Thivent