posts - 118, comments - 131, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

2008年5月9日

参考:第 9 章 事务管理 - Spring Framework reference 2.0.5 参考手册中文版
http://doc.javanb.com/spring-framework-reference-zh-2-0-5/ch09.html

先从配置文件开始:
源码:springAop.rar

需要jar
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    
<classpathentry kind="src" path="java"/>
    
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    
<classpathentry kind="lib" path="lib/aspectjrt.jar"/>
    
<classpathentry kind="lib" path="lib/aspectjweaver.jar"/>
    
<classpathentry kind="lib" path="lib/spring.jar"/>
    
<classpathentry kind="lib" path="lib/spring-sources.jar"/>
    
<classpathentry kind="lib" path="lib/commons-logging-1.0.4.jar"/>
    
<classpathentry kind="lib" path="lib/cglib-nodep-2.1_3.jar"/>
    
<classpathentry kind="lib" path="lib/hibernate3.jar"/>
    
<classpathentry kind="lib" path="lib/log4j-1.2.11.jar"/>
    
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
    
<classpathentry kind="lib" path="lib/dom4j-1.6.1.jar"/>
    
<classpathentry kind="lib" path="lib/commons-collections-2.1.1.jar"/>
    
<classpathentry kind="lib" path="lib/mysql.jar"/>
    
<classpathentry kind="lib" path="lib/jta.jar"/>
    
<classpathentry kind="lib" path="lib/antlr-2.7.6.jar"/>
    
<classpathentry kind="output" path="bin"/>
</classpath>


spring 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop
="http://www.springframework.org/schema/aop"
       xmlns:tx
="http://www.springframework.org/schema/tx"
       xsi:schemaLocation
="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
>
       
  
  
<!-- daoCalss : extends HibernateDaoSupport implements BeanDao -->
  
<bean id="beanDao" class="dao.imp.BeanDaoImp">
      
<property name="sessionFactory">
          
<ref bean="sessionFactory"></ref>
      
</property>
  
</bean>
  
   
   
<!-- hibernate3 sessionFactory -->
   
<bean id="sessionFactory"     
        class
="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
       
<!-- spring 与 hibernate 联系 -->  
       
<property name="configLocation" value="classpath:hibernate.cfg.xml" />  
   
</bean>  
   
   
<!-- aop 与事务联系 aopBean<->txAdvice  -->
   
<aop:config>
           
<!-- 逻辑拦截 -->
         
<aop:pointcut id="aopBean" expression="execution(* *.*.*(..))"/>
           
<aop:advisor advice-ref="txAdvice" pointcut-ref="aopBean" />
      
</aop:config>

    
<!-- 事务适配器 -->
       
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
      
<property name="sessionFactory" ref="sessionFactory" />
    
</bean>

    
<!-- 事务原子 具体方法进行什么事务 -->
      
<tx:advice id="txAdvice" transaction-manager="txManager">
           
<tx:attributes>
             
<tx:method name="get*" read-only="true"/>
          
<tx:method name="*" />
        
</tx:attributes>
      
</tx:advice>

</beans>


hibernate 配置
<?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 name="asdf">
    
<property name="hibernate.dialect">mysql</property>
    
<property name="myeclipse.connection.profile">
        com.mysql.jdbc.Driver
    
</property>
    
<property name="connection.url">
        jdbc:mysql://localhost/aop
    
</property>
    
<property name="show_sql">true</property>
    
    
<property name="connection.username">root</property>
    
<property name="connection.password"></property>
    
<property name="connection.driver_class">
        com.mysql.jdbc.Driver
    
</property>
    
<property name="dialect">
        org.hibernate.dialect.MySQLDialect
    
</property>
    
    
<mapping resource="bean/UnitBean.hbm.xml" />
    
</session-factory>
</hibernate-configuration>


dao 类(接口)
package dao.imp;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bean.UnitBean;

import dao.BeanDao;

public class BeanDaoImp extends HibernateDaoSupport implements BeanDao{
    
public void addBean(UnitBean unitBean) {
        
this.getHibernateTemplate().save(unitBean);
    }

    
public List<UnitBean> getBeanByAll() {
        
return this.getHibernateTemplate().find(" from "+UnitBean.class.getName());
    }

    
public void removeBean(long beanId) {
        
this.getHibernateTemplate().delete(
                getHibernateTemplate().get(UnitBean.
class, beanId)
            );
    }
    
}

Main 类
package unit;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dao.BeanDao;
import bean.UnitBean;

public class Main {
    
public static void main(String[] args) {
           ApplicationContext ctx 
= new ClassPathXmlApplicationContext("beans.xml");
           BeanDao dao 
= (BeanDao) ctx.getBean("beanDao");
           UnitBean bean 
= new UnitBean();
           bean.setName(
"xx");
           bean.setPass(
"11");
           dao.addBean(bean);
           
           
for(UnitBean unitBean : dao.getBeanByAll() ){
               System.out.println( unitBean.getId() );
           }
           
           dao.removeBean(bean.getId());
           
    }
}
结果:
Hibernate: insert into bean (name, pass) values (?, ?)
Hibernate: select unitbean0_.id as id0_, unitbean0_.name as name0_, unitbean0_.pass as pass0_ from bean unitbean0_
1
Hibernate: select unitbean0_.id as id0_0_, unitbean0_.name as name0_0_, unitbean0_.pass as pass0_0_ from bean unitbean0_ where unitbean0_.id=?
Hibernate: delete from bean where id=?






posted @ 2008-05-09 13:47 G_G 阅读(711) | 评论 (0)编辑 收藏

2008年5月8日

我的aop 基础
spring 实际使用 (这就使用一个例子说明)

测试类以及结果:
package unit;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import bean.HelloService;

public class Main {
    
public static void main(String[] args) {
           ApplicationContext context 
= new ClassPathXmlApplicationContext(      
                   
"beans.xml");    
           HelloService service 
= (HelloService) context.getBean("helloService");    
           service.annotationAop();
           
           System.out.println();
           
           service.xmlAop();
           
    }
}
结果:
 annotationAop//正常方法运行
aop--AspectJ! //
annotation拦截

 xmlAop 
//正常方法运行
 aop--XmlAop! //配置拦截



use jar
  • --aspectjrt.jar
  • --aspectjweaver.jar
  • --acglib-nodep-2.1_3.jar
  • --commons-logging.jar
  • --spring.jar
  • --spring-aspects.jar
XML配置
<beans xmlns="http://www.springframework.org/schema/beans"       
            xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:aop
="http://www.springframework.org/schema/aop"
               xsi:schemaLocation
=        
                   "http://www.springframework.org/schema/beans         
                   http://www.springframework.org/schema/beans/spring-beans.xsd         
                   http://www.springframework.org/schema/aop         
                   http://www.springframework.org/schema/aop/spring-aop.xsd"
>
        
        
<!-- 测试使用类 分别由 方法 annotationAop/xmlAop -->
        
<bean id="helloService"       
            class
="bean.HelloService"/>    
        
            
        
<!-- annotation aop 拦截 使用@Aspect 
            @Pointcut("execution(* annotationAop(..))")  
            @AfterReturning("mainMethod()")  
        
-->
        
<bean id="xmlAop" 
            class
="aop.AnnotationAspectJ"/>
        
<aop:aspectj-autoproxy/>    
        
        
        
<!-- xml aop  配置文件拦截 -->
        
<bean id="XmlAspectJ"       
            class
="aop.XmlAspectJ"/>
        
<aop:config>     
             
<aop:aspect ref="XmlAspectJ">
                 
<aop:pointcut id="mainMethod" expression="execution(* xmlAop(..))"/>    
                 
<aop:after-returning pointcut-ref="mainMethod" method="goXmlAop"/>     
             
</aop:aspect>   
         
</aop:config>    
            
</beans>

HelloService.java
package bean;

public class HelloService {  
    
public void annotationAop() {    
        System.out.println(
" annotationAop ");
    }
    
    
public void xmlAop(){
        System.out.println(
" xmlAop ");
    }
}

AnnotationAspectJ.java
package aop;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class AnnotationAspectJ {  
    @Pointcut(
"execution(* annotationAop(..))")  
    
public void mainMethod() {}  
    
    @AfterReturning(
"mainMethod()")  
    
public void sayHello() {    
        System.out.println(
"aop--AspectJ!");  
    }
}

XmlAspectJ.java
package aop;

public class XmlAspectJ {
    
public void goXmlAop(){
        System.out.println(
" aop--XmlAop! ");
    }
}













posted @ 2008-05-08 10:08 G_G 阅读(660) | 评论 (0)编辑 收藏

2008年5月4日

这就不介绍了 代码上:
package unit;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Assert;
import org.junit.Test;

