2015年4月26日 星期日

String之HibernateTemplate经典查询

http://zhaoshijie.iteye.com/blog/836757

 一、find(String queryString);  
 
     示例:this.getHibernateTemplate().find("from bean.User");  
 
     返回所有User对象  
 
 
 
二、find(String queryString , Object value);  
 
     示例:this.getHibernateTemplate().find("from bean.User u where u.name=?", "test");  
 
     或模糊查询:this.getHibernateTemplate().find("from bean.User u where u.name like ?", "%test%");  
 
     返回name属性值为test的对象(模糊查询,返回name属性值包含test的对象)  
 
 
 
三、find(String queryString, Object[] values);  
 
     示例:String hql= "from bean.User u where u.name=? and u.password=?" 
 
               this.getHibernateTemplate().find(hql, new String[]{"test", "123"});  
 
     返回用户名为test并且密码为123的所有User对象  
 
 
 
---------------------------------  
 
四、findByExample(Object exampleEntity)  
 
     示例:  
 
            User u=new User();      
 
            u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)      
 
            u.setName("bb");      
 
            list=this.getHibernateTemplate().findByExample(u,start,max);    
 
     返回:用户名为bb密码为123的对象  
 
 
 
五、findByExample(Object exampleEntity, int firstResult, int maxResults)  
 
     示例:  
 
           User u=new User();      
 
           u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)      
 
           u.setName("bb");      
 
           list=this.getHibernateTemplate().findByExample(u,start,max);      
 
     返回:满足用户名为bb密码为123,自start起共max个User对象。(对象从0开始计数)  
 
 
 
---------------------------------------------------  
 
六、findByNamedParam(String queryString , String paramName , Object value)  
 
 
 
   使用以下语句查询:   
 
        String queryString = "select count(*) from bean.User u where u.name=:myName";   
 
        String paramName= "myName";  
 
        String value= "xiyue";  
 
        this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);   
 
        System.out.println(list.get(0));   
 
    返回name为xiyue的User对象的条数  
 
 
 
七、findByNamedParam(String queryString , String[] paramName , Object[] value)  
 
     示例:  
 
        String queryString = "select count(*) from bean.User u where u.name=:myName and u.password=:myPassword";   
 
        String[] paramName= new String[]{"myName", "myPassword"};  
 
        String[] value= new String[]{"xiyue", "123"};  
 
        this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);  
 
        返回用户名为xiyue密码为123的User对象  
 
 
 
八、findByNamedQuery(String queryName)  
 
     示例:  
 
       1、首先需要在User.hbm.xml中定义命名查询  
 
            <hibernate-mapping>  
 
                 <class>......</class>  
 
                 <query name="queryAllUser"><!--此查询被调用的名字-->  
 
                      <!--[CDATA[  
 
                           from bean.User  
 
                       ]]>  
 
                 </query>  
 
            </hibernate-mapping>  
 
        2、如下使用查询:  
 
            this.getHibernateTemplate().findByNamedQuery("queryAllUser");  
 
 
 
九、findByNamedQuery(String queryName, Object value)  
 
     示例:  
 
       1、首先需要在User.hbm.xml中定义命名查询  
 
            <hibernate-mapping>  
 
                 <class>......</class>  
 
                 <query name="queryByName"><!--此查询被调用的名字-->  
 
                      <![CDATA[  
 
                           from bean.User u where u.name = ?  
 
                       ]]>  
 
                 </query>  
 
            </hibernate-mapping>  
 
        2、如下使用查询:  
 
            this.getHibernateTemplate().findByNamedQuery("queryByName", "test");  
 
 
 
十、findByNamedQuery(String queryName, Object[] value)  
 
     示例:  
 
       1、首先需要在User.hbm.xml中定义命名查询  
 
            <hibernate-mapping>  
 
                 <class>......</class>  
 
                 <query name="queryByNameAndPassword"><!--此查询被调用的名字-->  
 
                      <![CDATA[  
 
                           from bean.User u where u.name =? and u.password =?  
 
                       ]]>  
 
                 </query>  
 
            </hibernate-mapping>  
 
        2、如下使用查询:  
 
            String[] values= new String[]{"test", "123"};  
 
            this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , values);  
 
 
 
十一、findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)   
 
示例:  
 
       1、首先需要在User.hbm.xml中定义命名查询  
 
            <hibernate-mapping>  
 
                 <class>......</class>  
 
                 <query name="queryByName"><!--此查询被调用的名字-->  
 
                      <![CDATA[  
 
                           from bean.User u where u.name =:myName  
 
                       ]]>  
 
                 </query>  
 
            </hibernate-mapping>  
 
        2、如下使用查询:  
 
            this.getHibernateTemplate().findByNamedQuery("queryByName" , "myName", "test");  
 
 
 
