For Hibernate configuration, We can use hibernate.cfg.xml file to configure:
1 <?xml version=‘1.0‘ encoding=‘utf-8‘?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 8 <session-factory> 9 10 <!-- Database connection settings --> 11 <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> 12 <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> 13 <property name="connection.username">sa</property> 14 <property name="connection.password"></property> 15 16 <!-- JDBC connection pool (use the built-in) --> 17 <property name="connection.pool_size">1</property> 18 19 <!-- SQL dialect --> 20 <property name="dialect">org.hibernate.dialect.HSQLDialect</property> 21 22 <!-- Enable Hibernate‘s automatic session context management --> 23 <property name="current_session_context_class">thread</property> 24 25 <!-- Disable the second-level cache --> 26 <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> 27 28 <!-- Echo all executed SQL to stdout --> 29 <property name="show_sql">true</property> 30 31 <!-- Drop and re-create the database schema on startup --> 32 <property name="hbm2ddl.auto">update</property> 33 34 <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> 35 36 </session-factory> 37 38 </hibernate-configuration>
You configure Hibernate‘s SessionFactory, SessionFactory is a glob factory responsible for a particular database.
If you have several databases, for easier startup you shuould use several <session-factory> configurations in your several configration files.
(in java code use configure("xml file name") to chose configuration which is use for.)
the first four property elements is used for configure jdbc connection.
<property name="current_session_context_class">thread</property>
In Hibernate 4.x use currentSession. So This element provide the context class.
the value thread is use for tomcat and others which server is not suport several databases.
The value can be also "jta",Jta can be used for server which is suport several databases like JBOSS.
<mapping class="com.hibernate.model.Teacher"/> This element mapping to The java calss you created.
The class must use annotation like tihs:
1 @Entity 2 @Table(name="_teacher") 3 //If Object name is not same as table‘s name, use this annotate 4 public class Teacher { 5 @Id 6 @GeneratedValue 7 //if you want to automate id. Just use @GeneratedValue 8 //by default all database can automate id 9 //When use Database which suport identity. just use @GeneratedValue(strategy = GenerationType.IDENTITY) 10 //When use database which suport sequence. just use @GeneratedValue(strategy = GenerationType.IDENTITY) 11 public int getId() { 12 return id; 13 } 14 public void setId(int id) { 15 this.id = id; 16 } 17 18 @Column(name="_name") 19 //If Object name is not same as column use this annotate 20 public String getName() { 21 return name; 22 } 23 public void setName(String name) { 24 this.name = name; 25 } 26 27 public String getTitle() { 28 return title; 29 } 30 public void setTitle(String title) { 31 this.title = title; 32 } 33 @Transient 34 //When you don‘t need to save this object to DB, just use @Transient 35 public String getYourWifeName() { 36 return yourWifeName; 37 } 38 public void setYourWifeName(String yourWifeName) { 39 this.yourWifeName = yourWifeName; 40 } 41 42 @Temporal(TemporalType.DATE) 43 //just save date and type integer database is Date 44 public Date getBrithDate() { 45 return brithDate; 46 } 47 public void setBrithDate(Date brithDate) { 48 this.brithDate = brithDate; 49 } 50 @Enumerated(EnumType.STRING) 51 //use STRING will save a string in database witch you wrote in enumerate; 52 //use ORDINAL will save a integer type in database order by enumerate elements; 53 public Zhicheng getZhicheng() { 54 return zhicheng; 55 } 56 public void setZhicheng(Zhicheng zhicheng) { 57 this.zhicheng = zhicheng; 58 } 59 60 private int id; 61 private String name; 62 private String title; 63 private String yourWifeName; 64 private Date brithDate; 65 private Zhicheng zhicheng; 66 67 }
the annotation @Entity means this class can mapping for confguration.
@Id before Getter method, that means this proprety is the primary key for table in database.
If you want save data to database. Just do like this:
At the first, you must build the SessionFactory. The SessionFactory build by configuration file (hibernat.cfg.xml). So code:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Then, you should get Session from SessionFactory. Because SessionFactory comes from the configration.
Session session = getSessionFactory().getCurrentSession();
Use getCurrentSession() method to get session. Maybe, The Session is created aready. Because getSessionFactory() get the session from context.
You can use this session until you commit it.
session.beginTransaction();
When you need to transact data, Just beginTransaction. Then you can do something for database.
session.save(d);
session.getTransaction().commit();
When you commit the session, CurrentSession will be destoryed.
The datas‘ there stats:
When you create object, It where be transient, In memory only has a object no id in map.
When you save object to databases, It wiil be prisistent, In memory has Id in map (memory will create map to mapping object by id) and It is also be saved in database.
When commit the Transactiong, It will be deteched,In memory no object, no id, But it‘s saved database already.
Select data from databases:
We can use Session.get() and Session.load()
When use get() method:
The get() method has two parameter: get(Object, Serializable);
First parameter is an Object which is used for mapping table.
Second parameter is an Serialzable object which is used for for primary key.
Use get() method, program will send SQL string to database speedy and all data you got will be set to object.
So, Even though the Session is be comiited. You can also get data from your object.
like this:
1 @Test 2 public void testGetProgramer() { 3 ProgramerPK pp = new ProgramerPK(); 4 pp.setId(1); 5 pp.setSid("123"); 6 Session session = getSessionFactory().getCurrentSession(); 7 session.beginTransaction(); 8 Programer p = (Programer)session.get(Programer.class, pp); 9 session.getTransaction().commit(); 10 System.out.println(p.getName()); 11 }
When use load() method:
The load() method has two parameter: get(Object, Serializable);
First parameter is an Object which is used for mapping table.
Second parameter is an Serialzable object which is used for for primary key.
Use load() method, program will send SQL string to database when you use Object‘s getter method.
So, If the Session is be commited. You cannot get data by Objects.getXXX().
It means you must get the data before you commit Session. Because The Object you got from load() it not yours.
It‘s Just a Proxy.
Use is like this:
1 @Test 2 public void testLoadProgramer() { 3 ProgramerPK pp = new ProgramerPK(); 4 pp.setId(1); 5 pp.setSid("123"); 6 Session session = getSessionFactory().getCurrentSession(); 7 session.beginTransaction(); 8 Programer p = (Programer)session.load(Programer.class, pp); 9 System.out.println(p.getName()); 10 session.getTransaction().commit(); 11 }