public class RegexUnit {


    @Test
    
/**
     * <p>向前\向后查找</p>
     
*/
    
public void unit9()throws Exception{
        String testStr 
= "http://www.google.com";
        
        
/* 一般查找
         * .+(:) 查询出结果包含 :
         
*/
        Pattern pattern 
= Pattern.compile(".+(:)");        
        Matcher matcher 
=  pattern.matcher(testStr);
            Assert.assertTrue(
"错误: 查找出结果通过 .+(:) 此regex没有包含 : ",
                    matcher.find() 
&& matcher.group().equals("http:") );
        
        
/*  向前查找
         *  .+(?=:) 查询结果不包含 :
         
*/
        Pattern pattern2 
= Pattern.compile(".+(?=:)");
        Matcher matcher2 
= pattern2.matcher(testStr);
            Assert.assertTrue(
"错误: 查找出结果通过 .+(?=:) 此regex有包含 : ",
                    matcher2.find()
&& matcher2.group().equals("http"));
        
/* 向后查找
         * (?<=:).+
         
*/
        Pattern pattern3 
= Pattern.compile("(?<=://).+");
        Matcher matcher3 
= pattern3.matcher(testStr);
            Assert.assertTrue(
"错误:查找出结果包含 http:// 不向后查询",
                    matcher3.find()
&& matcher3.group().equals("www.google.com") );
    }


    @Test
    
/** 回朔应用 
     *  查询回朔、回朔替换、回朔大小写替换
     
*/
    
public void unit8()throws Exception{
        String testStr 
= "this is a block of of test,"+
                            
" several words here are are " +
                            
" repeated , and and they should not be. ";
        
        Pattern pattern 
= Pattern.compile("[ ]+(\\w+)[ ]+\\1");
        Matcher matcher 
= pattern.matcher(testStr);
        
//查询结果 are are 
        Assert.assertTrue("错误:regex 不匹配 "
                matcher.find()
&&matcher.group().split(" ").length>=2 );
        
        
while( matcher.find() ){
            Assert.assertTrue(
"错误:regex 不匹配 "
                    matcher.group().split(
" ").length>=2 );
        }
        
        
        
//替换
        String testStr2s = "313-555-1234";
        Pattern pattern2 
= Pattern.compile("(\\d{3})(-)(\\d{3})(-)(\\d{4})");
        Matcher mtmp 
=  pattern2.matcher(testStr2s);
        Assert.assertTrue(
"错误:没有查替换",
                mtmp.find() 
&& 
                    mtmp.replaceAll(
"($1) $3-$5").equals("(313) 555-1234") );
        
        
        
/*大小写替换(java 不能成功)
         *  \E 结束 \L 或 \U转换
         *  \l  \L 把下一个字符(串)换为小写
         *  \ u  \U 把下一个字符(串)转换为大写 
         
*/
        String testStr3 
= "tt:google:xx";
        Pattern pattern3 
= Pattern.compile("(?<=:)(.+)(?=:)");
        Matcher matcher2 
= pattern3.matcher(testStr3);
        
if( matcher2.find())
            System.out.println( matcher2.group() ) ;
    }
    
    
}



posted @ 2008-05-04 09:59 G_G 阅读(966) | 评论 (2)编辑 收藏

2008年4月29日

MySQL 存取控制包含2个阶段:

  • 阶段1:服务器检查是否允许你连接。
  • 阶段2:假定你能连接,服务器检查你发出的每个请求。看你是否有足够的权限实施它。例如,如果你从数据库表中选择(select)行或从数据库删除表,服务器确定你对表有SELECT权限或对数据库有DROP权限。
参考 : 5.8. MySQL用户账户管理

1.权限查看
mysql> show grants for 'root'@'localhost' ;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+
1 row in set (0.06 sec)

2.权限设置
5.8.2. 向MySQL增加新用户账户
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
    
->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION;

mysql
> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
    
->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
   其中两个账户有相同的用户名monty和密码some_pass。两个账户均为超级用户账户,具有完全的权限可以做任何事情。一个账户 ('monty'@'localhost')只用于从本机连接时。另一个账户('monty'@'%')可用于从其它主机连接。


mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
该账户只用于从本机连接。授予了RELOADPROCESS管理权限。这些权限允许admin用户执行mysqladmin reloadmysqladmin refreshmysqladmin flush-xxx命令,以及mysqladmin processlist。未授予访问数据库的权限。你可以通过GRANT语句添加此类权限。