十二、findByNamedQueryAndNamedParam(String queryName, String[] paramName, Object[] value)   
 
示例:  
 
       1、首先需要在User.hbm.xml中定义命名查询  
 
            <hibernate-mapping>  
 
                 <class>......</class>  
 
                 <query name="queryByNameAndPassword"><!--此查询被调用的名字-->  
 
                      <![CDATA[  
 
                           from bean.User u where u.name =:myName and u.password=:myPassword  
 
                       ]]>  
 
                 </query>  
 
            </hibernate-mapping>  
 
        2、如下使用查询:  
 
            String[] names= new String[]{"myName", "myPassword"};  
 
            String[] values= new String[]{"test", "123"};  
 
 
 
            this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , names, values);  
 
 
 
十三、findByValueBean(String queryString , Object value);  
 
示例:  
 
     1、定义一个ValueBean,属性名必须和HSQL语句中的:后面的变量名同名,此处必须至少有两个属性,分别为myName和

myPassword,使用setter方法设置属性值后  
 
         ValueBean valueBean= new ValueBean();  
 
         valueBean.setMyName("test");  
 
         valueBean.setMyPasswrod("123");  
 
     2、  
 
         String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";  
 
         this.getHibernateTemplate().findByValueBean(queryString , valueBean);  
 
         
 
十四、findByNamedQueryAndValueBean(String queryName , Object value);  
 
示例:  
 
      1、首先需要在User.hbm.xml中定义命名查询  
 
            <hibernate-mapping>  
 
                 <class>......</class>  
 
                 <query name="queryByNameAndPassword"><!--此查询被调用的名字-->  
 
                      <![CDATA[  
 
                           from bean.User u where u.name =:myName and u.password=:myPassword  
 
                       ]]-->  
 
                 </query>  
 
            </hibernate-mapping>  
 
     2、定义一个ValueBean,属性名必须和User.hbm.xml命名查询语句中的:后面的变量名同名,此处必须至少有两个属性,分别

为myName和myPassword,使用setter方法设置属性值后  
 
         ValueBean valueBean= new ValueBean();  
 
         valueBean.setMyName("test");  
 
         valueBean.setMyPasswrod("123");  
 
     3、  
 
         String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";  
 
         this.getHibernateTemplate().findByNamedQueryAndValueBean("queryByNameAndPassword", valueBean);  


HibernateTemplate 需搭配SpringOpenSessionInViewFilter來關閉session
<filter>
    <filter-name>SpringOpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SpringOpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

ERROR 2017 (HY000): Can't open named pipe to host: . pipe: MySQL (2)

I had the same problem with MySQL 5.0. I tried the other items suggested by other users (which didn't work).

To successfully install:
1) Go to control panel->add/remove programs and remove MySql
2) Go to c:\program files\ and delete the MySql directory
3) Reinstall and select "Standard Configuration" from the Server Instance Configuration Wizard. Do NOT choose "Detailed Configuration"
4) After the installation is complete (successfully this time) you can go to Start->Programs->MySql->MySql Server 5.0->MySQL Server Instance Configuration Wizard. Now you can configure the server as you wish...

WebMvcConfigurerAdapter

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-customize

OpenSessionInViewFilter 的配置及替代方案

http://justsee.iteye.com/blog/1174999
Spring 为我们提供了一个叫做 OpenSessionInViewFilter 的过滤器,他是标准的 Servlet Filter 所以我们把它按照规范配置到 web.xml 中方可使用。使用中我们必须配合使用 Spring 的 HibernateDaoSupport 来进行开发,也就是说,我们的dao层的类都要继承于 HibernateDaoSupport,从中由 Spring 来控制 Hibernate 的 Session 在请求来的时候开启,走的时候关闭,保证了我们访问数据对象时的稳定性。

2015年4月18日 星期六

mysql Access denied for user

 http://stackoverflow.com/questions/22508922/java-sql-sqlexception-access-denied-for-user-rootlocalhost-using-password

Access denied for user 'suntone'@'localhost' (using password: YES

sol:

GRANT ALL PRIVILEGES ON *.* TO 'suntone'@'localhost' IDENTIFIED BY 'suntone' WITH GRANT OPTION;

create table from pojo

http://openhome.cc/Gossip/HibernateGossip/HbmToTable.html
http://stackoverflow.com/questions/12054422/unsuccessful-alter-table-xxx-drop-constraint-yyy-in-hibernate-jpa-hsqldb-standa

package com.lfo.suntone.test;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HbmToTable {

    public static void main(String[] args) {
        Configuration config = new Configuration().configure();
        System.out.println("Creating tables...");
        SchemaExport schemaExport = new SchemaExport(config);
        schemaExport.create(true, true);

    }

}



package com.lfo.suntone.test;

import org.hibernate.dialect.MySQL5InnoDBDialect;

public class ImprovedMySQLDialect extends MySQL5InnoDBDialect {
    @Override
    public String getDropSequenceString(String sequenceName) {
        // Adding the "if exists" clause to avoid warnings
        return "drop sequence if exists " + sequenceName;
    }

    @Override
    public boolean dropConstraints() {
        // We don't need to drop constraints before dropping tables, that just leads to error
        // messages about missing tables when we don't have a schema in the database
        return false;
    }
}


DOWNLOAD
http://1drv.ms/1DRR8Bw

2015年4月11日 星期六

NotificationCompat

http://segmentfault.com/a/1190000000402154
 private void sendNotification(String yourAwesomeUnicodeString) {
        Stock stock= Utils.instance.readValueAsObject(yourAwesomeUnicodeString,new Stock());
         // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, MainActivity.class);

        resultIntent.putExtra(Config.gcmDateField,yourAwesomeUnicodeString);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );


        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)

                        .setContentTitle(stock.getStocktype().getName() + "缺貨通知").setSmallIcon(R.drawable.ic_launcher)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText("剩餘" + stock.getAmount())).setVibrate(new long[] { 1000, 1000 })
        .setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true);


        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

AToATool


               /*
before
               editholder.getName().setText(positionobject.getName());
                editholder.getAddress().setText(positionobject.getAddress());
                editholder.getFixLineTel().setText(positionobject.getFixLineTel());
                editholder.getMobile().setText(positionobject.getMobile());
                */

after
      AToATool.instance.setAllTextViewByGetter(positionobject, context, editholder.getConvertView());


----------------------package suntone.lfo.com.suntonehelper.tool;

import android.content.Context;
import android.view.View;
import android.widget.TextView;

import com.googlecode.openbeans.IntrospectionException;
import com.googlecode.openbeans.Introspector;
import com.googlecode.openbeans.PropertyDescriptor;
import com.lfo.suntone.db.Supplier;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by user on 2015/4/11.
 */
