Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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;
}
}
}
------------------------------ 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"
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 (?, ?)
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"
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.: