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

<?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> 
        <-! password for connecting to the database specified -> 
        <Property name = "connection.password"> 32147 </ Property> 
        <-! specify connection pool The maximum number of connections -> 
        <Property name = "hibernate.c3p0.max_size"> 20 is </ Property> 
        <-! connection pool specified minimum number of connections -> 
        <Property name = "hibernate.c3p0.min_size">. 1 </ Property> 
        <-! long timeout specified connection pool connection -> 
        <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>
        <property name="hibernate.c3p0.acquire_increment">2</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> 
        <-! list all persistent class class name -> 
        <Mapping class = "org.crazyit.app.domain.User" / > 
    </session-factory>
</hibernate-configuration>
package org.crazyit.app.domain;

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 () 
    { 
    } 
    // constructor initializes all member variables 
    public the User ( name String, int Age, nationality String) 
    { 
        the this .name = name;
         the this .age = Age;
         the this .nationality = nationality; 
    } 

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

    // name的setter和getter方法
    public void setName(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }

    // age的setter和getter方法
    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 lee;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;
/**
 * 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
 */
public classThe HibernateUtil 
{ 
    public  static  Final SessionFactory the sessionFactory; 

    static 
    { 
        the try 
        { 
            // the default configuration file created hibernate.cfg.xml Configuration Example 
            Configuration CFG = new new Configuration () 
                .configure (); 
            // to Configuration instance to create SessionFactory instances 
            ServiceRegistry serviceRegistry = new new StandardServiceRegistryBuilder () 
                . .applySettings (cfg.getProperties ()) Build (); 
            the sessionFactory = cfg.buildSessionFactory (ServiceRegistry); 
        } 
        the catch(The Throwable EX) 
        { 
            System.err.println ( + "the SessionFactory the Initial Creation failed." EX);
             the throw  new 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 the Session currentSession ()
         throws plain HibernateException 
    { 
        the Session S = Session.get ();
         //If the thread has not Session, a new one is created the Session 
        IF (S == null ) 
        { 
            S = sessionFactory.openSession ();
             // the Session variable storage ThreadLocal variable obtained in the session in 
            session.set (S); 
        } 
        return S; 
    } 

    public  static  void closeSession ()
         throws plain HibernateException 
    { 
        the Session S = Session.get ();
         IF (S =! null ) 
            S.CLOSE (); 
        session.set ( null );  
    }
}
package lee;

import org.hibernate.*;

import org.crazyit.app.domain.*;
/**
 * 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
 */
public class UserManager
{
    public static void main(String[] args)throws Exception
    {
        UserManager mgr = new UserManager();
        mgr.updateUsers();
        HibernateUtil.sessionFactory.close();
    }
    private void updateUsers()throws Exception
    {
        // 打开Session
        Session session = HibernateUtil.currentSession();
        // 开始事务
        Transaction tx = session.beginTransaction();
        // 查询出User表中的所有记录
        ScrollableResults users = session.createQuery("from User")
            .setCacheMode(CacheMode.IGNORE)
            .scroll (ScrollMode.FORWARD_ONLY); 
        int COUNT = 0 ;
         // traverse all records in the User table 
        the while (users.next ()) 
        { 
            User U = (User) users.get (0 ); 
            u.setName ( "New username "+ count);
             // when the count is a multiple of 20, the
             // results from the Session flush updated to the database. 
            IF (COUNT% ++ 20 is == 0 ) 
            { 
                Session.flush (); 
                Session.clear (); 
            } 
        } 
        tx.commit (); 
        HibernateUtil.closeSession (); 
    }
}

 

Guess you like

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