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

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

Fixed typed criteria method parameters from Criteria.eq(String attribute, String value) to eq(String attribute, Object value). They accept values of any type, e.g. int, string, date.

Turned off debug messages by default. They can be enabled by setting Ven.setDebug(true).

Updated to Netbeans 7.0.1, which updated build-impl.xml, nothing to do with functionality.

File size: 8.3 KB
Line 
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
20import com.fmguler.ven.util.Convert;
21import java.util.HashMap;
22import java.util.List;
23import java.util.Map;
24import java.util.Set;
25import javax.sql.DataSource;
26import org.springframework.beans.BeanWrapper;
27import org.springframework.beans.BeanWrapperImpl;
28import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
29import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
30import org.springframework.jdbc.core.namedparam.SqlParameterSource;
31
32/**
33 * The main class for data access
34 * @author Fatih Mehmet Güler
35 */
36public class Ven {
37    private NamedParameterJdbcTemplate template;
38    private QueryGenerator generator;
39    private QueryMapper mapper;
40    private boolean debug = false;
41
42    public Ven() {
43        generator = new QueryGenerator();
44        mapper = new QueryMapper();
45    }
46
47    public int count() {
48        return 0;
49    }
50
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.
55     * To include the object associations (retrieve the object graph) joins should be specified, e.g.
56     * <code>SomeObject.anotherObject</code>
57     *
58     * @param id the id of the object to be retrieved
59     * @param objectClass the class of the object to be retrieved
60     * @param joins the set of object graphs to be included with the object
61     * @return the retrieved object including specified associations
62     */
63    public Object get(int id, Class objectClass, Set joins) {
64        String query = generator.generateSelectQuery(objectClass, joins);
65        query += " where 1=1 and " + Convert.toDB(Convert.toSimpleName(objectClass.getName())) + ".id = :___id ";
66
67        Map paramMap = new HashMap();
68        paramMap.put("___id", new Integer(id));
69        if (debug) System.out.println("Ven - SQL: " + query);
70
71        List result = mapper.list(query, paramMap, objectClass);
72        if (result.isEmpty()) return null;
73        if (result.size() > 1) System.out.println("Ven - WARNING >> get(id) returns more than one row");
74        return result.get(0);
75    }
76
77    /**
78     * List the objects of the specified objectClass type.
79     * <p>
80     * By default none of the associations will be retrieved.
81     * To include the object associations (retrieve the object graph) joins should be specified, e.g.
82     * <code>SomeObject.anotherObject</code>
83     *
84     * @param objectClass the class of the objects to be retrieved
85     * @param joins the set of object graphs to be included with objects
86     * @return the list of objects including specified associations
87     */
88    public List list(Class objectClass, Set joins) {
89        String query = generator.generateSelectQuery(objectClass, joins);
90
91        Map paramMap = new HashMap();
92        if (debug) System.out.println("Ven - SQL: " + query);
93
94        List result = mapper.list(query, paramMap, objectClass);
95        return result;
96    }
97
98    /**
99     * List the objects of the specified objectClass type, filtering according to some criteria.
100     * <p>
101     * By default none of the associations will be retrieved.
102     * To include the object associations (retrieve the object graph) joins should be specified, e.g.
103     * <code>SomeObject.anotherObject</code>
104     *
105     * @param objectClass the class of the objects to be retrieved
106     * @param joins the set of object graphs to be included with objects
107     * @param criteria to filter and order the result according to some criteria
108     * @return the list of objects including the specified associations filtered according to the specified criteria
109     */
110    public List list(Class objectClass, Set joins, Criteria criteria) {
111        String query = generator.generateSelectQuery(objectClass, joins);
112        query += " where 1=1 " + criteria.criteriaStringToSQL() + " and " + criteria.criteriaToSQL();
113
114        if (debug) System.out.println("Ven - SQL: " + query);
115
116        List result = mapper.list(query, criteria.getParameters(), objectClass);
117        return result;
118    }
119
120    /**
121     * Save the object. If it has a non null (or non zero) "id" property it will be updated.
122     * It will be inserted otherwise.
123     * <p>
124     * The object will be saved to a table with the same name as the object,
125     * The fields of object will be mapped to the table fields.
126     *
127     * @param object the object to be saved
128     */
129    public void save(Object object) {
130        String query = null;
131
132        if (isObjectNew(object)) {
133            //if this is a new object assign a new id first
134            generateId(object);
135            query = generator.generateInsertQuery(object);
136        } else {
137            query = generator.generateUpdateQuery(object);
138        }
139
140        //execute the insert/update query
141        SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(object);
142        template.update(query, parameterSource);
143    }
144
145    /**
146     * Delete the the object with the specified id of the specified objectClass type
147     * @param id the id of the object to be deleted
148     * @param objectClass the class of the object to be deleted
149     */
150    public void delete(int id, Class objectClass) {
151        String query = generator.generateDeleteQuery(objectClass);
152        Map parameterMap = new HashMap();
153        parameterMap.put("id", new Integer(id));
154        template.update(query, parameterMap);
155    }
156
157    //--------------------------------------------------------------------------
158    //PRIVATE METHODS
159    //return true if the object id is zero or null false otherwise
160    private boolean isObjectNew(Object object) throws VenException {
161        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
162        Object objectId = beanWrapper.getPropertyValue("id");
163        if (objectId == null) return true;
164        if (!(objectId instanceof Integer)) throw new VenException(VenException.EC_GENERATOR_OBJECT_ID_TYPE_INVALID);
165        return ((Integer)objectId).intValue() == 0;
166    }
167
168    //set new object id
169    private void generateId(Object object) {
170        Integer newObjectId = new Integer(template.queryForInt(generator.generateSequenceQuery(object), new HashMap()));
171        BeanWrapper beanWrapper = new BeanWrapperImpl(object);
172        beanWrapper.setPropertyValue("id", newObjectId);
173    }
174
175    //--------------------------------------------------------------------------
176    //SETTERS
177    /**
178     * Set the DataSource to be used to access to the database
179     */
180    public void setDataSource(DataSource dataSource) {
181        if (dataSource == null) throw new RuntimeException("fmgVen - DataSource cannot be null");
182        this.template = new NamedParameterJdbcTemplate(dataSource);
183        mapper.setDataSource(dataSource);
184    }
185
186    /**
187     * Add the domain packages that have corresponding database tables.
188     * <p>
189     * The objects in these packages are considered persistable.
190     * @param domainPackage the package of the entity classes.
191     * @return this instance to allow chaining.
192     */
193    public Ven addDomainPackage(String domainPackage) {
194        generator.addDomainPackage(domainPackage);
195        mapper.addDomainPackage(domainPackage);
196        return this;
197    }
198
199    /**
200     * Set debug mode, true will log all debug messages to System.out
201     * <p>
202     * Note: Use debug mode to detect problems only. It is not a general purpose logging mode.
203     * @param debug set true to enable debug mode
204     */
205    public void setDebug(boolean debug) {
206        this.debug = debug;
207        generator.setDebug(debug);
208        mapper.setDebug(debug);
209    }
210}
Note: See TracBrowser for help on using the repository browser.