走前人的路,充实自己(3)

发布于 2015-11-22 / Java / 0条评论 / 520浏览

相信大家(java程序猿\媛)都见过再某个方法上有一个 @Override

这就是java注解 jdk 1.5版本引入的
不多说了,这次就使用注解完善走前人的路,充实自己(2)

直接上马,新建一个注解 Table.java

package com.denghb.duanzi.base.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 表
 * @author denghb
 *
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
	/**
	 * 表名
	 * @return
	 */
	String name();
	
	/**
	 * 数据库
	 */
	String database() default "";
}

新建Column.java 注解

package com.denghb.duanzi.base.annotation;

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

/**
 * 字段
 * @author denghb
 *
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {

	/**
	 * 列名
	 * @return
	 */
	String name();
}

完善后的 JdbcTools.java

package com.denghb.duanzi.base.tools;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.denghb.duanzi.base.annotation.Column;
import com.denghb.duanzi.base.annotation.Table;
import com.denghb.duanzi.base.domain.Domain;

/**
 * Created by denghb on 15/11/16.
 */
@Repository
public class JdbcTools {

	private static final Logger log = LoggerFactory.getLogger(JdbcTools.class);

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 插入一条数据
	 * 
	 * @param object
	 * @return
	 */
	public boolean insert(Domain domain) {
		// 用来存放sql语句
		StringBuffer sql = new StringBuffer();
		// 用来存放?号的语句
		StringBuffer paramsSql = new StringBuffer();

		// 用来存放参数值
		List<Object> params = new ArrayList<Object>();

		sql.append("insert into ");
		// 获取表名
		Table table = domain.getClass().getAnnotation(Table.class);
		if (null == table) {
			throw new RuntimeException("不是domain对象");
		}
		
		// 获取数据库名称
		String database = table.database();
		if (StringUtils.isNotBlank(database)) {
			sql.append(database);
			sql.append(".");
		}
		// 获取注解的表名
		sql.append(table.name());
		sql.append(" (");

		// 计数器
		int count = 0;

		try {
			// 分析列
			Field[] fields = domain.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				String fieldName = field.getName();
				if ("serialVersionUID".equals(fieldName)) {
					continue;
				}
				Column column = field.getAnnotation(Column.class);
				if (null == column) {
					// 没有列注解的直接跳过
					continue;
				}
				// 获取具体参数值
				Method getter = getGetter(domain.getClass(), fieldName);

				if (getter == null) {
					// 没有get method 的跳过
					continue;
				}

				Object value = getter.invoke(domain);
				if (value == null) {
					// 如果参数值是null就直接跳过(不允许覆盖为null值,规范要求更新的每个字段都要有值,没有值就是空字符串)
					continue;
				}

				if (count != 0) {
					sql.append(",");
				}
				// 字段名
				sql.append(column.name());

				if (count != 0) {
					paramsSql.append(",");
				}
				paramsSql.append("?");

				params.add(value);
				count++;
			}
		} catch (Exception e) {
			log.debug(e.getMessage(), e);
		}

		sql.append(") values (");
		sql.append(paramsSql);
		sql.append(")");

		Object[] objects = params.toArray();

		// 是debug的才执行
		if (log.isDebugEnabled()) {
			log.debug("sql:" + sql.toString());
			log.debug("param:" + Arrays.toString(objects));
		}

		// 执行insert
		int res = jdbcTemplate.update(sql.toString(), params.toArray(objects));
		if (1 == res) {
			// 成功了获取自动生成的ID
			Map<String, Object> map = jdbcTemplate.queryForMap("SELECT LAST_INSERT_ID() as id");
			domain.setId(Integer.parseInt(map.get("id").toString()));
		}
		// 返回受影响的行数
		return 1==res;
	}

	/**
	 * 获取属性的getter方法
	 * 
	 * @param clazz
	 * @param fieldName
	 * @return
	 */
	private static <T> Method getGetter(Class<T> clazz, String fieldName) {
		String getterName = "get" + StringTools.firstCharToUpperCase(fieldName);
		Method getter = null;
		try {
			getter = clazz.getMethod(getterName);
		} catch (Exception e) {
			log.debug(getterName + " doesn't exist!", e);
		}
		return getter;
	}
}

里面有个Domain.java
每张表都固有的字段,我将它提取出来了,

package com.denghb.duanzi.base.domain;

import java.io.Serializable;
import java.util.Date;

