Wu Yuxiong - natural born flyweight JAVA EE enterprise application development Struts2Sping4Hibernate Integrated Development Study Notes: Hibernate_Interceptor

<?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.UserManager" fork="yes" failonerror="true">
            <classpath refid="classpath"/>
        </java>
    </target>

</project>
<? xml Version = "1.0" encoding = "GBK"?> 
<-! DTD specifies the information Hibernate configuration file -> 
! <DOCTYPE hibernate- the Configuration the PUBLIC
     "- // Hibernate / Hibernate the Configuration DTD 3.0 // EN" 
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<-! is the root element of the configuration Hibernate-configuration file -> 
<Hibernate-the configuration> 
    <the session-Factory's> 
        <! - Specifies the database connection for driving -> 
        <Property name = "connection.driver_class"> com.mysql.jdbc.Driver </ Property> 
        <-! URL specified database connection, wherein hibernate is connected to the application database name -> 
        <Property name = "connection.url"> jdbc: MySQL: // localhost / Hibernate </ Property> 
        <-! Specifies the user name connecting to the database ->
        <Property name = "connection.username"> the root </ Property>property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</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 "> 200 is </ Property> 
        <-! connection pool specified minimum number of connections -> 
        <Property name =" hibernate.c3p0.min_size "> 2 </ Property> 
        <-! connection timeout specified connection pool duration -> 
        <Property name = "hibernate.c3p0.timeout"> 5000 </ Property> 
        <-! specify the connection pool maximum number of cache Statement object -> 
        <Property name = "hibernate.c3p0.max_statements"> 100 </ Property> 
        <Property name = "hibernate.c3p0.idle_test_period"> 3000 </ Property> 
        <name = Property "hibernate.c3p0.validate"> to true </ Property> 
        <-! dialect specified database -> 
        <Property name = "dialect"> org.hibernate.dialect.MySQL5InnoDBDialect </ Property> 
        <-! automatically create the database as needed -> 
        <Property name = "hbm2ddl .auto "> Update </ Property> 
        <-! display Hibernate persistence operations generated SQL -> 
        <Property name =" show_sql "> to true </ Property> 
        <-! SQL script will then be formatted output -> 
        <Property name = "hibernate.format_sql"> to true </ Property> 
        <-! defined context-Session specified in accordance with the current thread -> 
        <Property name = "hibernate.current_session_context_class is"> thread </ Property>
        <! - lists all persistent classes class name -> 
        <Mapping class="org.crazyit.app.domain.User"/>
    </session-factory>
</hibernate-configuration>
package lee;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;

import java.util.*;

import org.crazyit.app.domain.*;
import org.crazyit.common.hibernate.interceptor.MyInterceptor;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 A a Date *: 
 * @author   Yeeku.H.Lee [email protected] 
 * @version   1.0
  * / 
public  class the UserManager 
{ 
    static the Configuration CFG = new new the Configuration ()
         // load the configuration file hibernate.cfg.xml 
        .configure ()
         // set enable global interceptor 
        .setInterceptor ( new new myInterceptor ());
     // to create an instance of SessionFactory Configuration instance 
    static ServiceRegistry ServiceRegistry = new new StandardServiceRegistryBuilder () 
        .applySettings (cfg.getProperties ()) Build ().;
     static SessionFactory SF = cfg.buildSessionFactory(serviceRegistry);
    public static void main(String[] args)
    {
        UserManager mgr = new UserManager();
        mgr.testUser();
        sf.close();
    }
    private void testUser()
    {
        Session session = sf.getCurrentSession();
        Transaction tx = session.beginTransaction();
        // 创建一个User对象
        User u1 = new User();
        u1.setName("crazyit.org");
        u1.setAge(30);
        u1.setNationality("china");
        session.save(u1);
        User u = (User)session.load(User.class , 1);
        u.setName("疯狂Java联盟");
        tx.commit();
    }
}
package org.crazyit.app.domain;

import java.util.*;

import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Entity
@Table(name="user_inf")

public class User
{
    @Id @Column(name= "user_id" ) 
    @GeneratedValue (Strategy = GenerationType.IDENTITY)
     Private Integer ID;
     Private String name;
     Private  int Age;
     Private String nationality; 

