Hibernate Detailed Tutorial
1.Create the hibernate.cfg.xml configuration file in the src directory
PS:documents of You can't change your name.!
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- configure the database setting --> <property name="connection.username">root</property> <property name="connection.password">1234</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <!-- configure the hibernate setting --> <!-- transaction is supported by org.hibernate.dialect.MySQL5InnoDBDialect --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- show sql in the console --> <property name="show_sql">true</property> <!-- create and update the database automaticlly --> <property name="hbm2ddl.auto">update</property> <!-- javax.persistence.validation.mode The default isauto of, It means that if you don't set it up it will automatically go to yourclasspath Find one below bean-validation** packet, But I can't find it., consequentlybeanvalitionFactory mistakes --> <property name="javax.persistence.validation.mode">none</property> </session-factory> </hibernate-configuration>
2. Writing entity classes, using the Person class as an example
package test.Hibernate.model; import java.util.HashSet; import java.util.Set; public class Person { @Override public String toString() { return "Person [id=" + id + ", name=" + name + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<String> getAddress() { return address; } public void setAddress(Set<String> address) { this.address = address; } private int id; private String name; private Set<String> address = new HashSet<String>(); }
3.Write Person.hbm.xml entity class configuration file
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping package="test.Hibernate.model"> <class name="Person" table="person"> <id column="id" name="id" type="int"> <generator class="native"></generator> </id> <property name="name" column="name" length="50" type="string"></property> <set name="address" table="address"> <key column="personId"></key> <element column="address" type="string" length="50"></element> </set> </class> </hibernate-mapping>
4.Add mapping information to hibernate.cfg.xml
<mapping resource="test/Hibernate/model/Person.hbm.xml" />
5.Using MyEclipse to generate SessionFactory
package test.Hibernate.SessionFactory; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class SessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private SessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
6.Writing test classes
package test.Hibernate.dao; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import test.Hibernate.SessionFactory.SessionFactory; import test.Hibernate.model.Person; public class PersonDao { @Test public void add(){ Session session = SessionFactory.getSession(); Transaction tr = session.beginTransaction(); //---------------------------------------------- Person p = new Person(); p.setName("test"); p.getAddress().add("firstAddr"); p.getAddress().add("secondAddr"); p.getAddress().add("thirdAddr"); p.getAddress().add("fourthAddr"); session.save(p); //---------------------------------------------- tr.commit(); SessionFactory.closeSession(); } @Test public void get(){ Session session = SessionFactory.getSession(); Transaction tr = session.beginTransaction(); //---------------------------------------------- Person p = (Person)session.get(Person.class, 2); System.out.println(p); //---------------------------------------------- tr.commit(); SessionFactory.closeSession(); } }
identity : Use the database's auto-growth strategy, not all databases support it, for example oracle does not.
sequence: (located) atDB2,PostgreSQL,Oracle,SAPDB,McKoi Using sequences in(sequence) in useOracle This one can be used when the database。
hilo :Generate primary key values using the high-low algorithm. Only one additional table is needed and all data is supported.
native: Based on the underlying database of Ability selectionidentity、sequence perhapshilo in of an。
assigned : Specify the primary key value manually.
uuid : The UUID is automatically generated by Hibernate and assigned as the primary key value.
1. one-to-one mapping( Using primary key associations as an example)User together withIdCard( Foreign keyed side) ofXML configure:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping package="test.Hibernate.model"> <class name="User" table="user"> <id name="id" type="int" column="id"> <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <set name="address" table="address"> <key column="userId"></key> <element column="address" type="string"></element> </set> <one-to-one name="idCard" class="IdCard" cascade="all"></one-to-one> </class> </hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping package="test.Hibernate.model"> <class name="IdCard" table="idCard"> <id name="id" type="int" column="id"> <generator class="foreign"> <param name="property">user</param> </generator> </id> <property name="number" type="string" column="number"/> <one-to-one name="user" class="User" constrained="true"></one-to-one> </class> </hibernate-mapping>
2.One to many, many to one (using Father and Children as an example)
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="test.Hibernate.model"> <class name="Father" table="father"> <id name="id" type="int" column="id" > <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <set name="children" cascade="all"> <key column="fatherId"></key> <one-to-many class="Children"/> </set> </class> </hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="test.Hibernate.model"> <class name="Children" table="children"> <id name="id" type="int" column="id" > <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <many-to-one name="father" class="Father" column="fatherId"></many-to-one> </class> </hibernate-mapping>
3.Many-to-many (Student and Teacher as an example)
PS: Set sets with one side should be marked inverse=true (more on that later)
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping package="test.Hibernate.model"> <class name="Student" table="student"> <id name="id" type="int" column="id"> <generator class="native"></generator> </id> <property name="name" type="string" column="name" length="20"/> <set name="teachers" table="student_teacher" inverse="false" > <key column="studentId"></key> <many-to-many class="Teacher" column="teacherId"></many-to-many> </set> </class> </hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping package="test.Hibernate.model"> <class name="Teacher" table="teacher"> <id name="id" type="int" column="id"> <generator class="native"></generator> </id> <property name="name" column="name" type="string" length="20"></property> <set name="students" table="student_teacher" inverse="true" cascade="all"> <key column="teacherId"></key> <many-to-many class="Student" column="studentId"></many-to-many> </set> </class> </hibernate-mapping>
1.inverse=false on a one-to-many delete sets the child's foreign key to null, then deletes the father, and the child is not deleted, while casecade=all on a one-to-many delete sets the child's foreign key to null, then deletes the father, then deletes the child
2.manytomany of When maintained by one party, consequently One party is to setinverse=false, neverthelessinverse=true of Direct deletion by the other party will result in an error, This time you can usecasecade Complete cascade deletion
3.inverse=false For use onlyset etc. set attributes, (located) atonetoone The relationship can be used incasecade Complete cascade deletion
1. Additional import required3 sizejar packet
2.Add C3P0 configuration information to hibernate.cfg.xml
<!-- C3P0 Connection pool settings--> <!-- usec3p0 connection pool Configuring the connection pool provides of suppliers--> <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!-- Available in the connection pool of Database connection of Minimum number --> <property name="c3p0.min_size">5</property> <!-- All database connections in the connection pool of maximum number --> <property name="c3p0.max_size">20</property> <!-- Setting up a database connection of expiration date, in seconds, If the connection pool in of A database connection is idle of More time thantimeout times, will be cleared from the connection pool --> <property name="c3p0.timeout">120</property> <!-- each3000 Seconds to check all connections in the pool of idle connection in seconds--> <property name="c3p0.idle_test_period">3000</property>
@Test public void HQLSearch(){ Session session = SessionFactory.getSession(); Transaction tr = session.beginTransaction(); //----------------------------------------- //common search with where // String hql= "select e.id,e.name from User e where e.id>=5 and e.id<=9"; // Query query = session.createQuery(hql); // List list = query.list(); // for(Object o : list){ // System.out.println(Arrays.toString((Object[])o)); // } //paging search // String hql= "select e.id,e.name from User e"; // Query query = session.createQuery(hql); // query.setFirstResult(0); // query.setMaxResults(10); // List list = query.list(); // for(Object o : list){ // System.out.println(Arrays.toString((Object[])o)); // } //search with parameters // String hql= "select e.id,e.name from User e where id>=? and id<=?"; // Query query = session.createQuery(hql) // .setParameter(0, 1) // .setParameter(1, 3); // List list = query.list(); // for(Object o : list){ // System.out.println(Arrays.toString((Object[])o)); // } //search with parameters whose type is collection // String hql= "select e.id,e.name from User e where id in (:ids)"; // Query query = session.createQuery(hql) // .setParameterList("ids",new Object[]{1,2,3,8} ); // List list = query.list(); // for(Object o : list){ // System.out.println(Arrays.toString((Object[])o)); // } //----------------------------------------- tr.commit(); SessionFactory.closeSession(); }
@Test public void DML(){ Session session = SessionFactory.getSession(); Transaction tr = session.beginTransaction(); //----------------------------------------- User u = (User)session.get(User.class, 11); String sql = "update User set name=? where id>?"; int result = session.createQuery(sql) .setParameter(0, "updated") .setParameter(1, 10) .executeUpdate(); System.out.println("count of update:"+result); //the object's status in session was not updated when the object in database have been changed,so if you want //to get the updated object in session,you should use method "refresh". session.refresh(u); System.out.println(u); //----------------------------------------- tr.commit(); SessionFactory.closeSession(); }
1. The following jar packages need to be imported
2.Add the following configuration to hibernate.cfg.xml
<!-- Use of L2 cache, Default is unopened of。 --> <!-- Specify that you want to use the of buffer memory of provider (company), This also opens the secondary cache--> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- Enabling the use of query caching --> <property name="cache.use_query_cache">true</property> <!-- Specify that you want to use the L2 cache of physical category --> <class-cache usage="read-write" class="test.Hibernate.model.Person" />