/**
 * 所有实体的公共字段
 * 
 * @author denghb
 *
 */
public class Domain implements Serializable {

	private static final long serialVersionUID = 6733078133781959444L;

	/** 主键 id */
	private int id;
	
	/** 创建时间 */
	private Date createdTime = new Date();
	
	/** 更新时间 */
	private Date updatedTime;
	
	/** 删除 ? */
	private boolean deleted = false;
	
	/** 版本号 */
	private int version = 1;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Date getCreatedTime() {
		return createdTime;
	}

	public void setCreatedTime(Date createdTime) {
		this.createdTime = createdTime;
	}

	public Date getUpdatedTime() {
		return updatedTime;
	}

	public void setUpdatedTime(Date updatedTime) {
		this.updatedTime = updatedTime;
	}

	public boolean isDeleted() {
		return deleted;
	}

	public void setDeleted(boolean deleted) {
		this.deleted = deleted;
	}

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	@Override
	public String toString() {
		return "Domain [id=" + id + ", createdTime=" + createdTime + ", updatedTime=" + updatedTime + ", deleted="
				+ deleted + ", version=" + version + "]";
	}
	
	
}

user_info 表

CREATE TABLE `user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `accountId` int(11) NULL COMMENT '账号ID',
  `name` varchar(45) NULL COMMENT '名字|昵称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `gender` tinyint(2) DEFAULT '1' COMMENT '性别 1男 0女',
  `sign` varchar(10) DEFAULT NULL COMMENT '个性签名',
  `email` varchar(45) DEFAULT NULL COMMENT '邮箱',
  `mobile` varchar(45) DEFAULT NULL COMMENT '手机号',
  `status` varchar(45) DEFAULT '0' COMMENT '状态 0 等待激活不能登录 1 已激活 3 异常帐号',
  `createdTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updatedTime` datetime DEFAULT NULL COMMENT '更新时间',
  `deleted` tinyint(2) NOT NULL DEFAULT '0' COMMENT '是否删除 1 删除',
  `version` int(11) NOT NULL DEFAULT '1' COMMENT '版本号',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
</pre>

UserInfo.java  实体
<pre>
package com.denghb.duanzi.services.domain;

import com.denghb.duanzi.base.annotation.Column;
import com.denghb.duanzi.base.annotation.Table;
import com.denghb.duanzi.base.domain.Domain;

import java.util.Date;

/**
 *
 */
@Table(name="user_info")
public class UserInfo extends Domain {

	private static final long serialVersionUID = 1L;
	
	/** 账号ID */
	@Column(name="accountId")
	private Integer accountId;
	
	/** 名字|昵称 */
	@Column(name="name")
	private String name;
	
	/** 生日 */
	@Column(name="birthday")
	private Date birthday;
	
	/** 性别 1男 0女 */
	@Column(name="gender")
	private Boolean gender;
	
	/** 个性签名 */
	@Column(name="sign")
	private String sign;
	
	/** 邮箱 */
	@Column(name="email")
	private String email;
	
	/** 手机号 */
	@Column(name="mobile")
	private String mobile;
	
	/** 状态 0 等待激活不能登录 1 已激活 3 异常帐号 */
	@Column(name="status")
	private String status;
	

	public Integer getAccountId(){
		return accountId;
	}

	public void setAccountId(Integer accountId){
		this.accountId = accountId;
	}

	public String getName(){
		return name;
	}

	public void setName(String name){
		this.name = name;
	}

	public Date getBirthday(){
		return birthday;
	}

	public void setBirthday(Date birthday){
		this.birthday = birthday;
	}

	public Boolean getGender(){
		return gender;
	}

	public void setGender(Boolean gender){
		this.gender = gender;
	}

	public String getSign(){
		return sign;
	}

	public void setSign(String sign){
		this.sign = sign;
	}

	public String getEmail(){
		return email;
	}

	public void setEmail(String email){
		this.email = email;
	}

	public String getMobile(){
		return mobile;
	}

	public void setMobile(String mobile){
		this.mobile = mobile;
	}

	public String getStatus(){
		return status;
	}

	public void setStatus(String status){
		this.status = status;
	}

}

测试

public static void main( String[] args )
    {
        ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        JdbcTools jdbc = app.getBean(JdbcTools.class);
        UserInfo u = new UserInfo();
        u.setName("张三");
        //u.setGender(false);
        jdbc.insert(u);
    }

其实还是很简单的东西。。。

评论
站长统计