<?xml version="1.0" encoding="GBK"?> <project name="hibernate" basedir="." default=""> <property name="src" value="src"/> <property name="dest" value="classes"/> <path id="classpath"> <fileset dir="../../lib"> <include name="**/*.jar"/> </fileset> <pathelement path="${dest}"/> </path> <target name="compile" description="Compile all source code"> <delete dir="${dest}"/> <mkdir dir="${dest}"/> <copy todir="${dest}"> <fileset dir="${src}"> <exclude name="**/*.java"/> </fileset> </copy> <javac destdir="${dest}" debug="true" includeantruntime="yes" deprecation="false" optimize="false" failonerror="true"> <src path="${src}"/> <classpath refid="classpath"/> <compilerarg value="-Xlint:deprecation"/> </javac> </target> <target name="run" description="Run the main class" depends="compile"> <java classname="lee.PersonManager" fork="yes" failonerror="true"> <classpath refid="classpath"/> </java> </target> </project>
<?xml version="1.0" encoding="GBK"?> <! - Specifies the Hibernate configuration file DTD information -> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <-! Hibernate-configuration profile is the root element -> <hibernate-configuration> <session-factory> <! - Specifies the database connection for driving -> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <! - url specified connection database, wherein the database is the name of the present application hibernate connection -> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <! - Specifies the user name connected to the database -> <property name="connection.username">root</property> <! - Specifies the password for connecting to the database -> <property name="connection.password">32147</property> <! - Specifies the maximum number of connections the connection pool -> <property name="hibernate.c3p0.max_size">20</property> <! - specifies the minimum number of connections connecting pool -> <property name="hibernate.c3p0.min_size">1</property> <! - Specifies the time-out connection connected to the pool length -> <property name="hibernate.c3p0.timeout">5000</property> <! - Specifies the number of connection pool maximum cache Statement object -> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">true</property> <! - Specify the database dialect -> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <-! Required automatically create the database -> <property name="hbm2ddl.auto">update</property> <! - Display Hibernate persistence operations generated SQL -> <property name="show_sql">true</property> <! - SQL script will be formatted and then output -> <property name="hibernate.format_sql">true</property> <! - class lists names of all persistent classes -> <mapping class="org.crazyit.app.domain.Person"/> <mapping class="org.crazyit.app.domain.Address"/> </session-factory> </hibernate-configuration>
package lee; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.service.*; import org.hibernate.boot.registry.*; /** * Description: * <br/> website: <a href=" http://www.crazyit.org "> crazy Java league </a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * Author YeekuHLee kongyeeku163com * @Version 1.0 * / public class HibernateUtil { public static final SessionFactory sessionFactory; static { try { // create a Configuration instance using the default hibernate.cfg.xml configuration file Configuration cfg = new new Configuration () .configure(); // to Configuration instance to create SessionFactory instance ServiceRegistry ServiceRegistry = new new StandardServiceRegistryBuilder () .applySettings(cfg.getProperties()).build(); sessionFactory = cfg.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } // the ThreadLocal can isolate a plurality of threads to share data, eliminating the need to thread synchronization public static Final the ThreadLocal <the Session> the session = new new the ThreadLocal <the Session> (); public static Session currentSession() throws HibernateException { S the Session = Session.get (); // If the thread has not Session, create a new the Session IF (S == null ) { S = sessionFactory.openSession (); // the Session variables obtained ThreadLocal variable stored in the session in session.set (s); } return s; } public static void closeSession() throws HibernateException { Session s = session.get(); if (s != null) s.close(); session.set(null); } }
package lee; import org.hibernate.Transaction; import org.hibernate.Session; import java.util. * ; import org.crazyit.app.domain. * ; / ** * Description: * <br/> website: <a href=" http://www.crazyit.org "> crazy Java league </a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * Author YeekuHLee kongyeeku163com * @version 1.0 */ public class PersonManager { public static void main(String[] args) { PersonManager mgr = new PersonManager(); mgr.createAndStorePerson(); HibernateUtil.sessionFactory.close(); } private void createAndStorePerson() { Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction(); // 创建Person对象 Person person = new Person(); person.setAge ( 29 ); // set values for the two members of the composite primary key person.setFirst ( "crazyit.org" ); person.setLast ( "Crazy Java Alliance" ); A1 Address = new new Address ( "Tianhe" ); a1.setPerson (person); A2 Address = new new Address ( "Shanghai Hongkou" ); a2.setPerson (person); // first save the primary table entity Session.save (Person); // then save the entity from the table session.save (a1); session.save(a2); tx.commit(); HibernateUtil.closeSession(); } }
package org.crazyit.app.domain; import javax.persistence.*; /** * Description: * <br/> website: <a href=" http://www.crazyit.org "> crazy Java league </a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * Author YeekuHLee kongyeeku163com * @version 1.0 */ @Entity @Table(name="address_inf") public class Address { // identifier attribute the @Id @Column (name = "address_id" ) @GeneratedValue (at Strategy = GenerationType.IDENTITY) Private int AddressID; // define the address details representatives of member variables Private String addressDetail; // the Person entity records associated with the Address entity the @ManyToOne (. TargetEntity = the Person class ) // use @ JoinColumns comprising a plurality @JoinColumn define the foreign key column @JoinColumns ({ // Since the main table of the composite primary key (primary key a plurality of columns) // need to use the plurality @JoinColumn define the foreign key columns of the plurality of reference table person_inf primary key column @JoinColumn (name = "person_first" , the referencedColumnName = "First", = Nullable to false ), @JoinColumn(name="person_last" , referencedColumnName="last" , nullable=false) }) Private the Person Person; // no argument constructor public the Address () { } // constructor to initialize all the member variables public Address (String addressDetail) { this.addressDetail = addressDetail; } // AddressID setter and getter methods public void setAddressId ( int AddressID) { this.addressId = addressId; } public int getAddressId() { return this.addressId; } // addressDetail的setter和getter方法 public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } public String getAddressDetail() { return this.addressDetail; } // the Person of the setter and getter methods public void setPerson (the Person the Person) { this.person = person; } public Person getPerson() { return this.person; } }
package org.crazyit.app.domain; import java.util. * ; import javax.persistence.*; /** * Description: * <br/> website: <a href=" http://www.crazyit.org "> crazy Java league </a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * Author YeekuHLee kongyeeku163com * @version 1.0 */ @Entity @Table(name="person_inf") public class Person implements java.io.Serializable { // define the first member variables, as members of identifying attributes of the @Id Private String first; // define the last member variables, as members of identifying attributes of the @Id Private String last; Private int Age; // All Address records associated with that entity Person entity @OneToMany (. = the targetEntity the Address class , the mappedBy = "Person" , Cascade = CascadeType.ALL in) Private the Set <the Address> Addresses = new new HashSet <> (); // First in the setter and getter methods public void setFirst (String First) { this.first = first; } public String getFirst() { return this.first; } // Last setter and getter methods public void setLast (String Last) { this.last = last; } public String getLast() { return this.last; } // Age of setter and getter methods public void setAge ( int Age) { this.age = age; } public int getAge() { return this.age; } // addresses的setter和getter方法 public void setAddresses(Set<Address> addresses) { this.addresses = addresses; } public Set<Address> getAddresses() { return this.addresses; } // override equals () method, according to the judgment First, Last public Boolean the equals (Object obj) { if (this == obj) { return true; } if (obj != null && obj.getClass() == Person.class) { Person target = (Person)obj; return target.getFirst().equals(this.first) && target.getLast().equals(this.last); } return false; } // override hashCode () method, the value calculated according hashCode First, Last public int hashCode () { return getFirst().hashCode() * 31 + getLast().hashCode(); } }