Sei sulla pagina 1di 7

Pain point, why we are using hbernate

Mapping member variables to columns


Mapping relationships
Handling Datatypes
Managing changes to the object state
These are something we need to handle ourselves. Many ties because of all these problems, we will
not worry too much abt object relationships.

What we have to do in hibernate:


1. JDBC configuration hibernate config
2. Model object - Annotations
3. Service methods to create model objects The (HIBERNATE) API
4. Database Design Not Required. (Hibernate does it)
5. BIGGEST CHALLENGE DAO method to save object using SQL queries Not Required
Coding:
1. Write Hibernate Configuration file hibernate.cfg.xml
By default hibernate searches configuratin in file which has this name. Otherwise you have to
define it explixitly. We'refonna stick with this only.
It wil looksomething like this:
<?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">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgres://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.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">create</property>
<!-- Names the annotated entity class -->
<mapping class="org.hibernate.tutorial.annotations.Event"/>
</session-factory>
</hibernate-configuration>

2. writing model class:

package org.koushik.javabrains.dto;
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;
}
}

3. Instantiating model class


USING HiberNate API
1. Create a session factory
2. Create a session from a session factory
3. use the session to save model objects
package org.koushik.javabrains;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.koushik.javabrains.dto.UserDetails;
public class HibernateTest {
/**
* @param args
*/
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("FirstUser");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();//Create a
session factory
Session session = sessionFactory.openSession();//Create a session from a session factory
session.beginTransaction(); //use the session to begin transaction
session.save(user); //use the session to save model objects
session.getTransaction().commit(); //use the session to end transaction
}

}
------------------------------ OR -------------------------------------------package org.koushik.javabrains;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.koushik.javabrains.dto.UserDetails;
public class HibernateTest {
/**
* @param args
*/
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("FirstUser");
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}

HBM2DDL :
now if you create a second user,
user.setUserId(2);
user.setUserName("SecondUser");
the program will run successfully, but when you query select * from userdetails; , what you will get:
2;"SecondUser"
Somehow, he first user get deleted,
How????
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
this tag says, Drop and recreate the database schema on start up. That is when you run the same program which will
create the sessionfactory and session. Hibernate will drop the existing schema and recreates a new one.
The way tochange it ad retain data:
<property name="hbm2ddl.auto">update</property>
Now hibernatewill ONLY change the schema when it will find a change in the Model Class.

Now:
user.setUserId(3);
user.setUserName("ThirdUser");
the program will run successfully, but when you query select * from userdetails; , what you will get:
2;"SecondUser"
3;"ThirdUser"

<!-- Echo all executed SQL to stdout -->


<property name="show_sql">true</property>
: will print all the queries tostdout : console output e.g.
NFO: HHH000126: Indexes: [userdetails_pkey]
6 Nov, 2014 9:38:51 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: insert into UserDetails (userName, userId) values (?, ?)

Now Let us make some changes in the model class, because now hibernate takes some defaults in
making the table design and inserting values as of now cuz we made a very simple though effective
program.
1st default : table name : default: UserDetails
what if we change name to User, which database will not allowed as it is a restricted Keyword.
Same thing goes for field name.
Way to deal with that: @Entity(name = "USER_DETAILS")
OUTPUT:
INFO: HHH000262: Table not found: USER_DETAILS
6 Nov, 2014 9:47:20 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: insert into USER_DETAILS (userName, userId) values (?, ?)

For Fields:
@Id
@Column(name="USER_ID")
private int userId;
@Column(name="USER_NAME")
private String userName;
INFO: HHH000397: Using ASTQueryTranslatorFactory
6 Nov, 2014 9:53:19 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS cascade
Hibernate: create table USER_DETAILS (USER_ID int4 not null, USER_NAME varchar(255), primary key
(USER_ID))
6 Nov, 2014 9:53:19 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into USER_DETAILS (USER_NAME, USER_ID) values (?, ?)

We can also put these annotations above getter methods also:


private int userId;
private String userName;
@Id
@Column(name="USER_ID")
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Column(name="USER_NAME")
public String getUserName() {
return userName + from getter;
}
public void setUserName(String userName) {
this.userName = userName;
}
RUN and output:
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS cascade
Hibernate: create table USER_DETAILS (USER_ID int4 not null, USER_NAME varchar(255), primary key
(USER_ID))
6 Nov, 2014 9:57:52 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into USER_DETAILS (USER_NAME, USER_ID) values (?, ?)

3;"ThirdUser from getter"


i.e. Hibernates takes values from the getter

A Few more annotations:


@Entity
@Table(name="USER_DETAILS")
public class UserDetails {

How is this different from @Entity(name = "USER_DETAILS")


using name property in @Entity, you are providing a name for the Entity which is created itself
but with @Table you are providing a name for the table which is created for the entity.
==> Used in HQL Later.
If you dont want the field to get saved in the DB just mark it as static or Transient OR use @Transient above that
field.

private Date joinedDate;

what hibernate has done is mapped the Date to TimeStamp without Time Zone which in DB table will reflect as
"2014-11-06 10:15:08.646"
what if you only want date not hour.
@Temporal(TemporalType.DATE)
private Date joinedDate;
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS cascade
Hibernate: create table USER_DETAILS (userId int4 not null, address varchar(255), description varchar(255),
joinedDate date, userName varchar(255), primary key (userId))
6 Nov, 2014 10:20:40 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into USER_DETAILS (address, description, joinedDate, userName, userId) values (?, ?, ?, ?, ?)
"2014-11-06"

private String description;


Now hibernate will mapString to varchar(255) but what if i want to write more than 255 characters.
Use @Lob : LargeObject

******** Now if we want to fetch


session.close();
//make user obj null
user = null;
//open a new session to fetch whatever you wrote in DB
session = sessionFactory.openSession();
session.beginTransaction();
//how do i fetch
user = (UserDetails) session.get(UserDetails.class, 1);

get wi retrieve the object of UserDetails.class with primary key's value = 1, as the row in DB
corresponds to the instance of the Entity class.
INFO: HHH000397: Using ASTQueryTranslatorFactory
7 Nov, 2014 12:14:02 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists USER_DETAILS cascade
Hibernate: create table USER_DETAILS (userId int4 not null, address varchar(255), description varchar(255),
joinedDate timestamp, userName varchar(255), primary key (userId))
7 Nov, 2014 12:14:03 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete

Hibernate: insert into USER_DETAILS (address, description, joinedDate, userName, userId) values (?, ?, ?, ?, ?)
Hibernate: select userdetail0 .userId as userId1_0_0_, userdetail0_.address as address2_0_0_, userdetail0_.description
as descript3_0_0_, userdetail0_.joinedDate as joinedDa4_0_0_, userdetail0_.userName as userName5_0_0_ from
USER_DETAILS userdetail0_ where userdetail0_.userId=?
User retrieved is First User
it is doing a SELECT query because of session.get()
saving that object into user and user.getUserName is printing the user name
DONE!!!!!!
We'll look later torun QL and write SQL queries directly.
**** What does @Id do:
created a primary key column in the table.use this primary key in fetching the data.
Other ways how hibernate supports primary key.
Natural Key and Surrogate key.:

Potrebbero piacerti anche