代码改变世界

.NET程序员也用JAVA:使用BlazeDS,SpringFramework,MySql,Flex构建RIA应用 part 2 :Java代码编写.

2009-01-12 17:30  Otis's Technology Space  阅读(532)  评论(0编辑  收藏  举报

这次的目标是用JAVA代码添加数据到MySql中和从MySql中获取数据.

为了简单,这些Java代码只求实现目标.实现目标就好..因为在.net下,特别是开发小型的Asp.net程序,并不像java那样会用到很多模式..

第一步,先建表:看Sql都应该知道了.这里直接贴SQL..(我在用phpMyAdmin ^_^)

-- 
-- 数据库: `flex_hibernate_spring_01`
-- 

-- --------------------------------------------------------

-- 
-- 表的结构 `t_user`
-- 

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(255) default NULL,
  `password` varchar(255) default NULL,
  `note` varchar(1255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;

 

数据表建立完成后.下面写Java的Model,代码如下:

package cn.otis.spring.model;

public class User {
    private int id;
    private String userName;
    private String password;
    private String note;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }

}

数据访问用到了Spring的jdbcTemplate,下面配置一下Spring.

要加入的jar包如下:

image

在src下加入log4j.properties和applicationContext.xml 如下图:

image

applicationContext.xml 设置如下:开始是用连接池的,一切都没问题,但是在用flex remoting调用时,竟然说找不到commons-pool-1.4.jar这个包..所以现在换回spring的datasource了..

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <!--  class="org.apache.commons.dbcp.BasicDataSource"
     <property name="initialSize" value="5" />
        <property name="maxActive" value="10" /> -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/flex_hibernate_spring_01" />
        <property name="username" value="root" />
        <property name="password" value="sa" />
        
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
</beans>

这里我加了一个jdbcTemplate的bean并建一个类,让所有DAO类都继承这个类..

package cn.otis.spring.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.*;
import org.springframework.context.support.*;

public class baseJdbcTemplate {
    protected JdbcTemplate jdbcTemplate;

    public baseJdbcTemplate() {
        BeanFactory factory = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        this.jdbcTemplate = (JdbcTemplate) factory.getBean("jdbcTemplate");
    }
}

正规的写法也不是这样.应该是加一个seter方法让Spring注入jdbcTemplate..

我这里用构造函数new 了一个...^_^ .. 是为了之后就不用再写配置文件了..而且也不用为UserManager这个类建一个接口..再写一个UserMangerImpl的类..去实现UserManger...^_^..

下面直接写UserManger.继承自 baseJdbcTemplate...代码如下:

package cn.otis.spring.manager;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import org.springframework.jdbc.core.RowMapper;

import cn.otis.spring.jdbc.baseJdbcTemplate;
import cn.otis.spring.model.User;


public class UserManager extends baseJdbcTemplate{
    private static final String Insert = "insert into t_user (id,username,password,note) values (null,?,?,?)";
    private static final String Update = "update t_user set username=?,password=?,note=? where id=?";
    private static final String Select = "select id,username,password,note from t_user";
    private static final String Select_Where_by_id = Select + " where id=?";
    private RowMapper rowMapper = new RowMapper() {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            User u = new User();
            u.setId(rs.getInt(1));
            u.setPassword(rs.getString(3));
            u.setUserName(rs.getString(2));
            u.setNote(rs.getString(4));
            return u;
        }
    };
    public void addUser(User u){
        this.jdbcTemplate.update(Insert,new Object[] {u.getUserName(),u.getPassword(),u.getNote()});
    }
    public void updateUser(User u){
        this.jdbcTemplate.update(Update,new Object[] {u.getUserName(),
                u.getPassword(),u.getNote(),new Long(u.getId())});
    }
    public User GetUserById(int uid){
        
        User user = (User)this.jdbcTemplate.queryForObject(Select_Where_by_id,
                new Object[]{Long.valueOf(uid)},this.rowMapper);
        return user;
    }
    @SuppressWarnings("unchecked")
    public Collection<User> GetUser(int startIndex,int pageSize){
        String sql = Select + " limit "+startIndex+"," + pageSize;
        Collection<User> users = this.jdbcTemplate.query(sql,this.rowMapper);
        return users;
    }

}

可以看出,用了Spring后,DAO代码简化和好看多了..呵.. 几乎没有了try{}catch{}..

下面写点测试代码.这次先不用junit..因为我还没学到.. ^_^..

package cn.otis.spring.client;

import java.util.Collection;

import cn.otis.spring.manager.UserManager;
import cn.otis.spring.model.User;

public class TestUserManager {
    public static void main(String[] args) {
        User u = new User();
        u.setUserName("otis");
        u.setPassword("otis");
        u.setNote("我现在很好!");
        u.setId(1);
        UserManager umgr = new UserManager();
        umgr.addUser(u);
        
        // update 
        u.setPassword("updated");
        
        umgr.updateUser(u);
        
        u = umgr.GetUserById(1);
        String outStr = u.getUserName() + "  " + u.getPassword() + "  " + u.getNote() + " is Object";
        System.out.println(outStr);
        
        Collection<User> users = umgr.GetUser(0, 30);
        for(User ue : users){
            System.out.println(ue.getNote());
        }
        System.out.println("user length is " + users.size());
        
    }
}

下面再写一个UserService是给flex用的..

package cn.otis.spring.service;

import java.util.Collection;

import cn.otis.spring.manager.UserManager;
import cn.otis.spring.model.User;

public class UsersService {
    private UserManager umgr = new UserManager();
    public String addUser(User u){
        umgr.addUser(u);
        return "添加成功!";
    }
    public String Say(){
        return "I'm OK!";
    }
    public Collection<User> getUsers(){
        return umgr.GetUser(0, 30);
    }
}

ps:看来UserManger必须是接口呀.. 不然还真会带来很多问题..

大功告成!!