source: trunk/fmgVen/src/com/fmguler/ven/Ven.java @ 40

Last change on this file since 40 was 37, checked in by fmguler, 13 years ago

Refs #7 - Implemented orderAsc and orderDesc methods of Criteria. Have been testing these for a while, no problem so far. Added BigDecimal to db classes (Numeric db type). If the column name is "order" it is escaped while insert/update. (This should be done for all db keywords). Fixed missing mapping of one to many assc. (lists) of many to one (object) assc (obj.obj.list).

File size: 10.1 KB
RevLine 
[22]1/*
2 *  fmgVen - A Convention over Configuration Java ORM Tool
3 *  Copyright 2010 Fatih Mehmet Güler
4 *
5 *  Licensed under the Apache License, Version 2.0 (the "License");
6 *  you may not use this file except in compliance with the License.
7 *  You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 *  under the License.
17 */
18package com.fmguler.ven;
19
[28]20import com.fmguler.ven.util.Convert;
[26]21import java.util.HashMap;
[23]22import java.util.List;
[27]23import java.util.Map;
[28]24import java.util.Set;
[23]25import javax.sql.DataSource;
[26]26import org.springframework.beans.BeanWrapper;
27import org.springframework.beans.BeanWrapperImpl;
28import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
[23]29import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
[26]30import org.springframework.jdbc.core.namedparam.SqlParameterSource;
[23]31
[22]32/**
33 * The main class for data access
34 * @author Fatih Mehmet Güler
35 */
36public class Ven {
[23]37    private NamedParameterJdbcTemplate template;
38    private QueryGenerator generator;
39    private QueryMapper mapper;
[32]40    private boolean debug = false;
[23]41
42    public Ven() {
43        generator = new QueryGenerator();
44        mapper = new QueryMapper();
45    }
46
47    public int count() {
48        return 0;
49    }
50
[29]51    /**
52     * Get the object with the specified id, of the specified objectClass type.
53     * <p>
54     * By default none of the associations will be retrieved.
[37]55     * To include the object associations (retrieve the object graph) joins
56     * should be specified, e.g.
[29]57     * <code>SomeObject.anotherObject</code>
[37]58     *
[29]59     * @param id the id of the object to be retrieved
60     * @param objectClass the class of the object to be retrieved
61     * @param joins the set of object graphs to be included with the object
62     * @return the retrieved object including specified associations
63     */
[28]64    public Object get(int id, Class objectClass, Set joins) {
65        String query = generator.generateSelectQuery(objectClass, joins);
66        query += " where 1=1 and " + Convert.toDB(Convert.toSimpleName(objectClass.getName())) + ".id = :___id ";
67
68        Map paramMap = new HashMap();
69        paramMap.put("___id", new Integer(id));
70        if (debug) System.out.println("Ven - SQL: " + query);
71
72        List result = mapper.list(query, paramMap, objectClass);
73        if (result.isEmpty()) return null;
74        if (result.size() > 1) System.out.println("Ven - WARNING >> get(id) returns more than one row");
75        return result.get(0);
[23]76    }
77
[26]78    /**
[37]79     * Get the object with the specified id, of the specified objectClass type.
80     * <p>
81     * By default none of the associations will be retrieved.
82     * To include the object associations (retrieve the object graph) joins
83     * should be specified, e.g.
84     * <code>SomeObject.anotherObject</code>
85     *
86     * @param id the id of the object to be retrieved
87     * @param objectClass the class of the object to be retrieved
88     * @param joins the set of object graphs to be included with the object
89     * @param criteria to filter and order the result according to some criteria
90     * (e.g. for associations)
91     * @return the retrieved object including specified associations
92     */
93    public Object get(int id, Class objectClass, Set joins, Criteria criteria) {
94        String query = generator.generateSelectQuery(objectClass, joins);
95        query += " where 1=1 and " + Convert.toDB(Convert.toSimpleName(objectClass.getName())) + ".id = :___id " + criteria.criteriaStringToSQL() + " and " + criteria.criteriaToSQL() + criteria.orderStringToSQL();
96
97        criteria.getParameters().put("___id", new Integer(id));
98        if (debug) System.out.println("Ven - SQL: " + query);
99
100        List result = mapper.list(query, criteria.getParameters(), objectClass);
101        if (result.isEmpty()) return null;
102        if (result.size() > 1) System.out.println("Ven - WARNING >> get(id) returns more than one row");
103        return result.get(0);
104    }
105
106    /**
[29]107     * List the objects of the specified objectClass type.
108     * <p>
109     * By default none of the associations will be retrieved.
[37]110     * To include the object associations (retrieve the object graph) joins
111     * should be specified, e.g.
[29]112     * <code>SomeObject.anotherObject</code>
[37]113     *
[29]114     * @param objectClass the class of the objects to be retrieved
115     * @param joins the set of object graphs to be included with objects
116     * @return the list of objects including specified associations
117     */
118    public List list(Class objectClass, Set joins) {
[37]119        return list(objectClass, joins, new Criteria());
[29]120    }
121
122    /**
[37]123     * List the objects of the specified objectClass type, filtering according
124     * to some criteria.
[30]125     * <p>
126     * By default none of the associations will be retrieved.
[37]127     * To include the object associations (retrieve the object graph) joins
128     * should be specified, e.g.
[30]129     * <code>SomeObject.anotherObject</code>
[37]130     *
[30]131     * @param objectClass the class of the objects to be retrieved
132     * @param joins the set of object graphs to be included with objects
133     * @param criteria to filter and order the result according to some criteria
[37]134     * @return the list of objects including the specified associations filtered
135     * according to the specified criteria
[30]136     */
137    public List list(Class objectClass, Set joins, Criteria criteria) {
138        String query = generator.generateSelectQuery(objectClass, joins);
[37]139        query += " where 1=1 " + criteria.criteriaStringToSQL() + " and " + criteria.criteriaToSQL() + criteria.orderStringToSQL();
[30]140
141        if (debug) System.out.println("Ven - SQL: " + query);
142
143        List result = mapper.list(query, criteria.getParameters(), objectClass);
144        return result;
145    }
146
147    /**
[37]148     * Save the object. If it has a non null (or non zero) "id" property it will
149     * be updated.
[26]150     * It will be inserted otherwise.
151     * <p>
152     * The object will be saved to a table with the same name as the object,
153     * The fields of object will be mapped to the table fields.
[37]154     *
[26]155     * @param object the object to be saved
156     */
[23]157    public void save(Object object) {
[26]158        String query = null;
159
160        if (isObjectNew(object)) {
161            //if this is a new object assign a new id first
162            generateId(object);
163            query = generator.generateInsertQuery(object);
164        } else {
165            query = generator.generateUpdateQuery(object);
166        }
167
168        //execute the insert/update query
169        SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(object);
170        template.update(query, parameterSource);
[23]171    }
172
[27]173    /**
[37]174     * Delete the the object with the specified id of the specified objectClass
175     * type
[27]176     * @param id the id of the object to be deleted
177     * @param objectClass the class of the object to be deleted
178     */
[26]179    public void delete(int id, Class objectClass) {
[27]180        String query = generator.generateDeleteQuery(objectClass);
181        Map parameterMap = new HashMap();
182        parameterMap.put("id", new Integer(id));
183        template.update(query, parameterMap);
[23]184    }
185
[26]186    //--------------------------------------------------------------------------
187    //PRIVATE METHODS
188    //return true if the object id is zero or null false otherwise
189    private boolean isObjectNew(Object object) throws VenException {
190        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
[27]191        Object objectId = beanWrapper.getPropertyValue("id");
[26]192        if (objectId == null) return true;
193        if (!(objectId instanceof Integer)) throw new VenException(VenException.EC_GENERATOR_OBJECT_ID_TYPE_INVALID);
194        return ((Integer)objectId).intValue() == 0;
195    }
196
197    //set new object id
198    private void generateId(Object object) {
199        Integer newObjectId = new Integer(template.queryForInt(generator.generateSequenceQuery(object), new HashMap()));
200        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
201        beanWrapper.setPropertyValue("id", newObjectId);
202    }
203
204    //--------------------------------------------------------------------------
205    //SETTERS
[29]206    /**
207     * Set the DataSource to be used to access to the database
208     */
[23]209    public void setDataSource(DataSource dataSource) {
210        if (dataSource == null) throw new RuntimeException("fmgVen - DataSource cannot be null");
211        this.template = new NamedParameterJdbcTemplate(dataSource);
[28]212        mapper.setDataSource(dataSource);
[23]213    }
214
[29]215    /**
216     * Add the domain packages that have corresponding database tables.
217     * <p>
218     * The objects in these packages are considered persistable.
219     * @param domainPackage the package of the entity classes.
220     * @return this instance to allow chaining.
221     */
[23]222    public Ven addDomainPackage(String domainPackage) {
223        generator.addDomainPackage(domainPackage);
224        mapper.addDomainPackage(domainPackage);
225        return this;
226    }
[32]227
228    /**
229     * Set debug mode, true will log all debug messages to System.out
230     * <p>
[37]231     * Note: Use debug mode to detect problems only. It is not a general purpose
232     * logging mode.
[32]233     * @param debug set true to enable debug mode
234     */
235    public void setDebug(boolean debug) {
236        this.debug = debug;
237        generator.setDebug(debug);
238        mapper.setDebug(debug);
239    }
[37]240
241    //--------------------------------------------------------------------------
242    //GETTERS
243   
244    /**
245     * @return the underlying query generator, for advanced usage.
246     */
247    public QueryGenerator getQueryGenerator() {
248        return generator;
249    }
250
251    /**
252     * @return the underlying query mapper, for advanced usage.
253     */
254    public QueryMapper getQueryMapper() {
255        return mapper;
256    }
[22]257}
Note: See TracBrowser for help on using the repository browser.