public enum AToATool {
    instance;
    public List<Method> getGetters(Class claz){
        List<Method> getter=new ArrayList<Method>();
        try {
            for(PropertyDescriptor propertyDescriptor :
                    Introspector.getBeanInfo(claz).getPropertyDescriptors()){

                // propertyEditor.getReadMethod() exposes the getter
                // btw, this may be null if you have a write-only property
                Method m =propertyDescriptor.getReadMethod();
                if(m!=null){
                    getter.add(m) ;
                }

            }
            return getter;
        } catch (IntrospectionException e) {
            e.printStackTrace();
            return getter;
        }
    }
    public List<Method> getSetters(Class claz){
        List<Method> setters=new ArrayList<Method>();
        try {
            for(PropertyDescriptor propertyDescriptor :
                    Introspector.getBeanInfo(claz).getPropertyDescriptors()){

                // propertyEditor.getReadMethod() exposes the getter
                // btw, this may be null if you have a write-only property
                Method m =propertyDescriptor.getWriteMethod();
                if(m!=null){
                    setters.add(m) ;
                }

            }
            return setters;
        } catch (IntrospectionException e) {
            e.printStackTrace();
            return setters;
        }
    }
    public Method findMethod(String str,List<Method> list){
        if(str==null){
            Utils.instance.log("findMethod str==null");
            return null;
        }
        if(str.isEmpty()){
            Utils.instance.log("findMethod strisEmpty");
            return null;
        }
        for(Method m:list){
            if(m!=null){
                String mname=m.getName();
                mname=mname.substring(3);//去掉GET
                if(mname.toLowerCase().equals(str.toLowerCase())){
                    return m;
                }

            }

        }

        return null;

    }
    public <T> void setAllTextViewByGetter(T t, Context context, View layoutView) {

        Class claz = t.getClass();
        Field[] field = claz.getDeclaredFields();
        List<Method> getters =getGetters(claz);
//1.no getter method continue;
//2.no equals  name TextView continue;


        for (Field f : field) {
            String name = f.getName();
            Method m = findMethod(name, getters);
            if (m == null) {
                Utils.instance.log("setAllTextViewByGetter not find methhod  in getters of name : " + name);
                continue;
            }
            int resID = context.getResources().getIdentifier(name, "id", context.getPackageName());
            TextView textview = (TextView) layoutView.findViewById(resID);
            try {
                if (textview == null) {
                    Utils.instance.log("setAllTextViewByGetter not find TextView of " + name);
                    continue;
                }
                String str = "";
                str = String.valueOf(m.invoke(t));
                if(str.toLowerCase().equals("null")){
                    continue;
                }
                if (str != null) {
                    textview.setText(str);

                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return;
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                return;
            }
        }
    }


    public <T> void settingByAllTextView(T t, Context context, View layoutView) {

        //1.if setter param type is not string or integer then skip
        //2.setter only have one parameter
        Class claz=t.getClass();
        Field[] field = claz.getDeclaredFields();
        List<Method> setters =getSetters(claz);
        for (Field f : field) {
            String name = f.getName();
            Method m = findMethod(name, setters);
            if (m == null) {
                Utils.instance.log("settingByAllTextView not find methhod  in setters of name : " + name);
                continue;
            }
            int resID = context.getResources().getIdentifier(name, "id", context.getPackageName());
            TextView textview = (TextView) layoutView.findViewById(resID);
            try {
                if (textview == null) {
                    Utils.instance.log("settingByAllTextView not find TextView of " + name);
                    continue;
                }
                Class[] parameterTypes = m.getParameterTypes();
                if(parameterTypes.length>1){
                    Utils.instance.log("settingByAllTextView parameterTypes.length>1");
                    continue;
                }
                Class firstparamclass=parameterTypes[0];
                String str = textview.getText().toString();
                if(str.isEmpty()){
                    continue;
                }
                if(firstparamclass.getSimpleName().equals("String")){
                    m.invoke(t,str);
                    continue;
                }
                if(firstparamclass.getSimpleName().equals("Integer")){
                    m.invoke(t,Integer.valueOf(str));
                    continue;
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return;
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                return;
            }
        }

    }
}

custom dialog

    public void destory(){
        ViewGroup g= (ViewGroup) convertView.getParent();
        if(convertView!=null){
            try{
                g.removeView(convertView);
            }catch(Exception e){
                e.printStackTrace();
            }

        }

    }

when you are custom dialog view   remind holder must remove childview

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

2015年4月9日 星期四

getDeclaredFields()

https://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html

2015年4月4日 星期六

jackson readValueAsObjectList


    public <T> List<T> readValueAsObjectList(String h,Class clazz){
        List<T> list = null;
        try {
            TypeFactory t = TypeFactory.defaultInstance();
             list = Utils.instance.getObjectMapper().readValue(h, t.constructCollectionType(ArrayList.class,clazz));
            return list;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            return list;
        }
    }



如果用
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
 會變成linkedmap

aspect @annotation @around

 package com.lfo.suntone;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.stereotype.Component;

@Component("recordStockHistory")
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public  @interface RecordStockHistory {

}





package com.lfo.suntone.aspect;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lfo.suntone.NotValidException;
import com.lfo.suntone.RecordStockHistory;
import com.lfo.suntone.controller.StockController;
import com.lfo.suntone.dao.DaoUtils;
import com.lfo.suntone.db.Stockhistory;
import com.lfo.suntone.tool.AspectTool;
import com.lfo.vo.MoveRequest;
import com.lfo.vo.Status;
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Aspect
@Component
public class ControllerAspect {

   
    @Autowired
    private  AspectTool aspectTool;
    @Pointcut("@annotation(com.lfo.suntone.RecordStockHistory)")
    public void movePointcut() {
       
    }
   
    @Around("movePointcut()")
    public Object move(ProceedingJoinPoint  j) throws Throwable{
        System.out.println("movePointcut");
        Object[] args = j.getArgs();
         System.out.println("argslen"+args.length);
         MoveRequest m=(MoveRequest)args[0];
         System.out.println("move() m:"+m.getAmount());
        return j.proceed();
       
    }
    /*
    @Pointcut("execution(* com.lfo.suntone.controller.StockController.*(..))")
    public void header() {
       
    }
    @Around("header()")
    public Object   header(ProceedingJoinPoint  j) throws NotValidException {
       
       
        String userid=aspectTool.getHeaderInStockController(j);
        Boolean isvalidid=aspectTool.isValidUserid(userid);
         if(isvalidid){
             try {
               
                 System.out.println("header isValidUserid:");
               
                Object ss = j.proceed();//不但攔截並且取回結果
                 aspectTool.saveStockhistory(j, userid);
               
                return ss  ;//必須回傳否則無法原方法return 為null
            } catch (Throwable e) {
                e.printStackTrace();
            }
         }else{
             System.out.println("header isnot  ValidUserid");
           
             StockController s=(StockController) j.getTarget();
             try {
                s.getResponse().getOutputStream().print("error userid");
            } catch (IOException e) {
               
                e.printStackTrace();
            }
             return null;
           
           
           
         }
        return null;
    }
    */
   
}

2015年4月3日 星期五

windows terminate port8080

netstat -a -n -o | findstr :8080
 taskkill -pid XXXX -f

AspectJ Pointcut to exclude annotation

http://stackoverflow.com/questions/24447383/aspectj-pointcut-to-exclude-annotation