    // no argument constructor 
    public the User () 
    { 
    } 
    // initialize all member variables constructors 
    public the User (ID Integer, String name, int Age, nationality String) 
    { 
        the this .id = ID;
         the this .name = name;
         the this .age = Age;
         the this= .nationality nationality; 
    } 

    // ID of the setter and getter methods 
    public  void the setId (Integer ID) 
    { 
        the this .id = ID; 
    } 
    public Integer getId () 
    { 
        return  the this .id; 
    } 

    // name setter and getter methods 
    public  void the setName (String name) 
    { 
        the this .name = name; 
    } 
    public String getName () 
    { 
        return  the this .name; 
    } 

    // Age setter and getter methods 
    public  void setAge(int age)
    {
        this.age = age;
    }
    public int getAge()
    {
        return this.age;
    }

    // nationality的setter和getter方法
    public void setNationality(String nationality)
    {
        this.nationality = nationality;
    }
    public String getNationality()
    {
        return this.nationality;
    }

}
package org.crazyit.common.hibernate.interceptor;

import java.util.*;
import java.io.*;

import org.hibernate.*;
import org.hibernate.type.Type;

/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 usually employ to achieve interceptors inherit EmptyInterceptor//* /

public  class myInterceptor the extends EmptyInterceptor 
{ 
    // record the number of modifying 
    Private  int Updates;
     // record the number of times to create 
    Private  int Creates; 

    // when deleting the entity, onDelete () method is called 
    public  void The onDelete (Entity Object, the Serializable ID, 
        Object [ ] state, String [] the propertyNames, the Type [] types) 
    { 
        // do Nothing 
    } 

    // when the persistent state synchronization entity to the database, onFlushDirty () method is called 
    public  Boolean onFlushDirty (entity Object, the Serializable ID, 
        Object [] currentState, Object [] previousState ,
        String [] the propertyNames, the Type [] types)
    { 
        // each synchronization time, plus a modified accumulator. 1 
        Updates ++ ;
         for ( int I = 0; I <propertyNames.length; I ++ ) 
        { 
            IF ( "the lastUpdateTimestamp" .equals (the propertyNames [I])) 
            { 
                the currentState [I] = new new a Date ();
                 return  to true ; 
            } 
        } 
        return  to false ; 
    } 

    // when loaded persistent entity, onLoad () method is called 
    public  Boolean the onLoad (entity Object, the Serializable ID, 
        Object [] State, String [] the propertyNames, the Type [] types) 
    { 
        for ( int I = 0; I <propertyNames.length; I ++ ) 
        { 
            IF ( "name" .equals (the propertyNames [ I])) 
            { 
                // output value is loaded entity name attribute 
                System.out.println (State [I]);
                 return  to true ; 
            } 
        } 
        return  to false ; 
    } 

    // save persistent instance when the method is called 
    public  Boolean the onSave (Object entity, Serializable id,
        Object [] State, String [] the propertyNames, the Type [] types) 
    { 
        Creates  ++;
         for ( int I = 0; I <propertyNames.length; I ++ ) 
        { 
            IF ( "the createTimestamp" .equals (the propertyNames [I])) 
            { 
                State [I] = new new a Date ();
                 return  to true ; 
            } 
        } 
        return  to false ; 
    } 

    // after the changes made persistent synchronization is complete, call postFlush () method 
    public  void postFlush (the Iterator Entities) 
    {
        System.out.println ( "number of times to create:" 
            + Creates + ", the number of updates:" + Updates); 
    } 

    // before the synchronization of the changes made persistent, method call preFlush 
    public  void preFlush (the Iterator Entities) 
    { 
        / / do Nothing 
    } 

    // trigger before the transaction commits the method 
    public  void beforeTransactionCompletion (transaction tx) 
    { 
        System.out.println ( "transaction coming to an end" ); 
    } 

    // trigger the method after the transaction commits 
    public  void afterTransactionCompletion (transaction tx) 
    { 
        System.out.println ( "transaction is completed" ); 
    } 
}

 

Guess you like

Origin www.cnblogs.com/tszr/p/12370090.html