- 浏览: 34642 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
careast:
alin_ass 写道emma的问题在于开发人员已经不维护了, ...
使用emma收集webapp运行期代码覆盖率 -
alin_ass:
emma的问题在于开发人员已经不维护了,存在乱码和改代码重启后 ...
使用emma收集webapp运行期代码覆盖率 -
alin_ass:
今天发现2个问题,只解决了一个
问题1:图片自动缩放,解决如 ...
开源项目-使用googlecodewiki来编写pdf文档 -
SHQ:
赞一个 杭州GTUG的哦 呵呵
开源项目-使用googlecodewiki来编写pdf文档 -
samwalt:
tiandeyu188 写道这个现在淘宝自己做的已经很成熟了, ...
taobao+facebook+google=?
最近几天在写的一个jdbc orm, 放上来交流学习~~
目标:
no sql, no map , no sql, no map...............................(省略一百遍 ).
约束&特点:
显示代理
操纵proxy domain getter/setter等于构建sql, 重构对象即重构sql
domain对象属性和column名字相同
domain有接口
domain是javabean
某些dao接口参数需要beanproxy(主要是update的接口)
基本没有级联orm
待实现:
多表查询
稍微复杂的sql生成
考虑local&remote Object cache,query cache...
dao example:
修改自apache dbutils,用来做auto map
目标:
no sql, no map , no sql, no map...............................(省略一百遍 ).
约束&特点:
显示代理
操纵proxy domain getter/setter等于构建sql, 重构对象即重构sql
domain对象属性和column名字相同
domain有接口
domain是javabean
某些dao接口参数需要beanproxy(主要是update的接口)
基本没有级联orm
待实现:
多表查询
稍微复杂的sql生成
考虑local&remote Object cache,query cache...
dao example:
** * @version 2007-5-4 * @author xalinx at gmail dot com * */ public class UserDaoImpl extends DaoSupport<User, Long> implements UserDao { private final ParameterizedRowMapper<UserImpl> rowMapper = new AutoRowMapper<UserImpl>() { }; public void deleteById(Long id) { // create proxy BeanMonitor<User> monitor = new BeanMonitor<User>(); User proxy = monitor.proxy(new UserImpl()); // proxy where proxy.setId(id); monitor.eq(); getSimpleDaoTemplate().proxyDelete(monitor); } public User findById(Long id) { // create proxy BeanMonitor<User> monitor = new BeanMonitor<User>(); User proxy = monitor.proxy(new UserImpl()); // proxy select proxy.getId(); proxy.getUsername(); proxy.getPassword(); proxy.getNickname(); proxy.getCity(); proxy.getProv(); proxy.getUserStatus(); proxy.getCreateTime(); proxy.getModifyTime(); // proxy where proxy.setId(id); monitor.eq(); return getSimpleDaoTemplate().proxyQueryObject(monitor, rowMapper); } public int findCount() { return getSimpleDaoTemplate().findCount(UserImpl.class); } public void store(User u) { // integrity validate if (u == null || u.getId() <= 0 || u.getUserStatus() < 0 || u.getUsername() == null || u.getPassword() == null || u.getNickname() == null || u.getCreateTime() == null || u.getModifyTime() == null) { throw new DataIntegrityViolationException(u.toString()); } BeanMonitor<User> monitor = new BeanMonitor<User>(); User proxy = monitor.proxy(new UserImpl()); // proxy insert proxy.setId(u.getId()); proxy.setUsername(u.getUsername()); proxy.setPassword(u.getPassword()); proxy.setNickname(u.getNickname()); proxy.setCity(u.getCity()); proxy.setProv(u.getProv()); proxy.setUserStatus(u.getUserStatus()); proxy.setCreateTime(u.getCreateTime()); proxy.setModifyTime(u.getModifyTime()); // store getSimpleDaoTemplate().proxyStore(monitor); } public void updateById(BeanMonitor<User> monitor) { User u = monitor.getBean(); // integrity validate if (u == null || u.getId() <= 0) { throw new DataIntegrityViolationException(u.toString()); } // proxy where User proxy = monitor.getProxy(); monitor.where(); proxy.setId(u.getId()); monitor.eq(); // update getSimpleDaoTemplate().proxyUpdate(monitor, u.getId()); } public BasePage<User> findPage(UserPageQuery pageQuery) { // create proxy BeanMonitor<User> monitor = new BeanMonitor<User>(); User proxy = monitor.proxy(new UserImpl()); // proxy select proxy.getId(); proxy.getUsername(); proxy.getCreateTime(); // proxy where if (null != pageQuery.getUser().getCity()) { proxy.setCity(pageQuery.getUser().getCity()); monitor.eq(); } if (null != pageQuery.getEndCreateTime()) { proxy.setCreateTime(pageQuery.getEndCreateTime()); monitor.and().leeq(); } if (null != pageQuery.getStartCreateTime()) { proxy.setCreateTime(pageQuery.getStartCreateTime()); monitor.and().gteq(); } if (null != pageQuery.getUser().getUsername()) { proxy.setUsername(pageQuery.getUser().getUsername()); monitor.and().like(); } // query & orm & page return getSimpleDaoTemplate().proxyQueryPage(monitor, rowMapper, pageQuery); } }
评论
4 楼
alin_ass
2007-05-18
jdbc template & dao support
/** * @version 2007-5-10 * @author xalinx at gmail dot com * */ public class SimpleDaoTemplate extends SimpleJdbcTemplate { private SqlBuilder sqlBuilder; public void setSqlBuilder(SqlBuilder sqlBuilder) { this.sqlBuilder = sqlBuilder; } /** * @param classicJdbcTemplate */ public SimpleDaoTemplate(JdbcOperations classicJdbcTemplate) { super(classicJdbcTemplate); } @SuppressWarnings("unchecked") @Override public <T> T queryForObject(String sql, ParameterizedRowMapper<T> rm, Object... args) throws DataAccessException { Object obj = (ObjectUtils.isEmpty(args) ? getJdbcOperations().queryForObject(sql, rm) : getJdbcOperations() .queryForObject(sql, args, rm)); return obj == null ? null : (T) obj; } public <T> T queryObject(String sql, ParameterizedRowMapper<? extends T> rm, Object... args) { return queryForObject(sql, rm, args); } @SuppressWarnings("unchecked") public <T> List<T> queryForList(String sql, ParameterizedRowMapper<? extends T> rm, Object... args) throws DataAccessException { return (List<T>) (ObjectUtils.isEmpty(args) ? getJdbcOperations().query(sql, rm) : getJdbcOperations().query( sql, args, rm)); } public <T> BasePage<T> proxyQueryPage(BeanMonitor<T> beanMonitor, ParameterizedRowMapper<? extends T> rowMapper, PageQuery pageQuery) { QueryWrap wrap = sqlBuilder.buildLimitSelect(beanMonitor, pageQuery.getStart(), pageQuery.getPageSize()); List<T> items = queryForList(wrap.getSql(), rowMapper, wrap.getValues()); return new BasePage<T>(pageQuery, items); } public <T> List<T> proxyQueryList(BeanMonitor<T> monitor, ParameterizedRowMapper<? extends T> rm) { QueryWrap wrap = sqlBuilder.buildSelect(monitor); return queryForList(wrap.getSql(), rm, wrap.getValues()); } public <T> T proxyQueryObject(BeanMonitor<T> monitor, ParameterizedRowMapper<? extends T> rm) { QueryWrap wrap = sqlBuilder.buildSelect(monitor); return queryObject(wrap.getSql(), rm, wrap.getValues()); } public <T> void proxyStore(BeanMonitor<T> monitor) { QueryWrap wrap = sqlBuilder.buildInsert(monitor); update(wrap.getSql(), wrap.getValues()); } public <T> void proxyDelete(BeanMonitor<T> monitor) { QueryWrap wrap = sqlBuilder.buildDelete(monitor); update(wrap.getSql(), wrap.getValues()); } public <E> void proxyUpdate(BeanMonitor<E> monitor, Object id) { QueryWrap wrap = sqlBuilder.buildUpdate(monitor); update(wrap.getSql(), wrap.getValues()); } public <E> int findCount(BeanMonitor<E> monitor) { if (null == monitor) { throw new IllegalArgumentException(); } QueryWrap wrap = sqlBuilder.buildCount(monitor); return queryForInt(wrap.getSql(), wrap.getValues()); } public <E> int findCount(Class<E> entity) { if (null == entity) { throw new IllegalArgumentException(); } QueryWrap wrap = sqlBuilder.buildCount(entity); return queryForInt(wrap.getSql(), wrap.getValues()); } }
/** * @version 2007-5-9 * @author xalinx at gmail dot com * */ public class DaoSupport<E, ID extends Serializable> extends JdbcDaoSupport { protected JdbcTemplate createJdbcTemplate(DataSource dataSource) { return new DaoTemplate(dataSource); } private SimpleDaoTemplate simpleDaoTemplate; /** * Create a SimpleJdbcTemplate based on the configured JdbcTemplate. */ protected void initTemplateConfig() { this.simpleDaoTemplate = new SimpleDaoTemplate(getJdbcTemplate()); this.simpleDaoTemplate.setSqlBuilder(sqlBuilder); } /** * Return a SimpleJdbcTemplate wrapping the configured JdbcTemplate. */ protected SimpleDaoTemplate getSimpleDaoTemplate() { return simpleDaoTemplate; } private SqlBuilder sqlBuilder; public void setSqlBuilder(SqlBuilder builder) { this.sqlBuilder = builder; initTemplateConfig(); } }
3 楼
alin_ass
2007-05-18
sql builder
/** * @version 2007-5-17 * @author xalinx at gmail dot com * */ public class SqlBuilder { private NameMapper nameMapper; public void setNameMapper(NameMapper nameMapper) { this.nameMapper = nameMapper; } private Dialect dialect; public void setDialect(Dialect dialect) { this.dialect = dialect; } public void setDialectFactory(DialectFactory factory) { setDialect(factory.getDialect()); } public <T> QueryWrap buildLimitSelect(BeanMonitor<T> beanMonitor, int start, int size) { QueryWrap wrap = buildSelect(beanMonitor); boolean offset = 0 == start ? false : true; wrap.setSql(dialect.getLimitSql(wrap.getSql(), offset)); wrap.setValues(dialect.getLimitArguments(start, size, wrap.getValues())); return wrap; } public <T> QueryWrap buildSelect(BeanMonitor<T> monitor) { String tableName = getTableName(monitor); List<String> columns = monitor.getReadedPropertyNames(); int columnNum = columns.size(); StringBuilder builder = new StringBuilder(128); builder.append("select "); for (int i = 0; i < columnNum; i++) { builder.append(columns.get(i)); if (i < columnNum - 1) { builder.append(","); } } builder.append(" from "); builder.append(tableName); buildWhereExpression(monitor, builder); Object[] values = monitor.getWritedPropertyValues().toArray(ArrayKit.EMPTY_OBJECT_ARRAY); return new QueryWrap(builder.toString(), values); } public <T> QueryWrap buildDelete(BeanMonitor<T> monitor) { String tableName = getTableName(monitor); StringBuilder builder = new StringBuilder(128); builder.append("delete from "); builder.append(tableName); buildWhereExpression(monitor, builder); Object[] values = monitor.getWritedPropertyValues().toArray(ArrayKit.EMPTY_OBJECT_ARRAY); return new QueryWrap(builder.toString(), values); } public <T> QueryWrap buildInsert(BeanMonitor<T> monitor) { String tableName = getTableName(monitor); List<String> columns = monitor.getWritedPropertyNames(); int columnNum = columns.size(); StringBuilder builder = new StringBuilder(128); builder.append("insert into "); builder.append(tableName); builder.append(" ("); for (int i = 0; i < columnNum; i++) { builder.append(columns.get(i)); if (i < columnNum - 1) { builder.append(","); } } builder.append(") values ("); for (int i = 0; i < columnNum; i++) { builder.append("?"); if (i < columnNum - 1) { builder.append(","); } } builder.append(")"); Object[] values = monitor.getWritedPropertyValues().toArray(ArrayKit.EMPTY_OBJECT_ARRAY); return new QueryWrap(builder.toString(), values); } public <E> QueryWrap buildCount(BeanMonitor<E> monitor) { String tableName = getTableName(monitor); StringBuilder builder = new StringBuilder(128); builder.append("select count(*) from "); builder.append(tableName); buildWhereExpression(monitor, builder); Object[] values = monitor.getWritedPropertyValues().toArray(ArrayKit.EMPTY_OBJECT_ARRAY); return new QueryWrap(builder.toString(), values); } public <E> QueryWrap buildCount(Class<E> entity) { String tableName = getTableName(entity); return new QueryWrap("select count(*) from " + tableName, null); } /** * * * @param monitor * @param id */ public <E> QueryWrap buildUpdate(BeanMonitor<E> monitor) { List<String> columns = monitor.getWritedPropertyNames(); String tableName = getTableName(monitor); int columnNum = monitor.getWhereOffset(); StringBuilder builder = new StringBuilder(128); builder.append("update "); builder.append(tableName); builder.append(" set "); for (int i = 0; i < columnNum; i++) { builder.append(columns.get(i)); builder.append("=?"); if (i < columnNum - 1) { builder.append(","); } } buildWhereExpression(monitor, builder); Object[] values = monitor.getWritedPropertyValues().toArray(ArrayKit.EMPTY_OBJECT_ARRAY); return new QueryWrap(builder.toString(), values); } private String getTableName(BeanMonitor beanMonitor) { return nameMapper.getTableName(beanMonitor.getBean().getClass().getCanonicalName()); } private String getTableName(Class entity) { return nameMapper.getTableName(entity.getCanonicalName()); } private <E> void buildWhereExpression(BeanMonitor<E> monitor, StringBuilder builder) { int whereOffset = monitor.getWhereOffset(); List<String> columns = monitor.getWritedPropertyNames(); // build where expression if (!CollectionKit.isEmpty(columns) || whereOffset < columns.size()) { int columnNum = columns.size(); builder.append(" where"); Iterator<Condition> conditions = monitor.getConditions().iterator(); for (int i = whereOffset; i < columnNum; i++) { String columnName = columns.get(i); Condition cond = null; while (true) { cond = conditions.next(); if (!cond.isCompare()) { builder.append(" "); builder.append(cond.getExpression()); } else { break; } } builder.append(" "); builder.append(columnName); builder.append(cond.getExpression()); builder.append("?"); } } } }
2 楼
alin_ass
2007-05-18
bean monitor
/** * @author alin [xalinx at gmail dot com] * @date 2007-5-11 */ public class BeanMonitor<E> { private E bean; private E proxy; private PropertyDescriptor[] allProperties; private List<String> readedPropertyNames; private List<String> writedPropertyNames; private List<Object> writedPropertyValues; private List<Condition> conditions; public E getBean() { return bean; } public E getProxy() { return proxy; } public List<String> getReadedPropertyNames() { return readedPropertyNames; } public List<String> getWritedPropertyNames() { return writedPropertyNames; } public List<Object> getWritedPropertyValues() { return writedPropertyValues; } public List<Condition> getConditions() { return conditions; } private void addReaded(String pName) { if (null == readedPropertyNames) { readedPropertyNames = new ArrayList<String>(allProperties.length * 3 / 2); } readedPropertyNames.add(pName); } private void addWrited(String pName, Object value) { if (null == writedPropertyNames) { writedPropertyNames = new ArrayList<String>(allProperties.length * 3 / 2); writedPropertyValues = new ArrayList<Object>(allProperties.length * 3 / 2); } writedPropertyNames.add(pName); writedPropertyValues.add(value); } private void addCondition(Condition cond) { if (null == conditions) { conditions = new ArrayList<Condition>(allProperties.length * 3 / 2); } conditions.add(cond); } @SuppressWarnings("unchecked") public E proxy(E bean) { this.bean = bean; Class cls = bean.getClass(); BeanInfo bi; try { bi = Introspector.getBeanInfo(cls); } catch (IntrospectionException e) { throw new RuntimeException(e); } this.allProperties = bi.getPropertyDescriptors(); this.proxy = (E) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), new BeanHandler()); return proxy; } private class BeanHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object invokeResult = method.invoke(bean, args); for (int i = 0; i < allProperties.length; i++) { PropertyDescriptor pd = allProperties[i]; // skip default class property if (pd.getName().equals("class")) { continue; } if (null != pd.getReadMethod() && pd.getReadMethod().getName().equals(method.getName())) { addReaded(pd.getName()); break; } else if (null != pd.getWriteMethod() && pd.getWriteMethod().getName().equals(method.getName())) { // args[0] is suitable? addWrited(pd.getName(), args[0]); break; } } return invokeResult; } } /** * @return */ public BeanMonitor<E> like() { addCondition(Condition.LIKE); return this; } /** * @return */ public BeanMonitor<E> and() { addCondition(Condition.AND); return this; } /** * @return */ public BeanMonitor<E> or() { addCondition(Condition.OR); return this; } /** * ( * * @return */ public BeanMonitor<E> start() { addCondition(Condition.START); return this; } /** * } * * @return */ public BeanMonitor<E> end() { addCondition(Condition.END); return this; } /** * = */ public BeanMonitor<E> eq() { addCondition(Condition.EQ); return this; } /** * <= * * @return */ public BeanMonitor<E> leeq() { addCondition(Condition.LE_EQ); return this; } /** * < * * @return */ public BeanMonitor<E> le() { addCondition(Condition.LE); return this; } /** * >= * * @return */ public BeanMonitor<E> gteq() { addCondition(Condition.GT_EQ); return this; } /** * > * * @return */ public BeanMonitor<E> gt() { addCondition(Condition.GT); return this; } public BeanMonitor<E> isNotNull() { addCondition(Condition.IS_NOT_NULL); return this; } public BeanMonitor<E> isNull() { addCondition(Condition.IS_NULL); return this; } private int whereOffset = 0; /** * */ public void where() { whereOffset = this.writedPropertyNames.size(); } public int getWhereOffset() { return whereOffset; } }
1 楼
alin_ass
2007-05-16
修改自apache dbutils,用来做auto map
public abstract class AutoBeanHandler<T> implements ParameterizedHandler<T> { /** * The Class of beans produced by this handler. */ private Class<T> type = null; /** * The RowProcessor implementation to use when converting rows into beans. */ private RowProcessor convert = BasicRowProcessor.instance(); public AutoBeanHandler() { type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } public T handle(ResultSet rs, int rowNum) throws SQLException { return this.convert.toBean(rs, rowNum, type); } public List<T> handle(ResultSet rs) throws SQLException { return this.convert.toBeanList(rs, type); } } public abstract class AutoRowMapper<T> extends AutoBeanHandler<T> implements ParameterizedRowMapper<T> { public T mapRow(ResultSet rs, int rowNum) throws SQLException { return super.handle(rs, rowNum); } }
相关推荐
Oracle提供了多种JDBC驱动,包括 Thin、Thin No-TNS、OCI (Oracle Call Interface) 和 JMS (Java Message Service)。其中, Thin 驱动是一个纯Java实现,无需Oracle客户端软件,适合跨平台使用。oci驱动则需要本地...
2. **Oracle JDBC驱动**:Oracle提供了多种JDBC驱动,包括 Thin、Thin No-TNS、 Thick、JDBC OCI 和JDBC FAN。其中, Thin 驱动是最常用的一种,它是一个纯Java实现,不需要Oracle客户端软件。加载Oracle JDBC驱动后...
sql-q 一个简单的、轻量级的 Java JDBC ORM,尽可能类似于普通的 SQL,适用于 RESTful 服务。 不支持连接,但您始终可以对它们使用普通的 SQL 查询。用法模型类: public class Item {// By default, id is primary ...
5. **分页导航**:在JSP页面上创建上一页和下一页的链接,计算出正确的LIMIT和OFFSET值,然后更新SQL查询。 6. **关闭资源**:操作完成后,记得关闭`ResultSet`、`Statement`和`Connection`,防止资源泄露。 在...
没有ORM No ORM(NORM)软件包是一组基于JDBC构建的Java实用程序,用于以更安全和类型安全的方式更好地将SQL查询集成到Java代码中,而无需在Java中重新描述SQL表结构。 相反,其想法是使程序员能够在插入Java的类型...
- 使用ORM框架如Hibernate或MyBatis,可以更方便地进行SQL操作,减少手写SQL语句的错误。 - 遵循DRY(Don't Repeat Yourself)原则,避免代码重复,提高代码复用性。 - 保持代码整洁,遵循编码规范,使代码易于...
Hibernate:ORM的中间件,或者说是实现了ORM的一个框架,对JDBC做了轻量级的封装。 ORM:使用元数据信息来描述对象和数据库之间的关系,并且能够自动实现java中持久化对象到关系型数据库中表的映射 脏检查:自动对...
- **sqljdbc4.jar**:Microsoft SQL Server JDBC驱动程序,用于连接SQL Server数据库。 综上所述,这些JAR包构成了Struts2+Spring2+Hibernate3+Annotation开发所需的基本环境。通过合理配置这些库,开发者可以构建...
iBATIS是一个以SQL为中心的持久化层框架,它与Hibernate等对象关系映射(ORM)工具有所不同。iBATIS主要关注于SQL查询的参数和结果集映射,而不是像传统的ORM那样关注于将数据库表结构完全映射到对象模型上。这使得...
5. **ORM映射**:提供标签支持对象与数据库字段的映射,同时也支持对象关系组件的维护。 然而,MyBatis也存在一定的缺点: 1. **SQL编写工作量**:对于字段多、关联表复杂的场景,编写SQL可能较为耗时,需要开发者...
- **Hibernate与JDBC的关系**:Hibernate是对JDBC的封装,它简化了数据库操作,并提供了面向对象的方式来处理数据库交互。 4. **其他ORM框架**: - Apache OJB、TopLink、iBatis(MyBatis)、EJB CMP等也都是常见...
6. 使用Hibernate或其他Java框架调用Oracle存储过程,需要了解对应的JDBC API或ORM框架的调用方法。 调用Oracle存储过程的方式有多种,以下是三种常见情况: - **无返回值的存储过程**:这类过程通常用于执行一些...
对于现代应用,更推荐使用JDBC直接支持的数据库(如MySQL、PostgreSQL等)或者使用ORM框架如Hibernate,以提高性能和简化开发。 总结来说,"FoxPro_jdbc.jar"是Java程序通过JDBC-ODBC桥接访问FoxPro数据库的关键...
- **No Model**:如果应用程序不需要持久化对象或不需要复杂的数据模型,可以采用无模型的方式,直接使用简单的 POJO(Plain Old Java Object)对象。 - **ORM Framework**:Compass 能够与多种 ORM(Object-...
WHERE s.DEPT_NO = d.DEPT_NO) > 100000; ``` - **查询工资第二高的员工**: ```sql WITH ranked_salaries AS ( SELECT e.EMP_NAME, e.DEPT_NO, s.SALARY, RANK() OVER (ORDER BY s.SALARY DESC) AS salary_...
在Java开发中,Hibernate是一个非常流行的ORM(对象关系映射)框架,它允许开发者将数据库操作转化为对Java对象的操作,极大地简化了数据持久化的复杂性。本教程旨在提供一个无需Web服务器环境,在Eclipse中直接运行...
5. **处理结果集**:如果执行SQL返回了结果集,可以使用`ResultSet`进行遍历和数据读取。 6. **关闭资源**:执行完数据库操作后,记得关闭ResultSet、Statement和Connection,以释放系统资源。 **JDBC示例代码**:...
- **数据访问/集成**:提供了ORM框架支持(如Hibernate)、JDBC抽象层等。 - **Web模块**:提供了Spring MVC框架用于构建Web应用。 - **AOP与Instrumentation**:提供面向切面编程支持,增强了代码的复用性。 - **...
### Java分页方法总结 #### 一、MySQL的分页技术 MySQL的分页操作相对简单,主要通过`LIMIT`语句实现。该语句允许开发者指定查询结果...此外,还可以考虑使用ORM框架如Hibernate或MyBatis来简化分页查询的代码实现。
例如,我们可以使用JDBC或者ORM框架(如Hibernate、MyBatis)来执行分页查询。以下是一个基于JDBC的简单示例: ```java // 假设我们有一个SQL查询语句 String sql = "SELECT * FROM table"; // 创建PageUtils对象...