There are many ways to retrieve values from a table. Below example is one of doing it. Note that
since the table has already been generated and has some values in it, we set the value of "hbm2ddl.auto"
to update.
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">hr</property> <property name="connection.password">hr</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.OracleDialect</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> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <!-- Names the annotated entity class --> <mapping class="com.ram.dao.UserDetails"/> </session-factory> </hibernate-configuration>
package com.ram.dao; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class UserDetails { @Id private int userId; private String userName; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
package com.ram.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.ram.dao.UserDetails; public class RetrieveObjectsExample { public static void main(String[] args) { UserDetails userDetails = new UserDetails(); SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); //session.get() will retrieve the value from the data base userDetails = (UserDetails)session.get(UserDetails.class, 1); System.out.println("UserName of Id 1 is "+userDetails.getUserName()); session.close(); } }
No comments:
Post a Comment