mysql
> GRANT USAGE ON *.* TO 'dummy'@'localhost';
    一个账户有用户名dummy,没有密码。该账户只用于从本机连接。未授予权限。通过GRANT语句中的USAGE权限,你可以创建账户而不授予任何权限。它可以将所有全局权限设为'N'。假定你将在以后将具体权限授予该账户。

下面的例子创建3个账户,允许它们访问专用数据库。每个账户的用户名为custom,密码为obscure

mysql
> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    
->     ON bankaccount.*
    
->     TO 'custom'@'localhost'
    
->     IDENTIFIED BY 'obscure';

mysql
> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    
->     ON expenses.*
    
->     TO 'custom'@'whitehouse.gov'
    
->     IDENTIFIED BY 'obscure';

mysql
> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    
->     ON customer.*
    
->     TO 'custom'@'server.domain'
    
->     IDENTIFIED BY 'obscure';

这3个账户可以用于:

·         第1个账户可以访问bankaccount数据库,但只能从本机访问。

·         第2个账户可以访问expenses数据库,但只能从主机whitehouse.gov访问。

·         第3个账户可以访问customer数据库,但只能从主机server.domain访问。

要想不用GRANT设置custom账户,使用INSERT语句直接修改 授权表:

5.8.3. 从MySQL删除用户账户

DROP USER user;




posted @ 2008-04-29 13:52 G_G 阅读(911) | 评论 (0)编辑 收藏

2008年4月27日

请使用 mysql 1.5 或以上version;
测试表 level ;
create table test.level (name varchar(20));
再 insert 些数据 ;

 /*初始化*/ 
 
drop procedure if exists  useCursor //    
 
 
/*建立 存储过程 create */ 
 
CREATE PROCEDURE useCursor()
    
BEGIN
    
/*局部变量的定义 declare*/ 
         
