I'm very new to Hibernate.
I have a
Persons table.
Persons :
civilID (char)
name (char)
surname (char)
...
what I basically want is to select a Person and store it in HttpSession scope. so I wrote this code :
Code:
StringBuffer sb = new StringBuffer();
sb.append(" select");
sb.append(" p.civilID,");
sb.append(" p.name,");
sb.append(" p.surname");
sb.append(" from");
sb.append(" Person as p");
sb.append(" where");
sb.append(" p.civilID = :civilID");
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Person loggedInUser = (Person) session.createQuery(sb.toString()).setString("civilID", "12345").uniqueResult();
session.getTransaction().commit();
HttpSession httpSession = request.getSession();
httpSession.setAttribute("loggedInUser", loggedInUser);
1) Table 'Persons' has many more columns but I only need/want to fetch 3 of them. so I used a Query instead of load()/get(), right ? (As far as I've read, there's no way to specify the desired columns when doing load()/get() (?))
2) I always get a
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to myapp.domain.Personexception. I've read about GoF Visitor Pattern and about proxies in the documentation, but couldn't make this query to work. Hibernate executes the correct SQL, but afterwards I
always get the ClassCastException.
Also, I tried :
Code:
Person loggedInUser = (Person) session.createQuery(sb.toString()).setString("civilID", "12345").uniqueResult();
Hibernate.initialize(loggedInUser);
session.getTransaction().commit();
but the result is the same.
I tried to get() the whole row and it worked, but it fetched
all columns, but I only need three.
here's the hbm.xml file of the Person class :
Code:
<class name="Person" table="persons">
<id name="civilID"/>
<property name="name"/>
<property name="surname"/>
<... many more columns here...>
</class>
and finally the Hibernate config file :
Code:
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ybs</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping resource="myapp/domain/Person.hbm.xml"/>
</session-factory>
I need help with this, so please help !