declare tmpName varchar(20default '' ;
         
declare allName varchar(255default '' ;
         
         
declare cur1 CURSOR FOR SELECT name FROM test.level ;
         
         
/*    mysql 不知道为什么用异常加入判断 ?
          *    此请参考官方文档
20.2.11. 光标 光标 
          *        这把 游标 异常后 捕捉 
          *        并设置 循环使用 变量 tmpname 为 null 跳出循环。
          
*/
         
declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tmpname = null;
    
    
    
/*开游标*/ 
     
OPEN cur1;
         
/*游标向下走一步*/ 
         
FETCH cur1 INTO tmpName;
         
         
/* 循环体 这很明显 把游标查询出的 name 都加起并用 ; 号隔开 */
      
WHILE ( tmpname is not null) DO
          
set tmpName = CONCAT(tmpName ,";") ;
         
set allName = CONCAT(allName ,tmpName) ;
        
/*游标向下走一步*/ 
        
FETCH cur1 INTO tmpName;
      
END WHILE;
  
    
CLOSE cur1;
    
    
select allName ;
END;//
call useCursor()
//
 

运行结果:
mysql> call useCursor()//
+--------------------------------------+
| allName                              |
+--------------------------------------+
| f1;c3;c6;c5;c2;c4;c1;f1;f3;f4;f2;f5; |
+--------------------------------------+
1 row in set (0.00 sec)



posted @ 2008-04-27 17:05 G_G 阅读(49) | 评论 (0)编辑 收藏

2008年4月26日

     摘要: level 类:Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package hbm;import java.util.Set;/** * @hibernate.class table = "level" * where = " visible = ...  阅读全文

posted @ 2008-04-26 18:30 G_G 阅读(1109) | 评论 (0)编辑 收藏

2008年4月25日

你可以参考:快速修改 xdoclet samples ant -build.xml 适应实际开发
此文档为上面的改进版。

1.在 你电脑上建一个 ant第三方扩展文件夹,我这为:D:\ant\lib
2.当使用 eclipse->window->proferences..->ant->Runtime->Global Entries->Add External JARs->选择你建的 ant_lib 下的全部jar;
3.并在Global Entries下加入你的 classpath

使用现成的 xdoclet ant -> 加入自己的 ->
    <target name="hbm2ddl" depends="prepare">
          
<mkdir dir="${hbm2ddl.sql.dir}" />
          
<taskdef 
              
name="hbm2ddl"
             classname
="org.hibernate.tool.ant.HibernateToolTask" >
          
</taskdef>
          
<hbm2ddl destdir="${hbm2ddl.sql.dir}" >
                   
<configuration configurationfile="../src/hibernate.cfg.xml" />
                   
<hbm2ddl export="true" console="false" create="false" update="false" drop="false" outputfilename="bestunix.sql"/>
          
</hbm2ddl> 
           <!-- 支持 1.5 泛型请
搜索到xjavadoc最新1.5版本,下载,替换原来的xjavadoc-1.1.x,再次运行xdoclet任务,执行成功! -->
    
</target>

    
<target name="sql" depends="hbm2ddl">
        
         
<sql driver="org.gjt.mm.mysql.Driver" password=""  userid="root" autocommit="true"  
                       url
="jdbc:mysql://localhost:3306/zhongqi?characterEncoding=gbk" 
                        src
="../sql/data.sql" print="yes" output="sql_out.txt">  
              
</sql>  
    
</target>    

成功后就可以:
    使用 xdoclet 面向对象建表 ;
    通过 ant -> java2hbn, hbn2ddl,insertSql

在开发过程中当要加 jar 方法为:
    1.在 ant_lib 中加入 jar
    2.eclipse ->> Global Entries->Add External JARs->
工程转换修改 Global Entries中的classpath

例:
java
package hbm;

import java.util.Set;

/**
 * @hibernate.class table = "level"
 * where = " visible = 0  "
 * 
@author Administrator
 *
 
*/
public class Level {
    
private long id ;
    
private String name ;
    
private Level father ;
    
private Set<Level> childSet ;
    
private int visible  ;

    
public Level(){}
    
public Level(String name){  this.name = name ; }
    
    
public Level(String name,int visible){this.visible = visible;  this.name = name ; }
    
/**
     * @hibernate.id generator-class = "identity"
     * 
@return
     
*/
    
public long getId() {
        
return id;
    }
    
public void setId(long id) {
        
this.id = id;
    }
    
/**
     * @hibernate.property 
     * length = "20"
     * 
@return
     
*/
    
public String getName() {
        
return name;
    }
    
public void setName(String name) {
        
this.name = name;
    }
    
    
/**
     * @hibernate.many-to-one 
     * cascade = "save-update"
     * inverse = "false"
     * column = "fid"
     * 
@return
     
*/
    
public Level getFather() {
        
return father;
    }
    
public void setFather(Level father) {
        
this.father = father;
    }
    
    
/**
     * @hibernate.set 
     * lazy = "true"
     * table = "Level"
     * cascade = "save-update"
     * where = " visible = 0 "
     * @hibernate.collection-key column = "fid"
     * @hibernate.collection-one-to-many class = "hbm.Level"
     * 
@return
     
*/
    
public Set<Level> getChildSet() {
        
return childSet;
    }
    
public void setChildSet(Set<Level> childSet) {
        
this.childSet = childSet;
    }
    
    
/**
     * @hibernate.property 
     * 
@return
     
*/
    
public int getVisible() {
        
return visible;
    }
    
public void setVisible(int visible) {
        
this.visible = visible;
    }
}


unit
package test;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import hbm.Level;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import unit.HibernateUtil;

public class HbnUnit {
    @Test
    
public void level() throws Exception {
        Session session 
= HibernateUtil.currentSession();
        Transaction tr 
=  session.beginTransaction();
        
        Level level 
= new Level();
        level.setName(
"f1");
        
        Set
<Level> set = new HashSet<Level>();
            set.add(
new Level("c1"));
            set.add(
new Level("c2",1));
            set.add(
new Level("c3"));
            set.add(
new Level("c4",1 ));
            set.add(
new Level("c5" ));
            set.add(
new Level("c6",1 ));
        
        level.setChildSet(set);
        session.save(level);
        session.flush() ;
        session.clear();
        tr.commit();

        
    }
    
    @Test
    
public void sAll() throws Exception {
        Session session 
= HibernateUtil.currentSession();
        
        System.out.println(
"---------------------------------------------");
        List
<Level> list =  session.createQuery(" from Level tl where tl.father is null ").list();
        
for( Level tmp : list ){
            System.out.println(
"---->" + tmp.getName()+" visible="+tmp.getVisible()  );
            
            
for(  Level tt : tmp.getChildSet() ){
                System.out.println( tt.getName()
+" visible="+tt.getVisible()  );
            }
            
        }
        System.out.println( list.get(
0).getVisible()+":"+ list.size() );
    }
    
}

结果: