├── .circleci └── config.yml ├── .github └── FUNDING.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── j256 │ │ └── ormlite │ │ └── jdbc │ │ ├── BaseJdbcConnectionSource.java │ │ ├── DataSourceConnectionSource.java │ │ ├── JdbcCompiledStatement.java │ │ ├── JdbcConnectionSource.java │ │ ├── JdbcDatabaseConnection.java │ │ ├── JdbcDatabaseResults.java │ │ ├── JdbcPooledConnectionSource.java │ │ ├── JdbcSingleConnectionSource.java │ │ ├── TypeValMapper.java │ │ ├── db │ │ ├── DatabaseTypeUtils.java │ │ ├── Db2DatabaseType.java │ │ ├── DerbyClientServerDatabaseType.java │ │ ├── DerbyEmbeddedDatabaseType.java │ │ ├── GenericOdbcDatabaseType.java │ │ ├── H2DatabaseType.java │ │ ├── HsqldbDatabaseType.java │ │ ├── MariaDbDatabaseType.java │ │ ├── MysqlDatabaseType.java │ │ ├── NetezzaDatabaseType.java │ │ ├── OracleDatabaseType.java │ │ ├── PostgresDatabaseType.java │ │ ├── SqlServerDatabaseType.java │ │ ├── SqlServerJtdsDatabaseType.java │ │ └── SqliteDatabaseType.java │ │ └── spring │ │ ├── DaoFactory.java │ │ └── TableCreator.java ├── javadoc │ ├── com │ │ └── j256 │ │ │ └── ormlite │ │ │ ├── db │ │ │ └── package.html │ │ │ ├── jdbc │ │ │ └── package.html │ │ │ └── spring │ │ │ └── package.html │ └── overview.html └── resources │ └── com │ └── j256 │ └── ormlite │ └── jdbc │ ├── LICENSE.txt │ └── README.txt └── test ├── java └── com │ └── j256 │ └── ormlite │ └── jdbc │ ├── BaseJdbcTest.java │ ├── DataSourceConnectionSourceTest.java │ ├── JdbcCompiledStatementTest.java │ ├── JdbcConnectionSourceTest.java │ ├── JdbcDatabaseConnectionTest.java │ ├── JdbcDatabaseResultsTest.java │ ├── JdbcPooledConnectionSourceTest.java │ ├── JdbcRawResultsImplTest.java │ ├── JdbcSingleConnectionSourceTest.java │ ├── dao │ ├── BulkJdbcDaoTest.java │ ├── DoubleDbOpenTest.java │ └── JdbcBaseDaoImplTest.java │ ├── db │ ├── BaseJdbcDatabaseTypeTest.java │ ├── DatabaseTypeUtilsTest.java │ ├── Db2DatabaseTypeTest.java │ ├── DerbyClientServerDatabaseTypeTest.java │ ├── DerbyEmbeddedDatabaseTypeTest.java │ ├── H2DatabaseTypeTest.java │ ├── HsqldbDatabaseTypeTest.java │ ├── MariaDbDatabaseTypeTest.java │ ├── MysqlDatabaseTypeTest.java │ ├── OracleDatabaseTypeTest.java │ ├── PostgresDatabaseTypeTest.java │ ├── SqlServerDatabaseTypeTest.java │ ├── SqlServerJtdsDatabaseConnectTypeTest.java │ └── SqliteDatabaseTypeTest.java │ ├── examples │ ├── datapersister │ │ ├── DataPersisterMain.java │ │ ├── DateTimePersister.java │ │ ├── MyDatePersister.java │ │ ├── README.txt │ │ └── User.java │ ├── fieldConfig │ │ ├── Account.java │ │ ├── Delivery.java │ │ ├── FieldConfigMain.java │ │ └── README.txt │ ├── foreign │ │ ├── Account.java │ │ ├── ForeignMain.java │ │ ├── Order.java │ │ └── README.txt │ ├── foreignCollection │ │ ├── Account.java │ │ ├── ForeignCollectionMain.java │ │ ├── Order.java │ │ └── README.txt │ ├── manytomany │ │ ├── ManyToManyMain.java │ │ ├── Post.java │ │ ├── README.txt │ │ ├── User.java │ │ └── UserPost.java │ └── simple │ │ ├── Account.java │ │ ├── README.txt │ │ └── SimpleMain.java │ ├── misc │ └── JdbcTransactionManagerTest.java │ ├── spring │ ├── DaoFactoryTest.java │ └── TableCreatorTest.java │ └── stmt │ └── JdbcQueryBuilderTest.java └── resources ├── log4j.properties └── ormliteLocalLog.properties /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # config file for circleci 2 | version: 2 3 | jobs: 4 | build: 5 | docker: 6 | - image: circleci/openjdk:8-jdk-browsers 7 | steps: 8 | - checkout 9 | - restore_cache: 10 | key: j256-ormlite-jdbc-{{ checksum "pom.xml" }} 11 | - run: 12 | name: Get maven project dependencies 13 | command: mvn -P testing -U -DskipTests clean install dependency:resolve-plugins dependency:go-offline 14 | # save the project dependencies 15 | - save_cache: 16 | paths: 17 | - ~/.m2 18 | key: j256-ormlite-jdbc-{{ checksum "pom.xml" }} 19 | - run: 20 | name: mvn package 21 | # we need this profile to file the ormlite-core test release 22 | command: mvn -P testing package 23 | # uploads the test metadata from the `target/surefire-reports` directory so that it can show up in the CircleCI dashboard. 24 | - store_test_results: 25 | path: target/surefire-reports 26 | - run: 27 | name: Generate coverage report using jacoco 28 | command: mvn jacoco:report 29 | - run: 30 | name: Upload coverage report to CodeCov 31 | command: bash <(curl -s https://codecov.io/bash) 32 | - run: 33 | name: Test checks publishing to github 34 | command: mvn -X test-check-publisher:publish 35 | when: always 36 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: j256 4 | patreon: j256 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /target 3 | /.settings 4 | /.classpath 5 | /.project 6 | .idea 7 | *.iml 8 | /dependency-reduced-pom.xml 9 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | ISC License (https://opensource.org/licenses/ISC) 2 | 3 | Copyright 2021, Gray Watson 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ORMLite JDBC 2 | ============ 3 | 4 | This package provides the JDBC specific functionality. The released jars for this include the 5 | [ormlite-core (https://github.com/j256/ormlite-core) package as well. Android users should download the 6 | [ormlite-android](https://github.com/j256/ormlite-android) package instead of this JDBC one. 7 | 8 | * For more background on ORMLite, see the [ormlite-core repo](https://github.com/j256/ormlite-core). 9 | * For more information, visit the [ORMLite home page](http://ormlite.com/). 10 | * Online documentation can be found off the home page. Here's the [getting started information](http://ormlite.com/docs/getting-started). 11 | Here are the [Javadocs for the code](http://ormlite.com/javadoc/ormlite-jdbc/). 12 | * Browse the code on the [git repository](https://github.com/j256/ormlite-jdbc). [![CircleCI](https://circleci.com/gh/j256/ormlite-jdbc.svg?style=svg)](https://circleci.com/gh/j256/ormlite-jdbc) [![CodeCov](https://img.shields.io/codecov/c/github/j256/ormlite-jdbc.svg)](https://codecov.io/github/j256/ormlite-jdbc/) 13 | * Maven packages are published via [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.j256.ormlite/ormlite-jdbc/badge.svg?style=flat-square)](https://maven-badges.herokuapp.com/maven-central/com.j256.ormlite/ormlite-jdbc/) [![javadoc](https://javadoc.io/badge2/com.j256.ormlite/ormlite-jdbc/javadoc.svg)](https://javadoc.io/doc/com.j256.ormlite/ormlite-jdbc) 14 | 15 | Enjoy, Gray Watson 16 | 17 | # Maven Configuration 18 | 19 | Maven packages are published via [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.j256.ormlite/ormlite-jdbc/badge.svg?style=flat-square)](https://maven-badges.herokuapp.com/maven-central/com.j256.ormlite/ormlite-jdbc/) which includes the [ormlite-core](https://github.com/j256/ormlite-core) classes. 20 | 21 | For JDBC usage: 22 | 23 | ``` xml 24 | 25 | com.j256.ormlite 26 | ormlite-jdbc 27 | 6.0 28 | 29 | ``` 30 | 31 | # ChangeLog Release Notes 32 | 33 | The ChangeLog file comes from the ormlite-core repository. See the 34 | [ChangeLog.txt file](https://github.com/j256/ormlite-core/blob/master/src/main/javadoc/doc-files/changelog.txt). 35 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/BaseJdbcConnectionSource.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.sql.DriverManager; 4 | import java.sql.SQLException; 5 | 6 | import com.j256.ormlite.db.DatabaseType; 7 | import com.j256.ormlite.jdbc.db.DatabaseTypeUtils; 8 | import com.j256.ormlite.logger.Logger; 9 | import com.j256.ormlite.logger.LoggerFactory; 10 | import com.j256.ormlite.misc.IOUtils; 11 | import com.j256.ormlite.support.BaseConnectionSource; 12 | import com.j256.ormlite.support.ConnectionSource; 13 | import com.j256.ormlite.support.DatabaseConnection; 14 | import com.j256.ormlite.support.DatabaseConnectionProxyFactory; 15 | 16 | /** 17 | * Base class that defines some of the common JDBC connection source functionality. 18 | * 19 | * @author graywatson 20 | */ 21 | public abstract class BaseJdbcConnectionSource extends BaseConnectionSource implements ConnectionSource { 22 | 23 | protected static Logger logger = LoggerFactory.getLogger(BaseJdbcConnectionSource.class); 24 | 25 | protected String url; 26 | protected DatabaseConnection connection; 27 | protected DatabaseType databaseType; 28 | protected boolean initialized = false; 29 | private static DatabaseConnectionProxyFactory connectionProxyFactory; 30 | 31 | /** 32 | * Constructor for Spring type wiring if you are using the set methods. If you are using Spring then your should 33 | * use: init-method="initialize" 34 | */ 35 | public BaseJdbcConnectionSource() { 36 | // for spring type wiring 37 | } 38 | 39 | /** 40 | * Create a data source for a particular database URL. 41 | * 42 | * @param url 43 | * The database URL which should start jdbc:... 44 | * @throws SQLException 45 | * If the driver associated with the database driver is not found in the classpath. 46 | */ 47 | public BaseJdbcConnectionSource(String url) throws SQLException { 48 | this(url, null, true); 49 | } 50 | 51 | /** 52 | * Create a data source for a particular database URL. The databaseType is usually determined from the databaseUrl 53 | * so most users should call {@link #BaseJdbcConnectionSource(String)} instead. If, however, you need to force the 54 | * class to use a specific DatabaseType then this constructor should be used. 55 | * 56 | * @param url 57 | * The database URL which should start jdbc:... 58 | * @param databaseType 59 | * Database to associate with this connection source. 60 | * @throws SQLException 61 | * If the driver associated with the database driver is not found in the classpath. 62 | */ 63 | public BaseJdbcConnectionSource(String url, DatabaseType databaseType) throws SQLException { 64 | this(url, databaseType, true); 65 | } 66 | 67 | /** 68 | * Set initialize to false if you don't want to initialize. This is used by subclasses. 69 | */ 70 | protected BaseJdbcConnectionSource(String url, DatabaseType databaseType, boolean initialize) throws SQLException { 71 | this.url = url; 72 | this.databaseType = databaseType; 73 | if (initialize) { 74 | initialize(); 75 | } 76 | } 77 | 78 | /** 79 | * Make a connection to the database. 80 | * 81 | * @param logger 82 | * This is here so we can use the right logger associated with the sub-class. 83 | */ 84 | protected abstract DatabaseConnection makeConnection(Logger logger) throws SQLException; 85 | 86 | /** 87 | * Initialize the class after the setters have been called. If you are using the no-arg constructor and Spring type 88 | * wiring, this should be called after all of the set methods. 89 | * 90 | * @throws SQLException 91 | * If the driver associated with the database URL is not found in the classpath. 92 | */ 93 | public void initialize() throws SQLException { 94 | if (initialized) { 95 | return; 96 | } 97 | if (url == null) { 98 | throw new SQLException("url was never set on " + getClass().getSimpleName()); 99 | } 100 | if (databaseType == null) { 101 | databaseType = DatabaseTypeUtils.createDatabaseType(url); 102 | } 103 | databaseType.loadDriver(); 104 | databaseType.setDriver(DriverManager.getDriver(url)); 105 | initialized = true; 106 | } 107 | 108 | @Override 109 | public void close() throws Exception { 110 | if (!initialized) { 111 | throw new SQLException(getClass().getSimpleName() + " was not initialized properly"); 112 | } 113 | if (connection != null) { 114 | connection.close(); 115 | logger.debug("closed connection #{}", connection.hashCode()); 116 | connection = null; 117 | } 118 | } 119 | 120 | @Override 121 | public void closeQuietly() { 122 | IOUtils.closeQuietly(this); 123 | } 124 | 125 | public String getUrl() { 126 | return url; 127 | } 128 | 129 | public void setUrl(String url) { 130 | this.url = url; 131 | } 132 | 133 | @Override 134 | public DatabaseConnection getReadOnlyConnection(String tableName) throws SQLException { 135 | if (!initialized) { 136 | throw new SQLException(getClass().getSimpleName() + " was not initialized properly"); 137 | } 138 | return getReadWriteConnection(tableName); 139 | } 140 | 141 | @Override 142 | public DatabaseConnection getReadWriteConnection(String tableName) throws SQLException { 143 | if (!initialized) { 144 | throw new SQLException(getClass().getSimpleName() + " was not initialized properly"); 145 | } 146 | if (connection != null) { 147 | if (connection.isClosed()) { 148 | throw new SQLException("Connection has already been closed"); 149 | } else { 150 | return connection; 151 | } 152 | } 153 | connection = makeConnection(logger); 154 | if (connectionProxyFactory != null) { 155 | connection = connectionProxyFactory.createProxy(connection); 156 | } 157 | return connection; 158 | } 159 | 160 | @Override 161 | public void releaseConnection(DatabaseConnection connection) throws SQLException { 162 | if (!initialized) { 163 | throw new SQLException(getClass().getSimpleName() + " was not initialized properly"); 164 | } 165 | // noop right now 166 | } 167 | 168 | @Override 169 | @SuppressWarnings("unused") 170 | public boolean saveSpecialConnection(DatabaseConnection connection) throws SQLException { 171 | // noop since this is a single connection source 172 | return true; 173 | } 174 | 175 | @Override 176 | public void clearSpecialConnection(DatabaseConnection connection) { 177 | // noop since this is a single connection source 178 | } 179 | 180 | @Override 181 | public DatabaseType getDatabaseType() { 182 | if (!initialized) { 183 | throw new IllegalStateException(getClass().getSimpleName() + " was not initialized properly"); 184 | } 185 | return databaseType; 186 | } 187 | 188 | @Override 189 | public boolean isOpen(String tableName) { 190 | return connection != null; 191 | } 192 | 193 | @Override 194 | public boolean isSingleConnection(String tableName) { 195 | return true; 196 | } 197 | 198 | // not required 199 | public void setDatabaseType(DatabaseType databaseType) { 200 | this.databaseType = databaseType; 201 | } 202 | 203 | /** 204 | * Set to enable connection proxying. Set to null to disable. 205 | */ 206 | public static void setDatabaseConnectionProxyFactory(DatabaseConnectionProxyFactory connectionProxyFactory) { 207 | BaseJdbcConnectionSource.connectionProxyFactory = connectionProxyFactory; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/JdbcCompiledStatement.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.sql.PreparedStatement; 4 | import java.sql.ResultSetMetaData; 5 | import java.sql.SQLException; 6 | 7 | import com.j256.ormlite.dao.ObjectCache; 8 | import com.j256.ormlite.field.SqlType; 9 | import com.j256.ormlite.misc.IOUtils; 10 | import com.j256.ormlite.stmt.StatementBuilder.StatementType; 11 | import com.j256.ormlite.support.CompiledStatement; 12 | import com.j256.ormlite.support.DatabaseResults; 13 | 14 | /** 15 | * Wrapper around a {@link PreparedStatement} object which we delegate to. 16 | * 17 | * @author graywatson 18 | */ 19 | public class JdbcCompiledStatement implements CompiledStatement { 20 | 21 | private final PreparedStatement preparedStatement; 22 | private final String statement; 23 | private final StatementType type; 24 | private final boolean cacheStore; 25 | private ResultSetMetaData metaData = null; 26 | 27 | public JdbcCompiledStatement(PreparedStatement preparedStatement, String statement, StatementType type, 28 | boolean cacheStore) { 29 | this.preparedStatement = preparedStatement; 30 | this.statement = statement; 31 | this.type = type; 32 | this.cacheStore = cacheStore; 33 | } 34 | 35 | @Override 36 | public int getColumnCount() throws SQLException { 37 | if (metaData == null) { 38 | metaData = preparedStatement.getMetaData(); 39 | } 40 | return metaData.getColumnCount(); 41 | } 42 | 43 | @Override 44 | public String getColumnName(int column) throws SQLException { 45 | if (metaData == null) { 46 | metaData = preparedStatement.getMetaData(); 47 | } 48 | return metaData.getColumnName(column + 1); 49 | } 50 | 51 | @Override 52 | public int runUpdate() throws SQLException { 53 | // this can be a UPDATE, DELETE, or ... just not a SELECT 54 | if (!type.isOkForUpdate()) { 55 | throw new IllegalArgumentException("Cannot call update on a " + type + " statement"); 56 | } 57 | return preparedStatement.executeUpdate(); 58 | } 59 | 60 | @Override 61 | public DatabaseResults runQuery(ObjectCache objectCache) throws SQLException { 62 | if (!type.isOkForQuery()) { 63 | throw new IllegalArgumentException("Cannot call query on a " + type + " statement"); 64 | } 65 | return new JdbcDatabaseResults(preparedStatement, preparedStatement.executeQuery(), objectCache, cacheStore); 66 | } 67 | 68 | @Override 69 | public int runExecute() throws SQLException { 70 | if (!type.isOkForExecute()) { 71 | throw new IllegalArgumentException("Cannot call execute on a " + type + " statement"); 72 | } 73 | preparedStatement.execute(); 74 | return preparedStatement.getUpdateCount(); 75 | } 76 | 77 | @Override 78 | public void close() throws SQLException { 79 | try { 80 | preparedStatement.close(); 81 | } catch (SQLException e) { 82 | throw new SQLException("could not close prepared statement", e); 83 | } 84 | } 85 | 86 | @Override 87 | public void closeQuietly() { 88 | IOUtils.closeQuietly(this); 89 | } 90 | 91 | @Override 92 | public void cancel() throws SQLException { 93 | preparedStatement.cancel(); 94 | } 95 | 96 | @Override 97 | public void setObject(int parameterIndex, Object obj, SqlType sqlType) throws SQLException { 98 | if (obj == null) { 99 | preparedStatement.setNull(parameterIndex + 1, TypeValMapper.getTypeValForSqlType(sqlType)); 100 | } else { 101 | preparedStatement.setObject(parameterIndex + 1, obj, TypeValMapper.getTypeValForSqlType(sqlType)); 102 | } 103 | } 104 | 105 | @Override 106 | public void setMaxRows(int max) throws SQLException { 107 | preparedStatement.setMaxRows(max); 108 | } 109 | 110 | @Override 111 | public void setQueryTimeout(long millis) throws SQLException { 112 | preparedStatement.setQueryTimeout(Long.valueOf(millis).intValue() / 1000); 113 | } 114 | 115 | @Override 116 | public String getStatement() { 117 | return statement; 118 | } 119 | 120 | @Override 121 | public String toString() { 122 | return statement; 123 | } 124 | 125 | /** 126 | * Called by {@link JdbcDatabaseResults#next()} to get more results into the existing ResultSet. 127 | */ 128 | boolean getMoreResults() throws SQLException { 129 | return preparedStatement.getMoreResults(); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/JdbcConnectionSource.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.sql.DriverManager; 4 | import java.sql.SQLException; 5 | import java.util.Properties; 6 | 7 | import com.j256.ormlite.db.DatabaseType; 8 | import com.j256.ormlite.logger.Logger; 9 | import com.j256.ormlite.support.ConnectionSource; 10 | import com.j256.ormlite.support.DatabaseConnection; 11 | 12 | /** 13 | * Implementation of the ConnectionSource interface that supports what is needed by ORMLite. This is not thread-safe nor 14 | * synchronized and under the covers uses a single database connection. For other dataSources, see the 15 | * {@link DataSourceConnectionSource} class. 16 | * 17 | *

18 | * NOTE: If you are using the Spring type wiring in Java, {@link #initialize} should be called after all of the 19 | * set methods. In Spring XML, init-method="initialize" should be used. 20 | *

21 | * 22 | * @author graywatson 23 | */ 24 | public class JdbcConnectionSource extends BaseJdbcConnectionSource implements ConnectionSource { 25 | 26 | private String username; 27 | private String password; 28 | private Integer loginTimeoutSecs; 29 | private Properties additionalProperties; 30 | 31 | /** 32 | * Constructor for Spring type wiring if you are using the set methods. If you are using Spring then your should 33 | * use: init-method="initialize" 34 | */ 35 | public JdbcConnectionSource() { 36 | // for spring type wiring 37 | } 38 | 39 | /** 40 | * Create a data source for a particular database URL. 41 | * 42 | * @param url 43 | * The database URL which should start jdbc:... 44 | * @throws SQLException 45 | * If the driver associated with the database driver is not found in the classpath. 46 | */ 47 | public JdbcConnectionSource(String url) throws SQLException { 48 | this(url, null, null, null); 49 | } 50 | 51 | /** 52 | * Create a data source for a particular database URL. The databaseType is usually determined from the databaseUrl 53 | * so most users should call {@link #JdbcConnectionSource(String)} instead. If, however, you need to force the class 54 | * to use a specific DatabaseType then this constructor should be used. 55 | * 56 | * @param url 57 | * The database URL which should start jdbc:... 58 | * @param databaseType 59 | * Database to associate with this connection source. 60 | * @throws SQLException 61 | * If the driver associated with the database driver is not found in the classpath. 62 | */ 63 | public JdbcConnectionSource(String url, DatabaseType databaseType) throws SQLException { 64 | this(url, null, null, databaseType); 65 | } 66 | 67 | /** 68 | * Create a data source for a particular database URL with username and password permissions. 69 | * 70 | * @param url 71 | * The database URL which should start jdbc:... 72 | * @param username 73 | * Username for permissions on the database. 74 | * @param password 75 | * Password for permissions on the database. 76 | * @throws SQLException 77 | * If the driver associated with the database driver is not found in the classpath. 78 | */ 79 | public JdbcConnectionSource(String url, String username, String password) throws SQLException { 80 | this(url, username, password, null); 81 | } 82 | 83 | /** 84 | * Create a data source for a particular database URL with username and password permissions. The databaseType is 85 | * usually determined from the databaseUrl so most users should call 86 | * {@link #JdbcConnectionSource(String, String, String)} instead. If, however, you need to force the class to use a 87 | * specific DatabaseType then this constructor should be used. 88 | * 89 | * @param url 90 | * The database URL which should start jdbc:... 91 | * @param username 92 | * Username for permissions on the database. 93 | * @param password 94 | * Password for permissions on the database. 95 | * @param databaseType 96 | * Database to associate with this connection source. 97 | * @throws SQLException 98 | * If the driver associated with the database driver is not found in the classpath. 99 | */ 100 | public JdbcConnectionSource(String url, String username, String password, DatabaseType databaseType) 101 | throws SQLException { 102 | super(url, databaseType, false); 103 | this.username = username; 104 | this.password = password; 105 | initialize(); 106 | } 107 | 108 | // not required 109 | public void setUsername(String username) { 110 | this.username = username; 111 | } 112 | 113 | // not required 114 | public void setPassword(String password) { 115 | this.password = password; 116 | } 117 | 118 | /** 119 | * Set additional properties to pass to DriverManager#getConnection method. 120 | */ 121 | public void setAdditionalProperties(Properties props) { 122 | this.additionalProperties = props; 123 | } 124 | 125 | /** 126 | * Set the connection timeout number of seconds. 127 | * 128 | * NOTE: this is very database dependent and certain database drivers may not obey it. I recommend using a real 129 | * database connection pool if you need strict controls over this. 130 | */ 131 | public void setLoginTimeoutSecs(Integer loginTimeoutSecs) { 132 | this.loginTimeoutSecs = loginTimeoutSecs; 133 | } 134 | 135 | @Override 136 | protected DatabaseConnection makeConnection(Logger logger) throws SQLException { 137 | Properties properties = new Properties(); 138 | if (username != null) { 139 | properties.setProperty("user", username); 140 | } 141 | if (password != null) { 142 | properties.setProperty("password", password); 143 | } 144 | if (loginTimeoutSecs != null) { 145 | DriverManager.setLoginTimeout(loginTimeoutSecs); 146 | } 147 | if (additionalProperties != null) { 148 | properties.putAll(additionalProperties); 149 | } 150 | DatabaseConnection connection = new JdbcDatabaseConnection(DriverManager.getConnection(url, properties)); 151 | // by default auto-commit is set to true 152 | connection.setAutoCommit(true); 153 | logger.debug("opened connection to {} got #{}", url, connection.hashCode()); 154 | return connection; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/JdbcDatabaseResults.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.io.InputStream; 4 | import java.math.BigDecimal; 5 | import java.sql.Blob; 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.sql.ResultSetMetaData; 9 | import java.sql.SQLException; 10 | import java.sql.Timestamp; 11 | 12 | import com.j256.ormlite.dao.ObjectCache; 13 | import com.j256.ormlite.misc.IOUtils; 14 | import com.j256.ormlite.support.DatabaseResults; 15 | 16 | /** 17 | * Wrapper around a {@link ResultSet} object which we delegate to. 18 | * 19 | * @author graywatson 20 | */ 21 | public class JdbcDatabaseResults implements DatabaseResults { 22 | 23 | private final PreparedStatement preparedStmt; 24 | private final ResultSet resultSet; 25 | private final ResultSetMetaData metaData; 26 | private final ObjectCache objectCache; 27 | private final boolean cacheStore; 28 | private boolean first = true; 29 | 30 | public JdbcDatabaseResults(PreparedStatement preparedStmt, ResultSet resultSet, ObjectCache objectCache, 31 | boolean cacheStore) throws SQLException { 32 | this.preparedStmt = preparedStmt; 33 | this.resultSet = resultSet; 34 | this.metaData = resultSet.getMetaData(); 35 | this.objectCache = objectCache; 36 | this.cacheStore = cacheStore; 37 | } 38 | 39 | @Override 40 | public int getColumnCount() throws SQLException { 41 | return metaData.getColumnCount(); 42 | } 43 | 44 | @Override 45 | public String[] getColumnNames() throws SQLException { 46 | int colN = metaData.getColumnCount(); 47 | String[] columnNames = new String[colN]; 48 | for (int colC = 0; colC < colN; colC++) { 49 | columnNames[colC] = metaData.getColumnLabel(colC + 1); 50 | } 51 | return columnNames; 52 | } 53 | 54 | @Override 55 | public boolean first() throws SQLException { 56 | if (first) { 57 | /* 58 | * We have to do this because some databases do not like us calling first() if we are only moving forward 59 | * through the results. We do this here because Android has no such issues. 60 | */ 61 | first = false; 62 | return next(); 63 | } else { 64 | return resultSet.first(); 65 | } 66 | } 67 | 68 | @Override 69 | public boolean next() throws SQLException { 70 | // NOTE: we should not auto-close here, even if there are no more results 71 | if (resultSet.next()) { 72 | return true; 73 | } else if (!preparedStmt.getMoreResults()) { 74 | return false; 75 | } else { 76 | return resultSet.next(); 77 | } 78 | } 79 | 80 | @Override 81 | public boolean last() throws SQLException { 82 | return resultSet.last(); 83 | } 84 | 85 | @Override 86 | public boolean previous() throws SQLException { 87 | return resultSet.previous(); 88 | } 89 | 90 | @Override 91 | public boolean moveRelative(int offset) throws SQLException { 92 | return resultSet.relative(offset); 93 | } 94 | 95 | @Override 96 | public boolean moveAbsolute(int position) throws SQLException { 97 | return resultSet.absolute(position); 98 | } 99 | 100 | @Override 101 | public int findColumn(String columnName) throws SQLException { 102 | return resultSet.findColumn(columnName) - 1; 103 | } 104 | 105 | @Override 106 | public InputStream getBlobStream(int columnIndex) throws SQLException { 107 | Blob blob = resultSet.getBlob(columnIndex + 1); 108 | if (blob == null) { 109 | return null; 110 | } else { 111 | return blob.getBinaryStream(); 112 | } 113 | } 114 | 115 | @Override 116 | public boolean getBoolean(int columnIndex) throws SQLException { 117 | return resultSet.getBoolean(columnIndex + 1); 118 | } 119 | 120 | @Override 121 | public char getChar(int columnIndex) throws SQLException { 122 | String string = resultSet.getString(columnIndex + 1); 123 | if (string == null || string.length() == 0) { 124 | return 0; 125 | } else if (string.length() == 1) { 126 | return string.charAt(0); 127 | } else { 128 | throw new SQLException("More than 1 character stored in database column: " + columnIndex); 129 | } 130 | } 131 | 132 | @Override 133 | public byte getByte(int columnIndex) throws SQLException { 134 | return resultSet.getByte(columnIndex + 1); 135 | } 136 | 137 | @Override 138 | public byte[] getBytes(int columnIndex) throws SQLException { 139 | return resultSet.getBytes(columnIndex + 1); 140 | } 141 | 142 | @Override 143 | public double getDouble(int columnIndex) throws SQLException { 144 | return resultSet.getDouble(columnIndex + 1); 145 | } 146 | 147 | @Override 148 | public float getFloat(int columnIndex) throws SQLException { 149 | return resultSet.getFloat(columnIndex + 1); 150 | } 151 | 152 | @Override 153 | public int getInt(int columnIndex) throws SQLException { 154 | return resultSet.getInt(columnIndex + 1); 155 | } 156 | 157 | @Override 158 | public long getLong(int columnIndex) throws SQLException { 159 | return resultSet.getLong(columnIndex + 1); 160 | } 161 | 162 | @Override 163 | public short getShort(int columnIndex) throws SQLException { 164 | return resultSet.getShort(columnIndex + 1); 165 | } 166 | 167 | @Override 168 | public String getString(int columnIndex) throws SQLException { 169 | return resultSet.getString(columnIndex + 1); 170 | } 171 | 172 | @Override 173 | public Timestamp getTimestamp(int columnIndex) throws SQLException { 174 | return resultSet.getTimestamp(columnIndex + 1); 175 | } 176 | 177 | @Override 178 | public BigDecimal getBigDecimal(int columnIndex) throws SQLException { 179 | return resultSet.getBigDecimal(columnIndex + 1); 180 | } 181 | 182 | @Override 183 | public Object getObject(int columnIndex) throws SQLException { 184 | return resultSet.getObject(columnIndex + 1); 185 | } 186 | 187 | @Override 188 | public boolean wasNull(int columnIndex) throws SQLException { 189 | return resultSet.wasNull(); 190 | } 191 | 192 | @Override 193 | public ObjectCache getObjectCacheForRetrieve() { 194 | return objectCache; 195 | } 196 | 197 | @Override 198 | public ObjectCache getObjectCacheForStore() { 199 | if (cacheStore) { 200 | return objectCache; 201 | } else { 202 | return null; 203 | } 204 | } 205 | 206 | @Override 207 | public void close() throws Exception { 208 | try { 209 | resultSet.close(); 210 | } catch (SQLException e) { 211 | throw new SQLException("could not close result set", e); 212 | } 213 | } 214 | 215 | @Override 216 | public void closeQuietly() { 217 | IOUtils.closeQuietly(this); 218 | } 219 | 220 | /** 221 | * Returns the underlying JDBC ResultSet object. 222 | */ 223 | public ResultSet getResultSet() { 224 | return resultSet; 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/JdbcSingleConnectionSource.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.sql.Connection; 4 | import java.sql.SQLException; 5 | 6 | import com.j256.ormlite.db.DatabaseType; 7 | import com.j256.ormlite.logger.Logger; 8 | import com.j256.ormlite.support.ConnectionSource; 9 | import com.j256.ormlite.support.DatabaseConnection; 10 | 11 | /** 12 | * A connection source that uses an existing open database connection. This is not thread-safe nor synchronized. For 13 | * other dataSources, see the {@link DataSourceConnectionSource} class. 14 | * 15 | *

16 | * NOTE: If you are using the Spring type wiring in Java, {@link #initialize} should be called after all of the 17 | * set methods. In Spring XML, init-method="initialize" should be used. 18 | *

19 | * 20 | * @author graywatson 21 | */ 22 | public class JdbcSingleConnectionSource extends BaseJdbcConnectionSource implements ConnectionSource { 23 | 24 | private Connection sqlConnection; 25 | 26 | /** 27 | * Constructor for Spring type wiring if you are using the set methods. If you are using Spring then your should 28 | * use: init-method="initialize" 29 | */ 30 | public JdbcSingleConnectionSource() { 31 | // for spring type wiring 32 | } 33 | 34 | /** 35 | * Create a data source for a particular database URL. 36 | * 37 | * @param url 38 | * The database URL which should start jdbc:... 39 | * @param sqlConnection 40 | * Already open database connection that we will use. 41 | * @throws SQLException 42 | * If the driver associated with the database driver is not found in the classpath. 43 | */ 44 | public JdbcSingleConnectionSource(String url, Connection sqlConnection) throws SQLException { 45 | this(url, null, sqlConnection); 46 | } 47 | 48 | /** 49 | * Create a data source for a particular database URL. The databaseType is usually determined from the databaseUrl 50 | * so most users should call {@link #JdbcSingleConnectionSource(String, Connection)} instead. If, however, you need 51 | * to force the class to use a specific DatabaseType then this constructor should be used. 52 | * 53 | * @param url 54 | * The database URL which should start jdbc:... 55 | * @param databaseType 56 | * Database to associate with this connection source. 57 | * @param sqlConnection 58 | * Already open database connection that we will use. 59 | * @throws SQLException 60 | * If the driver associated with the database driver is not found in the classpath. 61 | */ 62 | public JdbcSingleConnectionSource(String url, DatabaseType databaseType, Connection sqlConnection) 63 | throws SQLException { 64 | super(url, databaseType, false); 65 | this.sqlConnection = sqlConnection; 66 | initialize(); 67 | } 68 | 69 | @Override 70 | public void close() { 71 | // no-op because we don't want to close the connection 72 | } 73 | 74 | @Override 75 | public void closeQuietly() { 76 | // no-op because we don't want to close the connection 77 | } 78 | 79 | // required 80 | public void setSqlConnection(Connection sqlConnection) { 81 | this.sqlConnection = sqlConnection; 82 | } 83 | 84 | @Override 85 | protected DatabaseConnection makeConnection(Logger logger) { 86 | return new JdbcDatabaseConnection(sqlConnection); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/TypeValMapper.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.sql.SQLException; 4 | import java.sql.Types; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import com.j256.ormlite.field.SqlType; 9 | 10 | /** 11 | * Map from {@link SqlType} to the constants in the {@link Types} class. 12 | * 13 | * @author graywatson 14 | */ 15 | public class TypeValMapper { 16 | 17 | private static final Map typeToValMap = new HashMap(); 18 | 19 | static { 20 | for (SqlType sqlType : SqlType.values()) { 21 | int[] values; 22 | switch (sqlType) { 23 | case STRING: 24 | values = new int[] { Types.VARCHAR }; 25 | break; 26 | case LONG_STRING: 27 | values = new int[] { Types.LONGVARCHAR }; 28 | break; 29 | case DATE: 30 | values = new int[] { Types.TIMESTAMP }; 31 | break; 32 | case BOOLEAN: 33 | values = new int[] { Types.BOOLEAN }; 34 | break; 35 | case CHAR: 36 | values = new int[] { Types.CHAR }; 37 | break; 38 | case BYTE: 39 | values = new int[] { Types.TINYINT }; 40 | break; 41 | case BYTE_ARRAY: 42 | values = new int[] { Types.VARBINARY }; 43 | break; 44 | case SHORT: 45 | values = new int[] { Types.SMALLINT }; 46 | break; 47 | case INTEGER: 48 | values = new int[] { Types.INTEGER }; 49 | break; 50 | case LONG: 51 | values = new int[] { Types.BIGINT }; 52 | break; 53 | case FLOAT: 54 | values = new int[] { Types.FLOAT }; 55 | break; 56 | case DOUBLE: 57 | values = new int[] { Types.DOUBLE }; 58 | break; 59 | case SERIALIZABLE: 60 | values = new int[] { Types.VARBINARY }; 61 | break; 62 | case BLOB: 63 | // the following do not need to be handled except in specific situations 64 | values = new int[] { Types.BLOB }; 65 | break; 66 | case BIG_DECIMAL: 67 | values = new int[] { Types.DECIMAL, Types.NUMERIC }; 68 | break; 69 | case UUID: 70 | values = new int[] { Types.OTHER }; 71 | break; 72 | case OTHER: 73 | values = new int[] { Types.OTHER }; 74 | break; 75 | case UNKNOWN: 76 | values = new int[] {}; 77 | break; 78 | default: 79 | throw new IllegalArgumentException("No JDBC mapping for unknown SqlType " + sqlType); 80 | } 81 | typeToValMap.put(sqlType, values); 82 | } 83 | } 84 | 85 | /** 86 | * Returns the primary type value associated with the SqlType argument. 87 | */ 88 | public static int getTypeValForSqlType(SqlType sqlType) throws SQLException { 89 | int[] typeVals = typeToValMap.get(sqlType); 90 | if (typeVals == null) { 91 | throw new SQLException("SqlType is unknown to type val mapping: " + sqlType); 92 | } 93 | if (typeVals.length == 0) { 94 | throw new SQLException("SqlType does not have any JDBC type value mapping: " + sqlType); 95 | } else { 96 | return typeVals[0]; 97 | } 98 | } 99 | 100 | /** 101 | * Returns the SqlType value associated with the typeVal argument. Can be slow-er. 102 | */ 103 | public static SqlType getSqlTypeForTypeVal(int typeVal) { 104 | // iterate through to save on the extra HashMap since only for errors 105 | for (Map.Entry entry : typeToValMap.entrySet()) { 106 | for (int val : entry.getValue()) { 107 | if (val == typeVal) { 108 | return entry.getKey(); 109 | } 110 | } 111 | } 112 | return SqlType.UNKNOWN; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/DatabaseTypeUtils.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.j256.ormlite.db.DatabaseType; 7 | 8 | /** 9 | * Utility class which helps with managing database specific classes. 10 | * 11 | * @author graywatson 12 | */ 13 | public class DatabaseTypeUtils { 14 | 15 | private static List databaseTypes = new ArrayList(); 16 | 17 | static { 18 | // new drivers need to be added here 19 | databaseTypes.add(new Db2DatabaseType()); 20 | databaseTypes.add(new DerbyClientServerDatabaseType()); 21 | databaseTypes.add(new DerbyEmbeddedDatabaseType()); 22 | databaseTypes.add(new GenericOdbcDatabaseType()); 23 | databaseTypes.add(new H2DatabaseType()); 24 | databaseTypes.add(new HsqldbDatabaseType()); 25 | databaseTypes.add(new MysqlDatabaseType()); 26 | databaseTypes.add(new MariaDbDatabaseType()); 27 | databaseTypes.add(new NetezzaDatabaseType()); 28 | databaseTypes.add(new OracleDatabaseType()); 29 | databaseTypes.add(new PostgresDatabaseType()); 30 | databaseTypes.add(new SqliteDatabaseType()); 31 | databaseTypes.add(new SqlServerDatabaseType()); 32 | databaseTypes.add(new SqlServerJtdsDatabaseType()); 33 | } 34 | 35 | /** 36 | * For static methods only. 37 | */ 38 | private DatabaseTypeUtils() { 39 | } 40 | 41 | /** 42 | * Creates and returns a {@link DatabaseType} for the database URL. 43 | * 44 | * @throws IllegalArgumentException 45 | * if the url format is not recognized, the database type is unknown, or the class could not be 46 | * constructed. 47 | */ 48 | public static DatabaseType createDatabaseType(String databaseUrl) { 49 | String dbTypePart = extractDbType(databaseUrl); 50 | for (DatabaseType databaseType : databaseTypes) { 51 | if (databaseType.isDatabaseUrlThisType(databaseUrl, dbTypePart)) { 52 | return databaseType; 53 | } 54 | } 55 | throw new IllegalArgumentException("Unknown database-type url part '" + dbTypePart + "' in: " + databaseUrl); 56 | } 57 | 58 | private static String extractDbType(String databaseUrl) { 59 | if (!databaseUrl.startsWith("jdbc:")) { 60 | throw new IllegalArgumentException("Database URL was expected to start with jdbc: but was " + databaseUrl); 61 | } 62 | String[] urlParts = databaseUrl.split(":"); 63 | if (urlParts.length < 2) { 64 | throw new IllegalArgumentException( 65 | "Database URL was expected to be in the form: jdbc:db-type:... but was " + databaseUrl); 66 | } 67 | return urlParts[1]; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/Db2DatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.FieldType; 7 | 8 | /** 9 | * IBM DB2 database type information used to create the tables, etc.. 10 | * 11 | *

12 | * WARNING: I have not tested this unfortunately because of a lack of access to a DB2 instance. Love to get 1-2 13 | * hours of access to an database to test/tweak this. Undoubtably is it wrong. Please contact us if you'd like to help 14 | * with this class. 15 | *

16 | * 17 | * @author graywatson 18 | */ 19 | public class Db2DatabaseType extends BaseDatabaseType { 20 | 21 | private final static String DATABASE_URL_PORTION = "db2"; 22 | private final static String DATABASE_NAME = "DB2"; 23 | private final static String NEWER_DRIVER_CLASS_NAME = "com.ibm.db2.jcc.DB2Driver"; 24 | private final static String OLDER_DRIVER_CLASS_NAME = "COM.ibm.db2.jdbc.app.DB2Driver"; 25 | 26 | @Override 27 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 28 | return DATABASE_URL_PORTION.equals(dbTypePart); 29 | } 30 | 31 | @Override 32 | protected String[] getDriverClassNames() { 33 | return new String[] { NEWER_DRIVER_CLASS_NAME, OLDER_DRIVER_CLASS_NAME }; 34 | } 35 | 36 | @Override 37 | public String getDatabaseName() { 38 | return DATABASE_NAME; 39 | } 40 | 41 | @Override 42 | protected void appendBooleanType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 43 | sb.append("SMALLINT"); 44 | } 45 | 46 | @Override 47 | protected void appendByteType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 48 | sb.append("SMALLINT"); 49 | } 50 | 51 | @Override 52 | protected void appendByteArrayType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 53 | sb.append("VARCHAR [] FOR BIT DATA"); 54 | } 55 | 56 | @Override 57 | protected void appendSerializableType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 58 | sb.append("VARCHAR [] FOR BIT DATA"); 59 | } 60 | 61 | @Override 62 | protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType, 63 | List statementsBefore, List statementsAfter, List additionalArgs, 64 | List queriesAfter) { 65 | sb.append("GENERATED ALWAYS AS IDENTITY "); 66 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 67 | } 68 | 69 | @Override 70 | public void appendEscapedEntityName(StringBuilder sb, String name) { 71 | sb.append('\"').append(name).append('\"'); 72 | } 73 | 74 | @Override 75 | public boolean isOffsetSqlSupported() { 76 | // there is no easy way to do this in this database type 77 | return false; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/DerbyClientServerDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | /** 4 | * Derby database type information used to create the tables, etc.. This is for client connections to a remote Derby 5 | * server. For embedded databases, you should use {@link DerbyEmbeddedDatabaseType}. 6 | * 7 | * @author graywatson 8 | */ 9 | public class DerbyClientServerDatabaseType extends DerbyEmbeddedDatabaseType { 10 | 11 | private final static String DRIVER_CLASS_NAME = "org.apache.derby.jdbc.ClientDriver"; 12 | private final static String DATABASE_NAME = "Derby Client/Server"; 13 | 14 | @Override 15 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 16 | if (!DATABASE_URL_PORTION.equals(dbTypePart)) { 17 | return false; 18 | } 19 | // jdbc:derby://localhost:1527/MyDbTest;create=true'; 20 | String[] parts = url.split(":"); 21 | return (parts.length >= 3 && parts[2].startsWith("//")); 22 | } 23 | 24 | @Override 25 | protected String[] getDriverClassNames() { 26 | return new String[] { DRIVER_CLASS_NAME }; 27 | } 28 | 29 | @Override 30 | public String getDatabaseName() { 31 | return DATABASE_NAME; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/GenericOdbcDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import com.j256.ormlite.db.BaseDatabaseType; 4 | 5 | /** 6 | * Generic JdbcOdbcBridge database type information used to create the tables, etc.. 7 | * 8 | *

9 | * NOTE: This is the initial take on this database type. We hope to get access to an external database for 10 | * testing. Please contact us if you'd like to help with this class. 11 | *

12 | * 13 | * @author Dale Asberry 14 | */ 15 | public class GenericOdbcDatabaseType extends BaseDatabaseType { 16 | 17 | private final static String DATABASE_URL_PORTION = "odbc"; 18 | private final static String DRIVER_CLASS_NAME = "sun.jdbc.odbc.JdbcOdbcDriver"; 19 | private final static String DATABASE_NAME = "ODBC"; 20 | 21 | @Override 22 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 23 | return DATABASE_URL_PORTION.equals(dbTypePart); 24 | } 25 | 26 | @Override 27 | protected String[] getDriverClassNames() { 28 | return new String[] { DRIVER_CLASS_NAME }; 29 | } 30 | 31 | @Override 32 | public String getDatabaseName() { 33 | return DATABASE_NAME; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/H2DatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.FieldType; 7 | 8 | /** 9 | * H2 database type information used to create the tables, etc.. 10 | * 11 | * NOTE: if this is updated, the ormlite-core/src/test one should be as well. 12 | * 13 | * @author graywatson 14 | */ 15 | public class H2DatabaseType extends BaseDatabaseType { 16 | 17 | private final static String DATABASE_URL_PORTION = "h2"; 18 | private final static String DRIVER_CLASS_NAME = "org.h2.Driver"; 19 | private final static String DATABASE_NAME = "H2"; 20 | 21 | @Override 22 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 23 | return DATABASE_URL_PORTION.equals(dbTypePart); 24 | } 25 | 26 | @Override 27 | protected String[] getDriverClassNames() { 28 | return new String[] { DRIVER_CLASS_NAME }; 29 | } 30 | 31 | @Override 32 | public String getDatabaseName() { 33 | return DATABASE_NAME; 34 | } 35 | 36 | @Override 37 | protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType, 38 | List statementsBefore, List statementsAfter, List additionalArgs, 39 | List queriesAfter) { 40 | sb.append("AUTO_INCREMENT "); 41 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 42 | } 43 | 44 | @Override 45 | public void appendLimitValue(StringBuilder sb, long limit, Long offset) { 46 | sb.append("LIMIT "); 47 | if (offset != null) { 48 | sb.append(offset).append(','); 49 | } 50 | sb.append(limit).append(' '); 51 | } 52 | 53 | @Override 54 | public boolean isOffsetLimitArgument() { 55 | return true; 56 | } 57 | 58 | @Override 59 | public void appendOffsetValue(StringBuilder sb, long offset) { 60 | throw new IllegalStateException("Offset is part of the LIMIT in database type " + getClass()); 61 | } 62 | 63 | @Override 64 | public boolean isTruncateSupported() { 65 | return true; 66 | } 67 | 68 | @Override 69 | public boolean isCreateIfNotExistsSupported() { 70 | return true; 71 | } 72 | 73 | @Override 74 | public boolean isLimitUpdateAtEndSupported() { 75 | return true; 76 | } 77 | 78 | @Override 79 | public boolean isLimitDeleteAtEndSupported() { 80 | return true; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/HsqldbDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.FieldType; 7 | import com.j256.ormlite.field.SqlType; 8 | 9 | /** 10 | * HyberSQL database type information used to create the tables, etc.. 11 | * 12 | * @author graywatson 13 | */ 14 | public class HsqldbDatabaseType extends BaseDatabaseType { 15 | 16 | private final static String DATABASE_URL_PORTION = "hsqldb"; 17 | private final static String DRIVER_CLASS_NAME = "org.hsqldb.jdbcDriver"; 18 | private final static String DATABASE_NAME = "HSQLdb"; 19 | 20 | @Override 21 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 22 | return DATABASE_URL_PORTION.equals(dbTypePart); 23 | } 24 | 25 | @Override 26 | protected String[] getDriverClassNames() { 27 | return new String[] { DRIVER_CLASS_NAME }; 28 | } 29 | 30 | @Override 31 | public String getDatabaseName() { 32 | return DATABASE_NAME; 33 | } 34 | 35 | @Override 36 | protected void appendLongStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 37 | sb.append("LONGVARCHAR"); 38 | } 39 | 40 | @Override 41 | protected void appendBooleanType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 42 | sb.append("BIT"); 43 | } 44 | 45 | @Override 46 | protected void appendByteArrayType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 47 | // was: "BINARY" 48 | if (fieldWidth == 0) { 49 | sb.append("VARBINARY(255)"); 50 | } else { 51 | sb.append("VARBINARY(").append(fieldWidth).append(')'); 52 | } 53 | } 54 | 55 | @Override 56 | protected void appendSerializableType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 57 | appendByteArrayType(sb, fieldType, fieldWidth); 58 | } 59 | 60 | @Override 61 | protected void configureGeneratedIdSequence(StringBuilder sb, FieldType fieldType, List statementsBefore, 62 | List additionalArgs, List queriesAfter) { 63 | // needs to match dropColumnArg() 64 | StringBuilder seqSb = new StringBuilder(128); 65 | seqSb.append("CREATE SEQUENCE "); 66 | appendEscapedEntityName(seqSb, fieldType.getGeneratedIdSequence()); 67 | if (fieldType.getSqlType() == SqlType.LONG) { 68 | seqSb.append(" AS BIGINT"); 69 | } else { 70 | // integer is the default 71 | } 72 | // with hsqldb (as opposed to all else) the sequences start at 0, grumble 73 | seqSb.append(" START WITH 1"); 74 | statementsBefore.add(seqSb.toString()); 75 | sb.append("GENERATED BY DEFAULT AS IDENTITY "); 76 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 77 | } 78 | 79 | @Override 80 | public void appendEscapedEntityName(StringBuilder sb, String name) { 81 | sb.append('\"').append(name).append('\"'); 82 | } 83 | 84 | @Override 85 | public void dropColumnArg(FieldType fieldType, List statementsBefore, List statementsAfter) { 86 | if (fieldType.isGeneratedIdSequence()) { 87 | StringBuilder sb = new StringBuilder(64); 88 | sb.append("DROP SEQUENCE "); 89 | appendEscapedEntityName(sb, fieldType.getGeneratedIdSequence()); 90 | statementsAfter.add(sb.toString()); 91 | } 92 | } 93 | 94 | @Override 95 | public boolean isIdSequenceNeeded() { 96 | return true; 97 | } 98 | 99 | @Override 100 | public boolean isSelectSequenceBeforeInsert() { 101 | return true; 102 | } 103 | 104 | @Override 105 | public boolean isVarcharFieldWidthSupported() { 106 | /** 107 | * In version 2.X, VARCHAR(width) is required. In 1.8.X or before, it is not supported. Wonderful. 108 | */ 109 | if (driver != null && driver.getMajorVersion() >= 2) { 110 | return true; 111 | } else { 112 | return false; 113 | } 114 | } 115 | 116 | @Override 117 | public boolean isLimitAfterSelect() { 118 | return true; 119 | } 120 | 121 | @Override 122 | public void appendLimitValue(StringBuilder sb, long limit, Long offset) { 123 | // the 0 is the offset, could also use TOP X 124 | sb.append("LIMIT "); 125 | if (offset == null) { 126 | sb.append("0 "); 127 | } else { 128 | sb.append(offset).append(' '); 129 | } 130 | sb.append(limit).append(' '); 131 | } 132 | 133 | @Override 134 | public boolean isOffsetLimitArgument() { 135 | return true; 136 | } 137 | 138 | @Override 139 | public void appendOffsetValue(StringBuilder sb, long offset) { 140 | throw new IllegalStateException("Offset is part of the LIMIT in database type " + getClass()); 141 | } 142 | 143 | @Override 144 | public void appendSelectNextValFromSequence(StringBuilder sb, String sequenceName) { 145 | sb.append("CALL NEXT VALUE FOR "); 146 | appendEscapedEntityName(sb, sequenceName); 147 | } 148 | 149 | @Override 150 | public boolean isEntityNamesMustBeUpCase() { 151 | return true; 152 | } 153 | 154 | @Override 155 | public String getPingStatement() { 156 | return "SELECT COUNT(*) FROM INFORMATION_SCHEMA.SYSTEM_TABLES"; 157 | } 158 | 159 | @Override 160 | public boolean isCreateIfNotExistsSupported() { 161 | // support for EXISTS subquery was added in 2.3.x, thanks to @lukewhitt 162 | return (driver != null && driver.getMajorVersion() >= 2 && driver.getMinorVersion() >= 3); 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/MariaDbDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import com.j256.ormlite.field.DataPersister; 4 | import com.j256.ormlite.field.FieldConverter; 5 | import com.j256.ormlite.field.FieldType; 6 | import com.j256.ormlite.field.SqlType; 7 | import com.j256.ormlite.field.converter.CharacterCompatFieldConverter; 8 | 9 | /** 10 | * MariaDB database type information used to create the tables, etc.. It is an extension of MySQL. 11 | * 12 | * @author kratorius 13 | */ 14 | public class MariaDbDatabaseType extends MysqlDatabaseType { 15 | 16 | private final static String DATABASE_URL_PORTION = "mariadb"; 17 | private final static String DRIVER_CLASS_NAME = "org.mariadb.jdbc.Driver"; 18 | private final static String DATABASE_NAME = "MariaDB"; 19 | 20 | @Override 21 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 22 | return DATABASE_URL_PORTION.equals(dbTypePart); 23 | } 24 | 25 | @Override 26 | protected String[] getDriverClassNames() { 27 | return new String[] { DRIVER_CLASS_NAME }; 28 | } 29 | 30 | @Override 31 | public String getDatabaseName() { 32 | return DATABASE_NAME; 33 | } 34 | 35 | @Override 36 | protected void appendByteArrayType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 37 | super.appendByteArrayType(sb, fieldType, fieldWidth); 38 | } 39 | 40 | @Override 41 | protected void appendLongStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 42 | super.appendLongStringType(sb, fieldType, fieldWidth); 43 | } 44 | 45 | @Override 46 | public FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType) { 47 | if (dataPersister.getSqlType() == SqlType.CHAR) { 48 | return new CharacterCompatFieldConverter(dataPersister); 49 | } else { 50 | return super.getFieldConverter(dataPersister, fieldType); 51 | } 52 | } 53 | 54 | @Override 55 | public boolean isCreateIndexIfNotExistsSupported() { 56 | return true; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/MysqlDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.FieldType; 7 | 8 | /** 9 | * MySQL database type information used to create the tables, etc.. 10 | * 11 | *

12 | * NOTE: By default the tables are created with the ENGINE=InnoDB suffix (see 13 | * {@link #DEFAULT_CREATE_TABLE_SUFFIX}. Use {@link #setCreateTableSuffix} to change that to "" to use the default 14 | * MyISAM storage engine, to choose another engine, or set other settings. For more information about engines, see the 15 | * 'SHOW ENGINES;' results from the MySQL command line tool. 16 | *

17 | * 18 | * @author graywatson 19 | */ 20 | public class MysqlDatabaseType extends BaseDatabaseType { 21 | 22 | private final static String DATABASE_URL_PORTION = "mysql"; 23 | private final static String DRIVER_CLASS_NAME_OLD = "com.mysql.jdbc.Driver"; 24 | private final static String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; 25 | private final static String DATABASE_NAME = "MySQL"; 26 | 27 | /** 28 | * Default suffix to the CREATE TABLE statement. Change with the {@link #setCreateTableSuffix} method. 29 | */ 30 | public final static String DEFAULT_CREATE_TABLE_SUFFIX = "ENGINE=InnoDB"; 31 | 32 | private String createTableSuffix = DEFAULT_CREATE_TABLE_SUFFIX; 33 | 34 | @Override 35 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 36 | return DATABASE_URL_PORTION.equals(dbTypePart); 37 | } 38 | 39 | @Override 40 | protected String[] getDriverClassNames() { 41 | return new String[] { DRIVER_CLASS_NAME, DRIVER_CLASS_NAME_OLD }; 42 | } 43 | 44 | @Override 45 | public String getDatabaseName() { 46 | return DATABASE_NAME; 47 | } 48 | 49 | /** 50 | * Set the string that is appended to the end of a CREATE TABLE statement. 51 | */ 52 | public void setCreateTableSuffix(String createTableSuffix) { 53 | this.createTableSuffix = createTableSuffix; 54 | } 55 | 56 | @Override 57 | protected void appendDateType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 58 | /** 59 | * TIMESTAMP in MySQL does some funky stuff with the last-modification time. Values are 'not null' by default 60 | * with an automatic default of CURRENT_TIMESTAMP. Strange design decision. 61 | */ 62 | sb.append("DATETIME"); 63 | } 64 | 65 | @Override 66 | protected void appendBooleanType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 67 | sb.append("TINYINT(1)"); 68 | } 69 | 70 | @Override 71 | protected void configureGeneratedId(String tableName, StringBuilder sb, FieldType fieldType, 72 | List statementsBefore, List statementsAfter, List additionalArgs, 73 | List queriesAfter) { 74 | sb.append("AUTO_INCREMENT "); 75 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 76 | } 77 | 78 | @Override 79 | public void appendCreateTableSuffix(StringBuilder sb) { 80 | sb.append(createTableSuffix); 81 | sb.append(' '); 82 | } 83 | 84 | @Override 85 | public boolean isTruncateSupported() { 86 | return true; 87 | } 88 | 89 | @Override 90 | public boolean isCreateIfNotExistsSupported() { 91 | return true; 92 | } 93 | 94 | @Override 95 | public boolean isCreateIndexIfNotExistsSupported() { 96 | return false; 97 | } 98 | 99 | @Override 100 | public boolean isLimitUpdateAtEndSupported() { 101 | return true; 102 | } 103 | 104 | @Override 105 | public boolean isLimitDeleteAtEndSupported() { 106 | return super.isLimitDeleteAtEndSupported(); 107 | } 108 | 109 | @Override 110 | protected void appendByteArrayType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 111 | super.appendByteArrayType(sb, fieldType, fieldWidth); 112 | } 113 | 114 | @Override 115 | protected void appendLongStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 116 | super.appendLongStringType(sb, fieldType, fieldWidth); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/NetezzaDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.FieldType; 7 | 8 | /** 9 | * Netezza database type information used to create the tables, etc.. 10 | * 11 | *

12 | * NOTE: This is the initial take on this database type. We hope to get access to an external database for 13 | * testing. Please contact us if you'd like to help with this class. 14 | *

15 | * 16 | * @author Richard Kooijman 17 | */ 18 | public class NetezzaDatabaseType extends BaseDatabaseType { 19 | 20 | private final static String DATABASE_URL_PORTION = "netezza"; 21 | private final static String DRIVER_CLASS_NAME = "org.netezza.Driver"; 22 | private final static String DATABASE_NAME = "Netezza"; 23 | 24 | @Override 25 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 26 | return DATABASE_URL_PORTION.equals(dbTypePart); 27 | } 28 | 29 | @Override 30 | protected String[] getDriverClassNames() { 31 | return new String[] { DRIVER_CLASS_NAME }; 32 | } 33 | 34 | @Override 35 | public String getDatabaseName() { 36 | return DATABASE_NAME; 37 | } 38 | 39 | @Override 40 | protected void appendByteType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 41 | sb.append("BYTEINT"); 42 | } 43 | 44 | @Override 45 | protected void configureGeneratedIdSequence(StringBuilder sb, FieldType fieldType, List statementsBefore, 46 | List additionalArgs, List queriesAfter) { 47 | String sequenceName = fieldType.getGeneratedIdSequence(); 48 | // needs to match dropColumnArg() 49 | StringBuilder seqSb = new StringBuilder(64); 50 | seqSb.append("CREATE SEQUENCE "); 51 | // when it is created, it needs to be escaped specially 52 | appendEscapedEntityName(seqSb, sequenceName); 53 | statementsBefore.add(seqSb.toString()); 54 | 55 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 56 | } 57 | 58 | @Override 59 | public void dropColumnArg(FieldType fieldType, List statementsBefore, List statementsAfter) { 60 | if (fieldType.isGeneratedIdSequence()) { 61 | StringBuilder sb = new StringBuilder(64); 62 | sb.append("DROP SEQUENCE "); 63 | appendEscapedEntityName(sb, fieldType.getGeneratedIdSequence()); 64 | statementsAfter.add(sb.toString()); 65 | } 66 | } 67 | 68 | @Override 69 | public void appendEscapedEntityName(StringBuilder sb, String name) { 70 | sb.append('\"').append(name).append('\"'); 71 | } 72 | 73 | @Override 74 | public boolean isIdSequenceNeeded() { 75 | return true; 76 | } 77 | 78 | @Override 79 | public void appendSelectNextValFromSequence(StringBuilder sb, String sequenceName) { 80 | sb.append("SELECT NEXT VALUE FOR "); 81 | // this is word and not entity unfortunately 82 | appendEscapedWord(sb, sequenceName); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/OracleDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.DataPersister; 7 | import com.j256.ormlite.field.DataType; 8 | import com.j256.ormlite.field.FieldConverter; 9 | import com.j256.ormlite.field.FieldType; 10 | import com.j256.ormlite.field.converter.CharacterCompatFieldConverter; 11 | 12 | /** 13 | * Oracle database type information used to create the tables, etc.. 14 | * 15 | *

16 | * WARNING: I have not tested this unfortunately because of a lack of access to a Oracle instance. Love to get 17 | * 1-2 hours of access to an database to test/tweak this. Undoubtably is it wrong. Please contact Please contact us if 18 | * you'd like to help with this class. 19 | *

20 | * 21 | * @author graywatson 22 | */ 23 | public class OracleDatabaseType extends BaseDatabaseType { 24 | 25 | private final static String DATABASE_URL_PORTION = "oracle"; 26 | private final static String DRIVER_CLASS_NAME = "oracle.jdbc.driver.OracleDriver"; 27 | private final static String DATABASE_NAME = "Oracle"; 28 | private static final String BOOLEAN_INTEGER_FORMAT = "integer"; 29 | 30 | @Override 31 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 32 | return DATABASE_URL_PORTION.equals(dbTypePart); 33 | } 34 | 35 | @Override 36 | protected String[] getDriverClassNames() { 37 | return new String[] { DRIVER_CLASS_NAME }; 38 | } 39 | 40 | @Override 41 | public String getDatabaseName() { 42 | return DATABASE_NAME; 43 | } 44 | 45 | @Override 46 | protected void appendStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 47 | sb.append("VARCHAR2(").append(fieldWidth).append(')'); 48 | } 49 | 50 | @Override 51 | protected void appendLongStringType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 52 | sb.append("LONG"); 53 | } 54 | 55 | @Override 56 | protected void appendByteType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 57 | sb.append("SMALLINT"); 58 | } 59 | 60 | @Override 61 | protected void appendLongType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 62 | sb.append("NUMERIC"); 63 | } 64 | 65 | @Override 66 | protected void appendByteArrayType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 67 | sb.append("LONG RAW"); 68 | } 69 | 70 | @Override 71 | protected void appendSerializableType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 72 | sb.append("LONG RAW"); 73 | } 74 | 75 | @Override 76 | protected void appendBigDecimalNumericType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 77 | // from stew 78 | sb.append("NUMBER(*," + fieldWidth + ")"); 79 | } 80 | 81 | @Override 82 | protected void appendBooleanType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 83 | if (BOOLEAN_INTEGER_FORMAT.equalsIgnoreCase(fieldType.getFormat())) { 84 | sb.append("INTEGER"); 85 | } else { 86 | sb.append("CHAR(1)"); 87 | } 88 | } 89 | 90 | @Override 91 | public FieldConverter getFieldConverter(DataPersister dataPersister, FieldType fieldType) { 92 | switch (dataPersister.getSqlType()) { 93 | case BOOLEAN: 94 | /* 95 | * Booleans in Oracle are stored as the character '1' or '0'. You can change the characters by 96 | * specifying a format string. It must be a string with 2 characters. The first character is the value 97 | * for TRUE, the second is FALSE. See {@link BooleanCharType}. 98 | * 99 | * You can also specify the format as "integer" to use an integer column type and the value 1 (really 100 | * non-0) for true and 0 for false. See {@link BooleanIntegerType}. 101 | */ 102 | if (BOOLEAN_INTEGER_FORMAT.equalsIgnoreCase(fieldType.getFormat())) { 103 | return DataType.BOOLEAN_INTEGER.getDataPersister(); 104 | } else { 105 | return new CharacterCompatFieldConverter(DataType.BOOLEAN_CHAR.getDataPersister()); 106 | } 107 | case CHAR: 108 | return new CharacterCompatFieldConverter(dataPersister); 109 | default: 110 | return super.getFieldConverter(dataPersister, fieldType); 111 | } 112 | } 113 | 114 | @Override 115 | protected void configureGeneratedIdSequence(StringBuilder sb, FieldType fieldType, List statementsBefore, 116 | List additionalArgs, List queriesAfter) { 117 | String seqName = fieldType.getGeneratedIdSequence(); 118 | // needs to match dropColumnArg() 119 | StringBuilder seqSb = new StringBuilder(64); 120 | seqSb.append("CREATE SEQUENCE "); 121 | // when it is created, it needs to be escaped specially 122 | appendEscapedEntityName(seqSb, seqName); 123 | statementsBefore.add(seqSb.toString()); 124 | 125 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 126 | } 127 | 128 | @Override 129 | protected void configureId(StringBuilder sb, FieldType fieldType, List statementsBefore, 130 | List additionalArgs, List queriesAfter) { 131 | // no PRIMARY KEY per stew 132 | } 133 | 134 | @Override 135 | public void dropColumnArg(FieldType fieldType, List statementsBefore, List statementsAfter) { 136 | if (fieldType.isGeneratedIdSequence()) { 137 | StringBuilder sb = new StringBuilder(64); 138 | sb.append("DROP SEQUENCE "); 139 | appendEscapedEntityName(sb, fieldType.getGeneratedIdSequence()); 140 | statementsAfter.add(sb.toString()); 141 | } 142 | } 143 | 144 | @Override 145 | public void appendEscapedEntityName(StringBuilder sb, String name) { 146 | sb.append('\"').append(name).append('\"'); 147 | } 148 | 149 | @Override 150 | public boolean isIdSequenceNeeded() { 151 | return true; 152 | } 153 | 154 | @Override 155 | public void appendSelectNextValFromSequence(StringBuilder sb, String sequenceName) { 156 | sb.append("SELECT "); 157 | // this may not work -- may need to have no escape 158 | appendEscapedEntityName(sb, sequenceName); 159 | // dual is some sort of special internal table I think 160 | sb.append(".nextval FROM dual"); 161 | } 162 | 163 | @Override 164 | public String getPingStatement() { 165 | return "SELECT 1 FROM DUAL"; 166 | } 167 | 168 | @Override 169 | public boolean isOffsetSqlSupported() { 170 | // there is no easy way to do this in this database type 171 | return false; 172 | } 173 | 174 | @Override 175 | public boolean isBatchUseTransaction() { 176 | // from stew 177 | return true; 178 | } 179 | 180 | @Override 181 | public boolean isSelectSequenceBeforeInsert() { 182 | // from stew 183 | return true; 184 | } 185 | 186 | @Override 187 | public boolean isEntityNamesMustBeUpCase() { 188 | // from stew 189 | return true; 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/PostgresDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.util.List; 4 | 5 | import com.j256.ormlite.db.BaseDatabaseType; 6 | import com.j256.ormlite.field.FieldType; 7 | 8 | /** 9 | * Postgres database type information used to create the tables, etc.. 10 | * 11 | * @author graywatson 12 | */ 13 | public class PostgresDatabaseType extends BaseDatabaseType { 14 | 15 | private final static String DATABASE_URL_PORTION = "postgresql"; 16 | private final static String DRIVER_CLASS_NAME = "org.postgresql.Driver"; 17 | private final static String DATABASE_NAME = "Postgres"; 18 | 19 | @Override 20 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 21 | return DATABASE_URL_PORTION.equals(dbTypePart); 22 | } 23 | 24 | @Override 25 | protected String[] getDriverClassNames() { 26 | return new String[] { DRIVER_CLASS_NAME }; 27 | } 28 | 29 | @Override 30 | public String getDatabaseName() { 31 | return DATABASE_NAME; 32 | } 33 | 34 | @Override 35 | protected void appendUuidNativeType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 36 | sb.append("UUID"); 37 | } 38 | 39 | @Override 40 | protected void appendByteType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 41 | sb.append("SMALLINT"); 42 | } 43 | 44 | @Override 45 | protected void appendByteArrayType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 46 | sb.append("BYTEA"); 47 | } 48 | 49 | @Override 50 | protected void appendSerializableType(StringBuilder sb, FieldType fieldType, int fieldWidth) { 51 | sb.append("BYTEA"); 52 | } 53 | 54 | @Override 55 | protected void configureGeneratedIdSequence(StringBuilder sb, FieldType fieldType, List statementsBefore, 56 | List additionalArgs, List queriesAfter) { 57 | String sequenceName = fieldType.getGeneratedIdSequence(); 58 | // needs to match dropColumnArg() 59 | StringBuilder seqSb = new StringBuilder(64); 60 | seqSb.append("CREATE SEQUENCE "); 61 | // when it is created, it needs to be escaped specially 62 | appendEscapedEntityName(seqSb, sequenceName); 63 | statementsBefore.add(seqSb.toString()); 64 | 65 | sb.append("DEFAULT NEXTVAL("); 66 | // postgres needed this special escaping for NEXTVAL('"sequence-name"') 67 | sb.append('\'').append('\"').append(sequenceName).append('\"').append('\''); 68 | sb.append(") "); 69 | // could also be the type serial for auto-generated sequences 70 | // 8.2 also have the returning insert statement 71 | 72 | configureId(sb, fieldType, statementsBefore, additionalArgs, queriesAfter); 73 | } 74 | 75 | @Override 76 | public void dropColumnArg(FieldType fieldType, List statementsBefore, List statementsAfter) { 77 | if (fieldType.isGeneratedIdSequence()) { 78 | StringBuilder sb = new StringBuilder(64); 79 | sb.append("DROP SEQUENCE "); 80 | appendEscapedEntityName(sb, fieldType.getGeneratedIdSequence()); 81 | statementsAfter.add(sb.toString()); 82 | } 83 | } 84 | 85 | @Override 86 | public void appendEscapedEntityName(StringBuilder sb, String name) { 87 | // this handles table names like schema.table which have to be quoted like "schema"."table" 88 | boolean first = true; 89 | for (String namePart : name.split("\\.")) { 90 | if (first) { 91 | first = false; 92 | } else { 93 | sb.append('.'); 94 | } 95 | sb.append('\"').append(namePart).append('\"'); 96 | } 97 | } 98 | 99 | @Override 100 | public boolean isIdSequenceNeeded() { 101 | return true; 102 | } 103 | 104 | @Override 105 | public boolean isSelectSequenceBeforeInsert() { 106 | return true; 107 | } 108 | 109 | @Override 110 | public void appendSelectNextValFromSequence(StringBuilder sb, String sequenceName) { 111 | sb.append("SELECT NEXTVAL("); 112 | // this is word and not entity unfortunately 113 | appendEscapedWord(sb, sequenceName); 114 | sb.append(')'); 115 | } 116 | 117 | @Override 118 | public boolean isTruncateSupported() { 119 | return true; 120 | } 121 | 122 | @Override 123 | public boolean isCreateIfNotExistsSupported() { 124 | int major = driver.getMajorVersion(); 125 | if (major > 9 || (major == 9 && driver.getMinorVersion() >= 1)) { 126 | return true; 127 | } else { 128 | return super.isCreateIfNotExistsSupported(); 129 | } 130 | } 131 | 132 | @Override 133 | public boolean isSequenceNamesMustBeLowerCase() { 134 | return true; 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/SqlServerJtdsDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | /** 4 | * Microsoft SQL server database type information connected through the JTDS JDBC driver. 5 | * 6 | *

7 | * NOTE: Currently with 1.2.4 version of the jTDS package, I'm seeing problems with Java 1.5 because jTDS is 8 | * using a java.sql 1.6 class. 9 | *

10 | * 11 | *

12 | * See JTDS home page for more information. To use this driver, you need to 13 | * specify the database URL as something like the following. See the URL for more information. 14 | *

15 | * 16 | *

17 | *

jdbc:jtds:sqlserver://host-name:host-port/database-name
18 | *

19 | * 20 | * @author graywatson 21 | */ 22 | public class SqlServerJtdsDatabaseType extends SqlServerDatabaseType { 23 | 24 | private final static String DATABASE_URL_PORTION = "jtds"; 25 | private final static String DRIVER_CLASS_NAME = "net.sourceforge.jtds.jdbc.Driver"; 26 | private final static String DATABASE_NAME = "SQL Server JTDS"; 27 | 28 | @Override 29 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 30 | return DATABASE_URL_PORTION.equals(dbTypePart); 31 | } 32 | 33 | @Override 34 | protected String[] getDriverClassNames() { 35 | return new String[] { DRIVER_CLASS_NAME }; 36 | } 37 | 38 | @Override 39 | public String getDatabaseName() { 40 | return DATABASE_NAME; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/db/SqliteDatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import com.j256.ormlite.db.BaseSqliteDatabaseType; 4 | 5 | /** 6 | * Sqlite database type information used to create the tables, etc.. 7 | * 8 | * @author graywatson 9 | */ 10 | public class SqliteDatabaseType extends BaseSqliteDatabaseType { 11 | 12 | private final static String DATABASE_URL_PORTION = "sqlite"; 13 | private final static String DRIVER_CLASS_NAME = "org.sqlite.JDBC"; 14 | private final static String DATABASE_NAME = "SQLite"; 15 | 16 | public SqliteDatabaseType() { 17 | } 18 | 19 | @Override 20 | public boolean isDatabaseUrlThisType(String url, String dbTypePart) { 21 | return DATABASE_URL_PORTION.equals(dbTypePart); 22 | } 23 | 24 | @Override 25 | protected String[] getDriverClassNames() { 26 | return new String[] { DRIVER_CLASS_NAME }; 27 | } 28 | 29 | @Override 30 | public String getDatabaseName() { 31 | return DATABASE_NAME; 32 | } 33 | 34 | @Override 35 | public void appendLimitValue(StringBuilder sb, long limit, Long offset) { 36 | sb.append("LIMIT "); 37 | if (offset != null) { 38 | sb.append(offset).append(','); 39 | } 40 | sb.append(limit).append(' '); 41 | } 42 | 43 | @Override 44 | public boolean isOffsetLimitArgument() { 45 | return true; 46 | } 47 | 48 | @Override 49 | public boolean isNestedSavePointsSupported() { 50 | return false; 51 | } 52 | 53 | @Override 54 | public void appendOffsetValue(StringBuilder sb, long offset) { 55 | throw new IllegalStateException("Offset is part of the LIMIT in database type " + getClass()); 56 | } 57 | 58 | @Override 59 | public boolean isLimitUpdateAtEndSupported() { 60 | return true; 61 | } 62 | 63 | @Override 64 | public boolean isLimitDeleteAtEndSupported() { 65 | return true; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/spring/DaoFactory.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.spring; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.j256.ormlite.dao.Dao; 6 | import com.j256.ormlite.dao.DaoManager; 7 | import com.j256.ormlite.support.ConnectionSource; 8 | import com.j256.ormlite.table.DatabaseTableConfig; 9 | 10 | /** 11 | *

12 | * Spring bean that can be used to create Dao's of certain classes without needing their own Dao class. 13 | *

14 | * 15 | *

16 | * Here is an example of spring wiring. See the Spring example in the documentation for more info. 17 | *

18 | * 19 | *
20 |  * 	<bean id="accountDao" class="com.j256.ormlite.spring.DaoFactory" factory-method="createDao">
21 |  * 		<constructor-arg index="0" ref="connectionSource" />
22 |  * 		<constructor-arg index="1" value="com.j256.ormlite.examples.spring.Account" />
23 |  * 	</bean>
24 |  * 
25 | * 26 | * @author graywatson 27 | */ 28 | public class DaoFactory { 29 | 30 | /** 31 | * Create and return a Dao based on the arguments. 32 | */ 33 | public static Dao createDao(ConnectionSource connectionSource, Class clazz) throws SQLException { 34 | return DaoManager.createDao(connectionSource, clazz); 35 | } 36 | 37 | /** 38 | * Create and return a Dao based on the arguments. 39 | */ 40 | public static Dao createDao(ConnectionSource connectionSource, DatabaseTableConfig tableConfig) 41 | throws SQLException { 42 | return DaoManager.createDao(connectionSource, tableConfig); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/j256/ormlite/jdbc/spring/TableCreator.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.spring; 2 | 3 | import java.sql.SQLException; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | import com.j256.ormlite.dao.BaseDaoImpl; 9 | import com.j256.ormlite.dao.Dao; 10 | import com.j256.ormlite.support.ConnectionSource; 11 | import com.j256.ormlite.table.DatabaseTableConfig; 12 | import com.j256.ormlite.table.TableUtils; 13 | 14 | /** 15 | * Spring bean that auto-creates any tables that it finds DAOs for if the property name in 16 | * TableCreator.AUTO_CREATE_TABLES property has been set to true. It will also auto-drop any tables that were 17 | * auto-created if the property name in TableCreator.AUTO_DROP_TABLES property has been set to true. 18 | * 19 | *

20 | * NOTE: If you are using the Spring type wiring in Java, {@link #initialize} should be called after all of the 21 | * set methods. In Spring XML, init-method="initialize" should be used. 22 | *

23 | * 24 | *

25 | * Here is an example of spring wiring. 26 | *

27 | * 28 | *
 29 |  * <!-- our database type factory-bean -->
 30 |  * <bean id="tableCreator" class="com.j256.ormlite.spring.TableCreator" init-method="initialize">
 31 |  * 	<property name="connectionSource" ref="connectionSource" />
 32 |  * 	<property name="configuredDaos">
 33 |  * 		<list>
 34 |  * 			<ref bean="accountDao" />
 35 |  * 			<ref bean="orderDao" />
 36 |  * 		</list>
 37 |  * 	</property>
 38 |  * </bean>
 39 |  * 
40 | * 41 | * @author graywatson 42 | */ 43 | public class TableCreator { 44 | 45 | public final static String AUTO_CREATE_TABLES = "ormlite.auto.create.tables"; 46 | public final static String AUTO_DROP_TABLES = "ormlite.auto.drop.tables"; 47 | 48 | private ConnectionSource connectionSource; 49 | private List> configuredDaos; 50 | private Set> createdClasses = new HashSet>(); 51 | 52 | public TableCreator() { 53 | // for spring 54 | } 55 | 56 | public TableCreator(ConnectionSource connectionSource, List> configuredDaos) { 57 | this.connectionSource = connectionSource; 58 | this.configuredDaos = configuredDaos; 59 | } 60 | 61 | /** 62 | * Possibly create the tables is the {@link #AUTO_CREATE_TABLES} system property is set to "true". 63 | */ 64 | public void maybeCreateTables() throws SQLException { 65 | initialize(); 66 | } 67 | 68 | /** 69 | * If you are using the Spring type wiring, this should be called after all of the set methods. 70 | */ 71 | public void initialize() throws SQLException { 72 | if (!Boolean.parseBoolean(System.getProperty(AUTO_CREATE_TABLES))) { 73 | return; 74 | } 75 | 76 | if (configuredDaos == null) { 77 | throw new SQLException("configuredDaos was not set in " + getClass().getSimpleName()); 78 | } 79 | 80 | // find all of the daos and create the tables 81 | for (Dao dao : configuredDaos) { 82 | Class clazz = dao.getDataClass(); 83 | try { 84 | DatabaseTableConfig tableConfig = null; 85 | if (dao instanceof BaseDaoImpl) { 86 | tableConfig = ((BaseDaoImpl) dao).getTableConfig(); 87 | } 88 | if (tableConfig == null) { 89 | tableConfig = DatabaseTableConfig.fromClass(connectionSource.getDatabaseType(), clazz); 90 | } 91 | TableUtils.createTable(connectionSource, tableConfig); 92 | createdClasses.add(tableConfig); 93 | } catch (Exception e) { 94 | // we don't stop because the table might already exist 95 | System.err.println("Was unable to auto-create table for " + clazz); 96 | e.printStackTrace(); 97 | } 98 | } 99 | } 100 | 101 | /** 102 | * Possibly drop the tables that were previously created if the {@link #AUTO_DROP_TABLES} system property is set to 103 | * "true". 104 | */ 105 | public void maybeDropTables() { 106 | destroy(); 107 | } 108 | 109 | public void destroy() { 110 | if (!Boolean.parseBoolean(System.getProperty(AUTO_DROP_TABLES))) { 111 | return; 112 | } 113 | for (DatabaseTableConfig tableConfig : createdClasses) { 114 | try { 115 | TableUtils.dropTable(connectionSource, tableConfig, false); 116 | } catch (Exception e) { 117 | // we don't stop because the table might already exist 118 | System.err.println("Was unable to auto-drop table for " + tableConfig.getDataClass()); 119 | e.printStackTrace(); 120 | } 121 | } 122 | createdClasses.clear(); 123 | } 124 | 125 | // This is @Required 126 | public void setConnectionSource(ConnectionSource dataSource) { 127 | this.connectionSource = dataSource; 128 | } 129 | 130 | public void setConfiguredDaos(List> configuredDaos) { 131 | this.configuredDaos = configuredDaos; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/main/javadoc/com/j256/ormlite/db/package.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

Classes to support the JDBC database types.

6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/main/javadoc/com/j256/ormlite/jdbc/package.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

JDBC database connection and results classes.

6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/main/javadoc/com/j256/ormlite/spring/package.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

Utility classes to support Spring configurations.

6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/main/javadoc/overview.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ORM Lite Package Overview 5 | 6 | 7 | 8 |

9 | This package provides the JDBC support for a lightweight Object Relational Mapping between Java classes and 11 | SQL databases. See the ORMLite home page for more 12 | information. 13 |

14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/resources/com/j256/ormlite/jdbc/LICENSE.txt: -------------------------------------------------------------------------------- 1 | ISC License (https://opensource.org/licenses/ISC) 2 | 3 | Copyright 2010 to 2020, Gray Watson 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /src/main/resources/com/j256/ormlite/jdbc/README.txt: -------------------------------------------------------------------------------- 1 | This package provides the JDBC specific functionality. You will also need to download the 2 | ormlite-core package as well. Android users should download the ormlite-android package instead of 3 | this JDBC one. 4 | 5 | For more information, see the online documentation on the home page: 6 | 7 | http://ormlite.com/ 8 | 9 | Sources can be found online via Github: 10 | 11 | https://github.com/j256/ormlite-jdbc 12 | 13 | Enjoy, 14 | Gray Watson 15 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/BaseJdbcTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.InetAddress; 6 | import java.net.UnknownHostException; 7 | import java.sql.SQLException; 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | 11 | import org.junit.jupiter.api.AfterEach; 12 | import org.junit.jupiter.api.BeforeEach; 13 | 14 | import com.j256.ormlite.dao.BaseDaoImpl; 15 | import com.j256.ormlite.dao.Dao; 16 | import com.j256.ormlite.dao.DaoManager; 17 | import com.j256.ormlite.db.DatabaseType; 18 | import com.j256.ormlite.table.DatabaseTableConfig; 19 | import com.j256.ormlite.table.TableUtils; 20 | 21 | public abstract class BaseJdbcTest { 22 | 23 | private static final String DATASOURCE_ERROR = "Property 'dataSource' is required"; 24 | 25 | protected static final String DEFAULT_DATABASE_URL = "jdbc:h2:mem:ormlite"; 26 | 27 | protected String databaseHost = null; 28 | protected String databaseUrl = DEFAULT_DATABASE_URL; 29 | protected String userName = null; 30 | protected String password = null; 31 | 32 | protected JdbcConnectionSource connectionSource = null; 33 | protected boolean isConnectionExpected = false; 34 | protected DatabaseType databaseType = null; 35 | 36 | private Set> dropClassSet = new HashSet>(); 37 | private Set> dropTableConfigSet = new HashSet>(); 38 | 39 | @BeforeEach 40 | public void before() throws Exception { 41 | DaoManager.clearCache(); 42 | if (connectionSource != null) { 43 | return; 44 | } 45 | // do this for everyone 46 | System.setProperty("derby.stream.error.file", "target/derby.log"); 47 | setDatabaseParams(); 48 | doOpenConnectionSource(); 49 | } 50 | 51 | protected void openConnectionSource() throws Exception { 52 | if (connectionSource == null) { 53 | doOpenConnectionSource(); 54 | } 55 | } 56 | 57 | /** 58 | * Set the database parameters for this db type. 59 | * 60 | * @throws SQLException 61 | * For sub classes 62 | */ 63 | protected void setDatabaseParams() throws SQLException { 64 | // noop here -- designed to be overridden 65 | } 66 | 67 | @AfterEach 68 | public void after() throws Exception { 69 | if (connectionSource != null) { 70 | for (Class clazz : dropClassSet) { 71 | dropTable(clazz, true); 72 | } 73 | dropClassSet.clear(); 74 | for (DatabaseTableConfig tableConfig : dropTableConfigSet) { 75 | dropTable(tableConfig, true); 76 | } 77 | dropTableConfigSet.clear(); 78 | } 79 | closeConnectionSource(); 80 | DaoManager.clearCache(); 81 | } 82 | 83 | /** 84 | * Return if this test was expecting to be able to load the driver class 85 | */ 86 | protected boolean isDriverClassExpected() { 87 | return true; 88 | } 89 | 90 | /** 91 | * Return if this test was expecting to be able to connect to the database 92 | */ 93 | protected boolean isConnectionExpected() throws IOException { 94 | try { 95 | if (databaseHost == null) { 96 | return true; 97 | } else { 98 | return InetAddress.getByName(databaseHost).isReachable(500); 99 | } 100 | } catch (UnknownHostException e) { 101 | return false; 102 | } 103 | } 104 | 105 | protected void closeConnectionSource() throws Exception { 106 | if (connectionSource != null) { 107 | connectionSource.close(); 108 | connectionSource = null; 109 | } 110 | } 111 | 112 | protected Dao createDao(Class clazz, boolean createTable) throws Exception { 113 | if (connectionSource == null) { 114 | throw new SQLException(DATASOURCE_ERROR); 115 | } 116 | @SuppressWarnings("unchecked") 117 | BaseDaoImpl dao = (BaseDaoImpl) DaoManager.createDao(connectionSource, clazz); 118 | return configDao(dao, createTable); 119 | } 120 | 121 | protected Dao createDao(DatabaseTableConfig tableConfig, boolean createTable) throws Exception { 122 | if (connectionSource == null) { 123 | throw new SQLException(DATASOURCE_ERROR); 124 | } 125 | @SuppressWarnings("unchecked") 126 | BaseDaoImpl dao = (BaseDaoImpl) DaoManager.createDao(connectionSource, tableConfig); 127 | return configDao(dao, createTable); 128 | } 129 | 130 | protected void createTable(Class clazz, boolean dropAtEnd) throws Exception { 131 | try { 132 | // first we drop it in case it existed before 133 | dropTable(clazz, true); 134 | } catch (SQLException ignored) { 135 | // ignore any errors about missing tables 136 | } 137 | TableUtils.createTable(connectionSource, clazz); 138 | if (dropAtEnd) { 139 | dropClassSet.add(clazz); 140 | } 141 | } 142 | 143 | protected void createTable(DatabaseTableConfig tableConfig, boolean dropAtEnd) throws Exception { 144 | try { 145 | // first we drop it in case it existed before 146 | dropTable(tableConfig, true); 147 | } catch (SQLException ignored) { 148 | // ignore any errors about missing tables 149 | } 150 | TableUtils.createTable(connectionSource, tableConfig); 151 | if (dropAtEnd) { 152 | dropTableConfigSet.add(tableConfig); 153 | } 154 | } 155 | 156 | protected void dropTable(Class clazz, boolean ignoreErrors) throws Exception { 157 | // drop the table and ignore any errors along the way 158 | TableUtils.dropTable(connectionSource, clazz, ignoreErrors); 159 | } 160 | 161 | protected void dropTable(DatabaseTableConfig tableConfig, boolean ignoreErrors) throws Exception { 162 | // drop the table and ignore any errors along the way 163 | TableUtils.dropTable(connectionSource, tableConfig, ignoreErrors); 164 | } 165 | 166 | protected static void removeDirectory(String path) { 167 | File file = new File(path); 168 | if (file.isDirectory()) { 169 | removeDirectory(file); 170 | } else { 171 | file.delete(); 172 | } 173 | } 174 | 175 | protected static void removeDirectory(File dir) { 176 | for (File file : dir.listFiles()) { 177 | if (file.isDirectory()) { 178 | removeDirectory(file); 179 | } else { 180 | file.delete(); 181 | } 182 | } 183 | dir.delete(); 184 | } 185 | 186 | private void doOpenConnectionSource() throws Exception { 187 | if (connectionSource == null) { 188 | isConnectionExpected = isConnectionExpected(); 189 | if (isConnectionExpected) { 190 | connectionSource = new JdbcConnectionSource(databaseUrl, userName, password); 191 | } 192 | } 193 | if (databaseType == null) { 194 | if (connectionSource != null) { 195 | databaseType = connectionSource.getDatabaseType(); 196 | } 197 | } else { 198 | if (connectionSource != null) { 199 | connectionSource.setDatabaseType(databaseType); 200 | } 201 | } 202 | } 203 | 204 | private Dao configDao(BaseDaoImpl dao, boolean createTable) throws Exception { 205 | if (connectionSource == null) { 206 | throw new SQLException(DATASOURCE_ERROR); 207 | } 208 | dao.setConnectionSource(connectionSource); 209 | if (createTable) { 210 | DatabaseTableConfig tableConfig = dao.getTableConfig(); 211 | if (tableConfig == null) { 212 | tableConfig = DatabaseTableConfig.fromClass(databaseType, dao.getDataClass()); 213 | } 214 | createTable(tableConfig, true); 215 | } 216 | dao.initialize(); 217 | return dao; 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/JdbcCompiledStatementTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import static org.easymock.EasyMock.createMock; 4 | import static org.easymock.EasyMock.expect; 5 | import static org.easymock.EasyMock.replay; 6 | import static org.easymock.EasyMock.verify; 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | import static org.junit.jupiter.api.Assertions.assertThrowsExactly; 9 | 10 | import java.sql.PreparedStatement; 11 | import java.sql.ResultSetMetaData; 12 | 13 | import org.easymock.EasyMock; 14 | import org.junit.jupiter.api.Test; 15 | 16 | import com.j256.ormlite.BaseCoreTest; 17 | import com.j256.ormlite.field.SqlType; 18 | import com.j256.ormlite.stmt.StatementBuilder.StatementType; 19 | 20 | public class JdbcCompiledStatementTest extends BaseCoreTest { 21 | 22 | @Test 23 | public void testGetColumnName() throws Exception { 24 | PreparedStatement preparedStatement = createMock(PreparedStatement.class); 25 | ResultSetMetaData metadata = createMock(ResultSetMetaData.class); 26 | expect(metadata.getColumnName(1)).andReturn("TEST_COLUMN1"); 27 | expect(preparedStatement.getMetaData()).andReturn(metadata); 28 | preparedStatement.close(); 29 | replay(metadata, preparedStatement); 30 | String statement = "statement"; 31 | JdbcCompiledStatement stmt = 32 | new JdbcCompiledStatement(preparedStatement, statement, StatementType.SELECT, false); 33 | assertEquals(statement, stmt.getStatement()); 34 | assertEquals(statement, stmt.toString()); 35 | assertEquals("TEST_COLUMN1", stmt.getColumnName(0)); 36 | stmt.close(); 37 | verify(preparedStatement, metadata); 38 | } 39 | 40 | @Test 41 | public void testGetMoreResults() throws Exception { 42 | PreparedStatement preparedStatement = createMock(PreparedStatement.class); 43 | expect(preparedStatement.getMoreResults()).andReturn(Boolean.TRUE); 44 | preparedStatement.close(); 45 | replay(preparedStatement); 46 | JdbcCompiledStatement stmt = 47 | new JdbcCompiledStatement(preparedStatement, "statement", StatementType.SELECT, false); 48 | stmt.getMoreResults(); 49 | stmt.close(); 50 | verify(preparedStatement); 51 | } 52 | 53 | @Test 54 | public void testSetNull() throws Exception { 55 | PreparedStatement preparedStatement = createMock(PreparedStatement.class); 56 | preparedStatement.setNull(1, TypeValMapper.getTypeValForSqlType(SqlType.STRING)); 57 | EasyMock.expectLastCall(); 58 | preparedStatement.close(); 59 | replay(preparedStatement); 60 | JdbcCompiledStatement stmt = 61 | new JdbcCompiledStatement(preparedStatement, "statement", StatementType.SELECT, false); 62 | stmt.setObject(0, null, SqlType.STRING); 63 | stmt.close(); 64 | verify(preparedStatement); 65 | } 66 | 67 | @Test 68 | public void testExecuteUpdateWithSelectType() { 69 | PreparedStatement preparedStatement = createMock(PreparedStatement.class); 70 | JdbcCompiledStatement stmt = 71 | new JdbcCompiledStatement(preparedStatement, "statement", StatementType.SELECT, false); 72 | assertThrowsExactly(IllegalArgumentException.class, () -> { 73 | stmt.runUpdate(); 74 | stmt.close(); 75 | }); 76 | } 77 | 78 | @Test 79 | public void testExecuteQueryWithNonSelectType() { 80 | PreparedStatement preparedStatement = createMock(PreparedStatement.class); 81 | JdbcCompiledStatement stmt = 82 | new JdbcCompiledStatement(preparedStatement, "statement", StatementType.EXECUTE, false); 83 | assertThrowsExactly(IllegalArgumentException.class, () -> { 84 | stmt.runQuery(null); 85 | stmt.close(); 86 | }); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/JdbcRawResultsImplTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNotNull; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.util.List; 8 | import java.util.concurrent.atomic.AtomicBoolean; 9 | 10 | import org.junit.jupiter.api.Test; 11 | 12 | import com.j256.ormlite.dao.Dao; 13 | import com.j256.ormlite.dao.GenericRawResults; 14 | import com.j256.ormlite.dao.RawRowMapper; 15 | import com.j256.ormlite.field.DatabaseField; 16 | 17 | public class JdbcRawResultsImplTest extends BaseJdbcTest { 18 | 19 | @Test 20 | public void testCustomColumnNames() throws Exception { 21 | Dao dao = createDao(Foo.class, true); 22 | Foo foo = new Foo(); 23 | foo.val = 1213213; 24 | assertEquals(1, dao.create(foo)); 25 | 26 | final String idName = "SOME_ID"; 27 | final String valName = "SOME_VAL"; 28 | final AtomicBoolean gotResult = new AtomicBoolean(false); 29 | GenericRawResults results = dao.queryRaw("select id as " + idName + ", val as " + valName + " from foo", 30 | new RawRowMapper() { 31 | @Override 32 | public Object mapRow(String[] columnNames, String[] resultColumns) { 33 | assertEquals(idName, columnNames[0]); 34 | assertEquals(valName, columnNames[1]); 35 | gotResult.set(true); 36 | return new Object(); 37 | } 38 | }); 39 | List list = results.getResults(); 40 | assertNotNull(list); 41 | assertEquals(1, list.size()); 42 | assertTrue(gotResult.get()); 43 | } 44 | 45 | protected static class Foo { 46 | @DatabaseField(generatedId = true) 47 | public int id; 48 | @DatabaseField 49 | public int val; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/JdbcSingleConnectionSourceTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertNotNull; 4 | 5 | import java.sql.Connection; 6 | import java.sql.DriverManager; 7 | import java.sql.SQLException; 8 | 9 | import org.junit.jupiter.api.Test; 10 | 11 | import com.j256.ormlite.BaseCoreTest; 12 | import com.j256.ormlite.dao.Dao; 13 | 14 | public class JdbcSingleConnectionSourceTest extends BaseCoreTest { 15 | 16 | private static final String DEFAULT_DATABASE_URL = "jdbc:h2:mem:ormlite"; 17 | 18 | @Test 19 | public void testStuff() throws SQLException { 20 | Connection connection = DriverManager.getConnection(DEFAULT_DATABASE_URL); 21 | JdbcSingleConnectionSource connectionSource = new JdbcSingleConnectionSource(DEFAULT_DATABASE_URL, connection); 22 | try { 23 | Dao dao = createDao(connectionSource, Foo.class, true); 24 | Foo foo = new Foo(); 25 | dao.create(foo); 26 | Foo result = dao.queryForId(foo.id); 27 | assertNotNull(result); 28 | } finally { 29 | connectionSource.close(); 30 | connection.close(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/dao/BulkJdbcDaoTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.dao; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import org.junit.jupiter.api.BeforeEach; 8 | import org.junit.jupiter.api.Test; 9 | 10 | import com.j256.ormlite.dao.Dao; 11 | import com.j256.ormlite.field.DatabaseField; 12 | import com.j256.ormlite.jdbc.BaseJdbcTest; 13 | 14 | public class BulkJdbcDaoTest extends BaseJdbcTest { 15 | 16 | private final static int NUMBER_OBJECTS_TO_CREATE = 1000; 17 | 18 | private Dao fooDao; 19 | 20 | @BeforeEach 21 | @Override 22 | public void before() throws Exception { 23 | super.before(); 24 | fooDao = createDao(Foo.class, true); 25 | } 26 | 27 | @Test 28 | public void testCreateBulk() throws Exception { 29 | for (int i = 0; i < NUMBER_OBJECTS_TO_CREATE; i++) { 30 | Foo foo = new Foo(); 31 | foo.index = i; 32 | assertEquals(1, fooDao.create(foo)); 33 | } 34 | 35 | int fooC = 0; 36 | for (Foo foo : fooDao) { 37 | assertEquals(fooC, foo.index); 38 | fooC++; 39 | } 40 | assertEquals(NUMBER_OBJECTS_TO_CREATE, fooC); 41 | } 42 | 43 | @Test 44 | public void testObjectsEqual() throws Exception { 45 | Foo foo = new Foo(); 46 | assertEquals(1, fooDao.create(foo)); 47 | int id = foo.id; 48 | Foo foo2 = fooDao.queryForId(id); 49 | // both other are null 50 | assertTrue(fooDao.objectsEqual(foo, foo2)); 51 | 52 | // set to some other number 53 | foo2.id = 1341313; 54 | assertFalse(fooDao.objectsEqual(foo2, foo)); 55 | 56 | foo2 = fooDao.queryForId(id); 57 | foo.other = "not null"; 58 | // try null checks from either direction 59 | assertFalse(fooDao.objectsEqual(foo, foo2)); 60 | assertFalse(fooDao.objectsEqual(foo2, foo)); 61 | } 62 | 63 | protected static class Foo { 64 | // @DatabaseField(generatedId = true, generatedIdSequence = "foo_id_seq") 65 | @DatabaseField(generatedId = true) 66 | int id; 67 | @DatabaseField 68 | int index; 69 | @DatabaseField 70 | String other; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/dao/DoubleDbOpenTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.dao; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNotNull; 5 | 6 | import java.io.File; 7 | 8 | import org.junit.jupiter.api.AfterEach; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | 12 | import com.j256.ormlite.BaseCoreTest; 13 | import com.j256.ormlite.dao.Dao; 14 | import com.j256.ormlite.dao.DaoManager; 15 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 16 | import com.j256.ormlite.support.ConnectionSource; 17 | import com.j256.ormlite.table.TableUtils; 18 | 19 | public class DoubleDbOpenTest extends BaseCoreTest { 20 | 21 | private static final String DATABASE_DIR = "/var/tmp/"; 22 | private static final String DATABASE_NAME_PREFIX = DoubleDbOpenTest.class.getSimpleName(); 23 | 24 | @Override 25 | @BeforeEach 26 | public void before() throws Exception { 27 | super.before(); 28 | clearDatabases(); 29 | } 30 | 31 | @Override 32 | @AfterEach 33 | public void after() throws Exception { 34 | super.after(); 35 | clearDatabases(); 36 | } 37 | 38 | @Test 39 | public void testDoubleDbOpen() throws Exception { 40 | clearDatabases(); 41 | ConnectionSource cs = 42 | new JdbcConnectionSource("jdbc:h2:file:" + DATABASE_DIR + "/" + DATABASE_NAME_PREFIX + ".1"); 43 | TableUtils.createTable(cs, Foo.class); 44 | Dao dao = DaoManager.createDao(cs, Foo.class); 45 | Foo foo1 = new Foo(); 46 | foo1.val = 12312; 47 | assertEquals(1, dao.create(foo1)); 48 | 49 | Foo result = dao.queryForId(foo1.id); 50 | assertNotNull(result); 51 | assertEquals(foo1.val, result.val); 52 | 53 | // ================================== 54 | 55 | cs = new JdbcConnectionSource("jdbc:h2:file:" + DATABASE_DIR + "/" + DATABASE_NAME_PREFIX + ".2"); 56 | DaoManager.clearCache(); 57 | TableUtils.createTable(cs, Foo.class); 58 | dao = DaoManager.createDao(cs, Foo.class); 59 | Foo foo2 = new Foo(); 60 | foo2.val = 12314; 61 | assertEquals(1, dao.create(foo2)); 62 | 63 | result = dao.queryForId(foo2.id); 64 | assertNotNull(result); 65 | assertEquals(foo2.val, result.val); 66 | } 67 | 68 | private void clearDatabases() { 69 | for (File file : new File(DATABASE_DIR).listFiles()) { 70 | if (file.getName().startsWith(DATABASE_NAME_PREFIX)) { 71 | file.delete(); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/BaseJdbcDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrowsExactly; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | import java.io.File; 9 | import java.sql.SQLException; 10 | import java.util.ArrayList; 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | import org.junit.jupiter.api.Test; 15 | 16 | import com.j256.ormlite.TestUtils; 17 | import com.j256.ormlite.field.DatabaseField; 18 | import com.j256.ormlite.field.FieldType; 19 | import com.j256.ormlite.jdbc.BaseJdbcTest; 20 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 21 | import com.j256.ormlite.stmt.QueryBuilder; 22 | import com.j256.ormlite.support.DatabaseConnection; 23 | import com.j256.ormlite.table.TableInfo; 24 | 25 | /** 26 | * Base test for other database tests which perform specific functionality tests on all databases. 27 | */ 28 | public abstract class BaseJdbcDatabaseTypeTest extends BaseJdbcTest { 29 | 30 | private final static String DATABASE_NAME = "ormlite"; 31 | private final String DB_DIRECTORY = new File("target", getClass().getSimpleName()).getAbsolutePath(); 32 | 33 | protected final static String GENERATED_ID_SEQ = "genId_seq"; 34 | 35 | @Test 36 | public void testCommentLinePrefix() { 37 | assertEquals("-- ", databaseType.getCommentLinePrefix()); 38 | } 39 | 40 | @Test 41 | public void testEscapedEntityName() { 42 | String word = "word"; 43 | assertEquals("`" + word + "`", TestUtils.appendEscapedEntityName(databaseType, word)); 44 | } 45 | 46 | @Test 47 | public void testEscapedWord() { 48 | String word = "word"; 49 | assertEquals("'" + word + "'", TestUtils.appendEscapedWord(databaseType, word)); 50 | } 51 | 52 | @Test 53 | public void testCreateColumnArg() throws Exception { 54 | if (connectionSource == null) { 55 | return; 56 | } 57 | List additionalArgs = new ArrayList(); 58 | List moreStmts = new ArrayList(); 59 | List queriesAfter = new ArrayList(); 60 | TableInfo tableInfo = new TableInfo(databaseType, StringId.class); 61 | FieldType fieldType = tableInfo.getIdField(); 62 | StringBuilder sb = new StringBuilder(); 63 | databaseType.appendColumnArg(null, sb, fieldType, additionalArgs, null, moreStmts, queriesAfter); 64 | assertTrue(sb.toString().contains(fieldType.getColumnName())); 65 | if (!sb.toString().contains("PRIMARY KEY")) { 66 | databaseType.addPrimaryKeySql(new FieldType[] { fieldType }, additionalArgs, null, moreStmts, queriesAfter); 67 | assertEquals(1, additionalArgs.size()); 68 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 69 | } 70 | } 71 | 72 | @Test 73 | public void testFileSystem() throws Exception { 74 | File dbDir = new File(DB_DIRECTORY); 75 | TestUtils.deleteDirectory(dbDir); 76 | dbDir.mkdirs(); 77 | assertEquals(0, dbDir.list().length); 78 | closeConnectionSource(); 79 | String dbUrl = "jdbc:h2:" + dbDir.getPath() + "/" + DATABASE_NAME; 80 | connectionSource = new JdbcConnectionSource(dbUrl); 81 | DatabaseConnection conn = connectionSource.getReadWriteConnection(null); 82 | try { 83 | databaseType = DatabaseTypeUtils.createDatabaseType(dbUrl); 84 | assertTrue(dbDir.list().length != 0); 85 | } finally { 86 | connectionSource.releaseConnection(conn); 87 | } 88 | } 89 | 90 | @Test 91 | public void testFieldWidthSupport() { 92 | assertTrue(databaseType.isVarcharFieldWidthSupported()); 93 | } 94 | 95 | @Test 96 | public void testLimitSupport() { 97 | assertTrue(databaseType.isLimitSqlSupported()); 98 | } 99 | 100 | @Test 101 | public void testLimitAfterSelect() { 102 | assertFalse(databaseType.isLimitAfterSelect()); 103 | } 104 | 105 | @Test 106 | public void testLimitFormat() throws Exception { 107 | if (connectionSource == null) { 108 | return; 109 | } 110 | if (!databaseType.isLimitSqlSupported()) { 111 | return; 112 | } 113 | TableInfo tableInfo = new TableInfo(databaseType, StringId.class); 114 | QueryBuilder qb = new QueryBuilder(databaseType, tableInfo, null); 115 | long limit = 1232; 116 | qb.limit(limit); 117 | String query = qb.prepareStatementString(); 118 | assertTrue(query.contains(" LIMIT " + limit), query + " should contain LIMIT"); 119 | } 120 | 121 | @Test 122 | public void testOffsetSupport() { 123 | assertTrue(databaseType.isOffsetSqlSupported()); 124 | } 125 | 126 | @Test 127 | public void testLoadDriver() { 128 | if (isDriverClassExpected()) { 129 | assertTrue(databaseType.loadDriver()); 130 | } 131 | } 132 | 133 | @Test 134 | public void testGeneratedIdSequence() throws Exception { 135 | if (connectionSource == null) { 136 | throw new SQLException("Simulate a failure"); 137 | } 138 | TableInfo tableInfo = 139 | new TableInfo(databaseType, GeneratedIdSequence.class); 140 | assertEquals(2, tableInfo.getFieldTypes().length); 141 | StringBuilder sb = new StringBuilder(); 142 | List additionalArgs = new ArrayList(); 143 | List statementsBefore = new ArrayList(); 144 | List statementsAfter = new ArrayList(); 145 | List queriesAfter = new ArrayList(); 146 | assertThrowsExactly(SQLException.class, () -> { 147 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, 148 | statementsAfter, queriesAfter); 149 | }); 150 | } 151 | 152 | /** 153 | * Return the ping value so we can test a connection. 154 | */ 155 | protected void testPingValue(long value) { 156 | assertEquals(1, value); 157 | } 158 | 159 | @Test 160 | public void testDatabasePing() throws Exception { 161 | if (connectionSource == null) { 162 | return; 163 | } 164 | if (!isDriverClassExpected()) { 165 | return; 166 | } 167 | String ping = databaseType.getPingStatement(); 168 | DatabaseConnection conn = connectionSource.getReadOnlyConnection(null); 169 | try { 170 | testPingValue(conn.queryForLong(ping)); 171 | } finally { 172 | connectionSource.releaseConnection(conn); 173 | } 174 | } 175 | 176 | protected static class StringId { 177 | @DatabaseField(id = true) 178 | String id; 179 | } 180 | 181 | protected static class GeneratedId { 182 | @DatabaseField(generatedId = true) 183 | public int id; 184 | @DatabaseField 185 | String other; 186 | 187 | public GeneratedId() { 188 | } 189 | } 190 | 191 | protected static class GeneratedIdSequence { 192 | @DatabaseField(generatedIdSequence = GENERATED_ID_SEQ) 193 | public int genId; 194 | @DatabaseField 195 | public String stuff; 196 | 197 | protected GeneratedIdSequence() { 198 | } 199 | } 200 | 201 | protected static class GeneratedIdSequenceAutoName { 202 | @DatabaseField(generatedId = true) 203 | int genId; 204 | @DatabaseField 205 | public String stuff; 206 | } 207 | 208 | protected static class AllTypes { 209 | @DatabaseField 210 | String stringField; 211 | @DatabaseField 212 | boolean booleanField; 213 | @DatabaseField 214 | Date dateField; 215 | @DatabaseField 216 | byte byteField; 217 | @DatabaseField 218 | short shortField; 219 | @DatabaseField 220 | int intField; 221 | @DatabaseField 222 | long longField; 223 | @DatabaseField 224 | float floatField; 225 | @DatabaseField 226 | double doubleField; 227 | 228 | AllTypes() { 229 | } 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/DatabaseTypeUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrowsExactly; 5 | 6 | import java.lang.reflect.Constructor; 7 | 8 | import org.junit.jupiter.api.Test; 9 | 10 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 11 | import com.j256.ormlite.support.ConnectionSource; 12 | 13 | public class DatabaseTypeUtilsTest { 14 | 15 | @Test 16 | public void testConstructor() throws Exception { 17 | @SuppressWarnings("rawtypes") 18 | Constructor[] constructors = DatabaseTypeUtils.class.getDeclaredConstructors(); 19 | assertEquals(1, constructors.length); 20 | constructors[0].setAccessible(true); 21 | constructors[0].newInstance(); 22 | } 23 | 24 | @Test 25 | public void testCreateDbType() { 26 | DatabaseTypeUtils.createDatabaseType("jdbc:h2:mem:ormlitetest"); 27 | } 28 | 29 | @Test 30 | public void testCreateDbTypeBadDriver() { 31 | assertThrowsExactly(IllegalArgumentException.class, () -> { 32 | DatabaseTypeUtils.createDatabaseType("jdbc:unknown-db:"); 33 | }); 34 | } 35 | 36 | @Test 37 | public void testCreateDbTypeBadUrl() { 38 | assertThrowsExactly(IllegalArgumentException.class, () -> { 39 | DatabaseTypeUtils.createDatabaseType("bad-url"); 40 | }); 41 | } 42 | 43 | @Test 44 | public void testCreateDbTypeNotEnoughParts() { 45 | assertThrowsExactly(IllegalArgumentException.class, () -> { 46 | DatabaseTypeUtils.createDatabaseType("jdbc:"); 47 | }); 48 | } 49 | 50 | @Test 51 | public void testCreateDbTypeDataSource() throws Exception { 52 | ConnectionSource dataSource = null; 53 | try { 54 | String dbUrl = "jdbc:h2:mem:ormlitetest"; 55 | dataSource = new JdbcConnectionSource(dbUrl, new H2DatabaseType()); 56 | dataSource.close(); 57 | } finally { 58 | if (dataSource != null) { 59 | dataSource.getReadOnlyConnection(null).close(); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/Db2DatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.sql.SQLException; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import com.j256.ormlite.TestUtils; 14 | import com.j256.ormlite.field.FieldType; 15 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 16 | import com.j256.ormlite.table.TableInfo; 17 | 18 | public class Db2DatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 19 | 20 | @Override 21 | protected void setDatabaseParams() throws SQLException { 22 | databaseUrl = "jdbc:db2:ormlitedb2"; 23 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 24 | databaseType = new Db2DatabaseType(); 25 | } 26 | 27 | @Override 28 | protected boolean isDriverClassExpected() { 29 | return false; 30 | } 31 | 32 | @Override 33 | @Test 34 | public void testEscapedEntityName() { 35 | String word = "word"; 36 | assertEquals("\"" + word + "\"", TestUtils.appendEscapedEntityName(databaseType, word)); 37 | } 38 | 39 | @Test 40 | public void testBoolean() throws Exception { 41 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 42 | assertEquals(9, tableInfo.getFieldTypes().length); 43 | FieldType booleanField = tableInfo.getFieldTypes()[1]; 44 | assertEquals("booleanField", booleanField.getColumnName()); 45 | StringBuilder sb = new StringBuilder(); 46 | List additionalArgs = new ArrayList(); 47 | List statementsBefore = new ArrayList(); 48 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 49 | assertTrue(sb.toString().contains("SMALLINT")); 50 | } 51 | 52 | @Test 53 | public void testByte() throws Exception { 54 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 55 | assertEquals(9, tableInfo.getFieldTypes().length); 56 | FieldType byteField = tableInfo.getFieldTypes()[3]; 57 | assertEquals("byteField", byteField.getColumnName()); 58 | StringBuilder sb = new StringBuilder(); 59 | List additionalArgs = new ArrayList(); 60 | List statementsBefore = new ArrayList(); 61 | databaseType.appendColumnArg(null, sb, byteField, additionalArgs, statementsBefore, null, null); 62 | assertTrue(sb.toString().contains("SMALLINT")); 63 | } 64 | 65 | @Test 66 | public void testGeneratedId() throws Exception { 67 | TableInfo tableInfo = new TableInfo(databaseType, GeneratedId.class); 68 | StringBuilder sb = new StringBuilder(); 69 | List additionalArgs = new ArrayList(); 70 | List statementsBefore = new ArrayList(); 71 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 72 | null); 73 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, null); 74 | assertTrue(sb.toString().contains(" GENERATED ALWAYS AS IDENTITY"), sb + "should contain the stuff"); 75 | assertEquals(0, statementsBefore.size()); 76 | assertEquals(1, additionalArgs.size()); 77 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 78 | } 79 | 80 | @Test 81 | public void testObject() { 82 | Db2DatabaseType dbType = new Db2DatabaseType(); 83 | StringBuilder sb = new StringBuilder(); 84 | dbType.appendByteArrayType(sb, null, 0); 85 | assertEquals("VARCHAR [] FOR BIT DATA", sb.toString()); 86 | } 87 | 88 | @Override 89 | @Test 90 | public void testOffsetSupport() { 91 | assertFalse(databaseType.isOffsetSqlSupported()); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/DerbyClientServerDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class DerbyClientServerDatabaseTypeTest extends DerbyEmbeddedDatabaseTypeTest { 10 | 11 | @Test 12 | public void testGetClientServerDriverClassName() { 13 | assertArrayEquals(new String[] { "org.apache.derby.jdbc.ClientDriver" }, 14 | new DerbyClientServerDatabaseType().getDriverClassNames()); 15 | } 16 | 17 | @Test 18 | public void testIsDatabaseUrlThisType() { 19 | assertTrue(new DerbyClientServerDatabaseType() 20 | .isDatabaseUrlThisType("jdbc:derby://localhost:1527/MyDbTest;create=true';", "derby")); 21 | assertFalse(new DerbyClientServerDatabaseType().isDatabaseUrlThisType("jdbc:derby:database", "derby")); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/H2DatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | import static org.junit.jupiter.api.Assertions.assertThrowsExactly; 6 | 7 | import java.io.File; 8 | import java.sql.SQLException; 9 | import java.util.ArrayList; 10 | 11 | import org.h2.tools.Server; 12 | import org.junit.jupiter.api.Test; 13 | 14 | import com.j256.ormlite.TestUtils; 15 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 16 | import com.j256.ormlite.table.TableInfo; 17 | 18 | public class H2DatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 19 | 20 | private final static String DATABASE_NAME = "ormlite"; 21 | private final String DB_DIRECTORY = "target/" + getClass().getSimpleName(); 22 | 23 | @Override 24 | protected void setDatabaseParams() { 25 | databaseUrl = "jdbc:h2:mem:" + DATABASE_NAME; 26 | databaseType = new H2DatabaseType(); 27 | } 28 | 29 | @Test 30 | public void testGeneratedIdSequenceNotSupported() throws Exception { 31 | TableInfo tableInfo = 32 | new TableInfo(databaseType, GeneratedIdSequence.class); 33 | assertEquals(2, tableInfo.getFieldTypes().length); 34 | StringBuilder sb = new StringBuilder(); 35 | ArrayList additionalArgs = new ArrayList(); 36 | ArrayList statementsBefore = new ArrayList(); 37 | assertThrowsExactly(SQLException.class, () -> { 38 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 39 | null); 40 | }); 41 | } 42 | 43 | @Test 44 | public void testUsernamePassword() throws Exception { 45 | closeConnectionSource(); 46 | databaseType = new DerbyEmbeddedDatabaseType(); 47 | } 48 | 49 | @Test 50 | public void testRemotePort() throws Exception { 51 | File dbDir = new File(DB_DIRECTORY); 52 | TestUtils.deleteDirectory(dbDir); 53 | dbDir.mkdirs(); 54 | // bad port 55 | int notTheRightPort = 12345; 56 | closeConnectionSource(); 57 | Server server = null; 58 | try { 59 | server = Server.createTcpServer("-tcpPort", Integer.toString(notTheRightPort)).start(); 60 | // try to disable the retry feature which delays this test failure 61 | System.setProperty("h2.socketConnectRetry", "0"); 62 | String dbUrl = "jdbc:h2:tcp://localhost:" + notTheRightPort + "/" + dbDir.getPath() + "/" + DATABASE_NAME; 63 | connectionSource = new JdbcConnectionSource(dbUrl); 64 | assertThrows(SQLException.class, () -> { 65 | connectionSource.getReadOnlyConnection(null); 66 | }); 67 | connectionSource.close(); 68 | } finally { 69 | if (server != null) { 70 | server.stop(); 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/HsqldbDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.lang.reflect.Field; 8 | import java.sql.SQLException; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import org.junit.jupiter.api.Test; 13 | 14 | import com.j256.ormlite.TestUtils; 15 | import com.j256.ormlite.dao.BaseDaoImpl; 16 | import com.j256.ormlite.field.DatabaseField; 17 | import com.j256.ormlite.field.FieldType; 18 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 19 | import com.j256.ormlite.stmt.QueryBuilder; 20 | import com.j256.ormlite.table.TableInfo; 21 | 22 | public class HsqldbDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 23 | 24 | private final static String GENERATED_ID_SEQ = "genId_seq"; 25 | 26 | @Override 27 | protected void setDatabaseParams() throws SQLException { 28 | databaseUrl = "jdbc:hsqldb:ormlite"; 29 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 30 | databaseType = new HsqldbDatabaseType(); 31 | } 32 | 33 | @Override 34 | protected boolean isDriverClassExpected() { 35 | return false; 36 | } 37 | 38 | @Override 39 | @Test 40 | public void testEscapedEntityName() { 41 | String word = "word"; 42 | assertEquals("\"" + word + "\"", TestUtils.appendEscapedEntityName(databaseType, word)); 43 | } 44 | 45 | @Test 46 | public void testDropSequence() throws Exception { 47 | Field field = GeneratedId.class.getField("id"); 48 | FieldType fieldType = FieldType.createFieldType(databaseType, "foo", field, GeneratedId.class); 49 | List statementsBefore = new ArrayList(); 50 | List statementsAfter = new ArrayList(); 51 | databaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter); 52 | assertEquals(0, statementsBefore.size()); 53 | assertEquals(1, statementsAfter.size()); 54 | assertTrue(statementsAfter.get(0).contains("DROP SEQUENCE ")); 55 | } 56 | 57 | @Override 58 | @Test 59 | public void testGeneratedIdSequence() throws Exception { 60 | TableInfo tableInfo = 61 | new TableInfo(databaseType, GeneratedIdSequence.class); 62 | assertEquals(2, tableInfo.getFieldTypes().length); 63 | StringBuilder sb = new StringBuilder(); 64 | List additionalArgs = new ArrayList(); 65 | List statementsBefore = new ArrayList(); 66 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 67 | null); 68 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, null); 69 | assertTrue(sb.toString().contains(" GENERATED BY DEFAULT AS IDENTITY "), 70 | sb + " should contain autoincrement stuff"); 71 | // sequence, sequence table, insert 72 | assertEquals(1, statementsBefore.size()); 73 | assertTrue(statementsBefore.get(0).contains(GENERATED_ID_SEQ.toUpperCase())); 74 | assertEquals(1, additionalArgs.size()); 75 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 76 | } 77 | 78 | @Test 79 | public void testGeneratedIdSequenceAutoName() throws Exception { 80 | TableInfo tableInfo = 81 | new TableInfo(databaseType, GeneratedIdSequenceAutoName.class); 82 | assertEquals(2, tableInfo.getFieldTypes().length); 83 | FieldType idField = tableInfo.getFieldTypes()[0]; 84 | StringBuilder sb = new StringBuilder(); 85 | List additionalArgs = new ArrayList(); 86 | List statementsBefore = new ArrayList(); 87 | databaseType.appendColumnArg(null, sb, idField, additionalArgs, statementsBefore, null, null); 88 | databaseType.addPrimaryKeySql(new FieldType[] { idField }, additionalArgs, statementsBefore, null, null); 89 | String seqName = databaseType 90 | .generateIdSequenceName(GeneratedIdSequenceAutoName.class.getSimpleName().toLowerCase(), idField); 91 | assertTrue(sb.toString().contains(" GENERATED BY DEFAULT AS IDENTITY "), 92 | sb + " should contain gen-id-seq-name stuff"); 93 | // sequence, sequence table, insert 94 | assertEquals(1, statementsBefore.size()); 95 | assertTrue(statementsBefore.get(0).contains(seqName.toUpperCase())); 96 | assertEquals(1, additionalArgs.size()); 97 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 98 | } 99 | 100 | @Override 101 | @Test 102 | public void testFieldWidthSupport() { 103 | assertFalse(databaseType.isVarcharFieldWidthSupported()); 104 | } 105 | 106 | @Override 107 | @Test 108 | public void testLimitAfterSelect() { 109 | assertTrue(databaseType.isLimitAfterSelect()); 110 | } 111 | 112 | @Override 113 | @Test 114 | public void testLimitFormat() throws Exception { 115 | connectionSource.setDatabaseType(databaseType); 116 | BaseDaoImpl dao = new BaseDaoImpl(connectionSource, StringId.class) { 117 | }; 118 | dao.initialize(); 119 | QueryBuilder qb = dao.queryBuilder(); 120 | long limit = 1232; 121 | qb.limit(limit); 122 | String query = qb.prepareStatementString(); 123 | assertTrue(query.startsWith("SELECT LIMIT 0 " + limit + " "), query + " should start with stuff"); 124 | } 125 | 126 | @Test 127 | public void testBoolean() throws Exception { 128 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 129 | assertEquals(9, tableInfo.getFieldTypes().length); 130 | FieldType booleanField = tableInfo.getFieldTypes()[1]; 131 | assertEquals("booleanField", booleanField.getColumnName()); 132 | StringBuilder sb = new StringBuilder(); 133 | List additionalArgs = new ArrayList(); 134 | List statementsBefore = new ArrayList(); 135 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 136 | assertTrue(sb.toString().contains("BIT")); 137 | } 138 | 139 | @Override 140 | protected void testPingValue(long value) { 141 | assertTrue(value >= 1); 142 | } 143 | 144 | private final static String LONG_SEQ_NAME = "longseq"; 145 | 146 | @Test 147 | public void testGneratedIdLong() throws Exception { 148 | TableInfo tableInfo = 149 | new TableInfo(databaseType, GeneratedIdLong.class); 150 | assertEquals(2, tableInfo.getFieldTypes().length); 151 | FieldType idField = tableInfo.getFieldTypes()[0]; 152 | assertEquals("genId", idField.getColumnName()); 153 | StringBuilder sb = new StringBuilder(); 154 | List additionalArgs = new ArrayList(); 155 | List statementsBefore = new ArrayList(); 156 | databaseType.appendColumnArg(null, sb, idField, additionalArgs, statementsBefore, null, null); 157 | assertEquals(1, statementsBefore.size()); 158 | StringBuilder sb2 = new StringBuilder(); 159 | sb2.append("CREATE SEQUENCE "); 160 | databaseType.appendEscapedEntityName(sb2, LONG_SEQ_NAME.toUpperCase()); 161 | sb2.append(" AS BIGINT"); 162 | assertTrue(statementsBefore.get(0).contains(sb2.toString()), 163 | statementsBefore.get(0) + " should contain the right stuff"); 164 | } 165 | 166 | protected static class GeneratedIdLong { 167 | @DatabaseField(generatedIdSequence = LONG_SEQ_NAME) 168 | long genId; 169 | @DatabaseField 170 | public String stuff; 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/MariaDbDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import org.junit.jupiter.api.Test; 11 | 12 | import com.j256.ormlite.field.FieldType; 13 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 14 | import com.j256.ormlite.table.TableInfo; 15 | 16 | public class MariaDbDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 17 | 18 | @Override 19 | protected void setDatabaseParams() throws SQLException { 20 | databaseUrl = "jdbc:mariadb:ormlite"; 21 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 22 | databaseType = new MariaDbDatabaseType(); 23 | } 24 | 25 | @Override 26 | protected boolean isDriverClassExpected() { 27 | return false; 28 | } 29 | 30 | @Test 31 | public void testBoolean() throws Exception { 32 | if (connectionSource == null) { 33 | return; 34 | } 35 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 36 | assertEquals(9, tableInfo.getFieldTypes().length); 37 | FieldType booleanField = tableInfo.getFieldTypes()[1]; 38 | assertEquals("booleanField", booleanField.getColumnName()); 39 | StringBuilder sb = new StringBuilder(); 40 | List additionalArgs = new ArrayList(); 41 | List statementsBefore = new ArrayList(); 42 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 43 | assertTrue(sb.toString().contains("TINYINT(1)")); 44 | } 45 | 46 | @Test 47 | public void testGeneratedIdBuilt() throws Exception { 48 | if (connectionSource == null) { 49 | return; 50 | } 51 | TableInfo tableInfo = 52 | new TableInfo(databaseType, GeneratedId.class); 53 | assertEquals(2, tableInfo.getFieldTypes().length); 54 | StringBuilder sb = new StringBuilder(); 55 | List additionalArgs = new ArrayList(); 56 | List statementsBefore = new ArrayList(); 57 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 58 | null); 59 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, null); 60 | assertTrue(sb.toString().contains(" AUTO_INCREMENT")); 61 | assertEquals(1, additionalArgs.size()); 62 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 63 | } 64 | 65 | @Test 66 | public void testTableSuffix() { 67 | MariaDbDatabaseType dbType = new MariaDbDatabaseType(); 68 | String suffix = "ewfwefef"; 69 | dbType.setCreateTableSuffix(suffix); 70 | StringBuilder sb = new StringBuilder(); 71 | dbType.appendCreateTableSuffix(sb); 72 | assertTrue(sb.toString().contains(suffix)); 73 | } 74 | 75 | @Test 76 | public void testDateTime() { 77 | MariaDbDatabaseType dbType = new MariaDbDatabaseType(); 78 | StringBuilder sb = new StringBuilder(); 79 | dbType.appendDateType(sb, null, 0); 80 | assertEquals("DATETIME", sb.toString()); 81 | } 82 | 83 | @Test 84 | public void testObject() { 85 | MariaDbDatabaseType dbType = new MariaDbDatabaseType(); 86 | StringBuilder sb = new StringBuilder(); 87 | dbType.appendByteArrayType(sb, null, 0); 88 | assertEquals("BLOB", sb.toString()); 89 | } 90 | 91 | @Test 92 | public void testLongStringSchema() { 93 | MariaDbDatabaseType dbType = new MariaDbDatabaseType(); 94 | StringBuilder sb = new StringBuilder(); 95 | dbType.appendLongStringType(sb, null, 0); 96 | assertEquals("TEXT", sb.toString()); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/MysqlDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.sql.SQLException; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import org.junit.jupiter.api.Test; 11 | 12 | import com.j256.ormlite.field.FieldType; 13 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 14 | import com.j256.ormlite.table.TableInfo; 15 | 16 | public class MysqlDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 17 | 18 | @Override 19 | protected void setDatabaseParams() throws SQLException { 20 | databaseUrl = "jdbc:mysql:ormlite"; 21 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 22 | databaseType = new MysqlDatabaseType(); 23 | } 24 | 25 | @Override 26 | protected boolean isDriverClassExpected() { 27 | return false; 28 | } 29 | 30 | @Test 31 | public void testBoolean() throws Exception { 32 | if (connectionSource == null) { 33 | return; 34 | } 35 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 36 | assertEquals(9, tableInfo.getFieldTypes().length); 37 | FieldType booleanField = tableInfo.getFieldTypes()[1]; 38 | assertEquals("booleanField", booleanField.getColumnName()); 39 | StringBuilder sb = new StringBuilder(); 40 | List additionalArgs = new ArrayList(); 41 | List statementsBefore = new ArrayList(); 42 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 43 | assertTrue(sb.toString().contains("TINYINT(1)")); 44 | } 45 | 46 | @Test 47 | public void testGeneratedIdBuilt() throws Exception { 48 | if (connectionSource == null) { 49 | return; 50 | } 51 | TableInfo tableInfo = 52 | new TableInfo(databaseType, GeneratedId.class); 53 | assertEquals(2, tableInfo.getFieldTypes().length); 54 | StringBuilder sb = new StringBuilder(); 55 | List additionalArgs = new ArrayList(); 56 | List statementsBefore = new ArrayList(); 57 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 58 | null); 59 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, null); 60 | assertTrue(sb.toString().contains(" AUTO_INCREMENT")); 61 | assertEquals(1, additionalArgs.size()); 62 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 63 | } 64 | 65 | @Test 66 | public void testTableSuffix() { 67 | MysqlDatabaseType dbType = new MysqlDatabaseType(); 68 | String suffix = "ewfwefef"; 69 | dbType.setCreateTableSuffix(suffix); 70 | StringBuilder sb = new StringBuilder(); 71 | dbType.appendCreateTableSuffix(sb); 72 | assertTrue(sb.toString().contains(suffix)); 73 | } 74 | 75 | @Test 76 | public void testDateTime() { 77 | MysqlDatabaseType dbType = new MysqlDatabaseType(); 78 | StringBuilder sb = new StringBuilder(); 79 | dbType.appendDateType(sb, null, 0); 80 | assertEquals("DATETIME", sb.toString()); 81 | } 82 | 83 | @Test 84 | public void testObject() { 85 | MysqlDatabaseType dbType = new MysqlDatabaseType(); 86 | StringBuilder sb = new StringBuilder(); 87 | dbType.appendByteArrayType(sb, null, 0); 88 | assertEquals("BLOB", sb.toString()); 89 | } 90 | 91 | @Test 92 | public void testLongStringSchema() { 93 | MysqlDatabaseType dbType = new MysqlDatabaseType(); 94 | StringBuilder sb = new StringBuilder(); 95 | dbType.appendLongStringType(sb, null, 0); 96 | assertEquals("TEXT", sb.toString()); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/OracleDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.lang.reflect.Field; 8 | import java.sql.SQLException; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | import org.junit.jupiter.api.Test; 13 | 14 | import com.j256.ormlite.TestUtils; 15 | import com.j256.ormlite.field.FieldType; 16 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 17 | import com.j256.ormlite.table.TableInfo; 18 | 19 | public class OracleDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 20 | 21 | @Override 22 | protected void setDatabaseParams() throws SQLException { 23 | databaseUrl = "jdbc:oracle:ormliteoracle"; 24 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 25 | databaseType = new OracleDatabaseType(); 26 | } 27 | 28 | @Override 29 | protected boolean isDriverClassExpected() { 30 | return false; 31 | } 32 | 33 | @Override 34 | @Test 35 | public void testEscapedEntityName() { 36 | String word = "word"; 37 | assertEquals("\"" + word + "\"", TestUtils.appendEscapedEntityName(databaseType, word)); 38 | } 39 | 40 | @Test 41 | public void testDropSequence() throws Exception { 42 | Field field = GeneratedId.class.getField("id"); 43 | FieldType fieldType = FieldType.createFieldType(databaseType, "foo", field, GeneratedId.class); 44 | List statementsBefore = new ArrayList(); 45 | List statementsAfter = new ArrayList(); 46 | databaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter); 47 | assertEquals(0, statementsBefore.size()); 48 | assertEquals(1, statementsAfter.size()); 49 | assertTrue(statementsAfter.get(0).contains("DROP SEQUENCE ")); 50 | } 51 | 52 | @Test 53 | @Override 54 | public void testGeneratedIdSequence() throws Exception { 55 | TableInfo tableInfo = 56 | new TableInfo(databaseType, GeneratedIdSequence.class); 57 | assertEquals(2, tableInfo.getFieldTypes().length); 58 | StringBuilder sb = new StringBuilder(); 59 | List additionalArgs = new ArrayList(); 60 | List statementsBefore = new ArrayList(); 61 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 62 | null); 63 | assertEquals(1, statementsBefore.size()); 64 | assertTrue(statementsBefore.get(0).contains(GENERATED_ID_SEQ.toUpperCase()), 65 | statementsBefore.get(0) + " should contain sequence"); 66 | assertEquals(0, additionalArgs.size()); 67 | } 68 | 69 | @Test 70 | public void testGeneratedIdSequenceAutoName() throws Exception { 71 | TableInfo tableInfo = 72 | new TableInfo(databaseType, GeneratedIdSequenceAutoName.class); 73 | assertEquals(2, tableInfo.getFieldTypes().length); 74 | FieldType idField = tableInfo.getFieldTypes()[0]; 75 | StringBuilder sb = new StringBuilder(); 76 | List additionalArgs = new ArrayList(); 77 | List statementsBefore = new ArrayList(); 78 | databaseType.appendColumnArg(null, sb, idField, additionalArgs, statementsBefore, null, null); 79 | assertEquals(1, statementsBefore.size()); 80 | String seqName = databaseType 81 | .generateIdSequenceName(GeneratedIdSequenceAutoName.class.getSimpleName().toLowerCase(), idField); 82 | assertTrue(statementsBefore.get(0).contains(seqName)); 83 | assertEquals(0, additionalArgs.size()); 84 | } 85 | 86 | @Test 87 | public void testByte() throws Exception { 88 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 89 | assertEquals(9, tableInfo.getFieldTypes().length); 90 | FieldType byteField = tableInfo.getFieldTypes()[3]; 91 | assertEquals("byteField", byteField.getColumnName()); 92 | StringBuilder sb = new StringBuilder(); 93 | List additionalArgs = new ArrayList(); 94 | List statementsBefore = new ArrayList(); 95 | databaseType.appendColumnArg(null, sb, byteField, additionalArgs, statementsBefore, null, null); 96 | assertTrue(sb.toString().contains("SMALLINT")); 97 | } 98 | 99 | @Test 100 | public void testLong() throws Exception { 101 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 102 | assertEquals(9, tableInfo.getFieldTypes().length); 103 | FieldType booleanField = tableInfo.getFieldTypes()[6]; 104 | assertEquals("longField", booleanField.getColumnName()); 105 | StringBuilder sb = new StringBuilder(); 106 | List additionalArgs = new ArrayList(); 107 | List statementsBefore = new ArrayList(); 108 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 109 | assertTrue(sb.toString().contains("NUMERIC")); 110 | } 111 | 112 | @Test 113 | public void testObject() { 114 | OracleDatabaseType dbType = new OracleDatabaseType(); 115 | StringBuilder sb = new StringBuilder(); 116 | dbType.appendByteArrayType(sb, null, 0); 117 | assertEquals("LONG RAW", sb.toString()); 118 | } 119 | 120 | @Test 121 | public void testSelectNextVal() { 122 | OracleDatabaseType dbType = new OracleDatabaseType(); 123 | StringBuilder sb = new StringBuilder(); 124 | String sequenceName = "stuff_seq"; 125 | dbType.appendSelectNextValFromSequence(sb, sequenceName); 126 | assertEquals("SELECT \"" + sequenceName + "\".nextval FROM dual", sb.toString()); 127 | } 128 | 129 | @Override 130 | @Test 131 | public void testOffsetSupport() { 132 | assertFalse(databaseType.isOffsetSqlSupported()); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/PostgresDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.lang.reflect.Field; 7 | import java.sql.SQLException; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import com.j256.ormlite.TestUtils; 14 | import com.j256.ormlite.field.FieldType; 15 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 16 | import com.j256.ormlite.table.TableInfo; 17 | 18 | public class PostgresDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 19 | 20 | @Override 21 | protected void setDatabaseParams() throws SQLException { 22 | databaseUrl = "jdbc:postgresql:ormlitepostgres"; 23 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 24 | databaseType = new PostgresDatabaseType(); 25 | } 26 | 27 | @Override 28 | protected boolean isDriverClassExpected() { 29 | return false; 30 | } 31 | 32 | @Override 33 | @Test 34 | public void testEscapedEntityName() { 35 | String word = "word"; 36 | assertEquals("\"" + word + "\"", TestUtils.appendEscapedEntityName(databaseType, word)); 37 | } 38 | 39 | @Test 40 | public void testEscapedEntityNameSchema() { 41 | String schema = "schema"; 42 | String table = "table"; 43 | String word = schema + "." + table; 44 | assertEquals("\"" + schema + "\".\"" + table + "\"", TestUtils.appendEscapedEntityName(databaseType, word)); 45 | } 46 | 47 | @Test 48 | public void testDropSequence() throws Exception { 49 | if (connectionSource == null) { 50 | return; 51 | } 52 | Field field = GeneratedId.class.getField("id"); 53 | FieldType fieldType = FieldType.createFieldType(databaseType, "foo", field, GeneratedId.class); 54 | List statementsBefore = new ArrayList(); 55 | List statementsAfter = new ArrayList(); 56 | databaseType.dropColumnArg(fieldType, statementsBefore, statementsAfter); 57 | assertEquals(0, statementsBefore.size()); 58 | assertEquals(1, statementsAfter.size()); 59 | assertTrue(statementsAfter.get(0).contains("DROP SEQUENCE ")); 60 | } 61 | 62 | @Test 63 | @Override 64 | public void testGeneratedIdSequence() throws Exception { 65 | if (connectionSource == null) { 66 | return; 67 | } 68 | TableInfo tableInfo = 69 | new TableInfo(databaseType, GeneratedIdSequence.class); 70 | assertEquals(2, tableInfo.getFieldTypes().length); 71 | StringBuilder sb = new StringBuilder(); 72 | List additionalArgs = new ArrayList(); 73 | List statementsBefore = new ArrayList(); 74 | List queriesAfter = new ArrayList(); 75 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 76 | queriesAfter); 77 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, queriesAfter); 78 | assertTrue(sb.toString().contains(" DEFAULT NEXTVAL('\"" + GENERATED_ID_SEQ + "\"')")); 79 | assertEquals(1, statementsBefore.size()); 80 | assertTrue(statementsBefore.get(0).contains(GENERATED_ID_SEQ)); 81 | assertEquals(1, additionalArgs.size()); 82 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 83 | assertEquals(0, queriesAfter.size()); 84 | } 85 | 86 | @Test 87 | public void testGeneratedIdSequenceAutoName() throws Exception { 88 | if (connectionSource == null) { 89 | return; 90 | } 91 | TableInfo tableInfo = 92 | new TableInfo(databaseType, GeneratedIdSequenceAutoName.class); 93 | assertEquals(2, tableInfo.getFieldTypes().length); 94 | FieldType idField = tableInfo.getFieldTypes()[0]; 95 | StringBuilder sb = new StringBuilder(); 96 | List additionalArgs = new ArrayList(); 97 | List statementsBefore = new ArrayList(); 98 | List queriesAfter = new ArrayList(); 99 | databaseType.appendColumnArg(null, sb, idField, additionalArgs, statementsBefore, null, queriesAfter); 100 | databaseType.addPrimaryKeySql(new FieldType[] { idField }, additionalArgs, statementsBefore, null, 101 | queriesAfter); 102 | String seqName = databaseType 103 | .generateIdSequenceName(GeneratedIdSequenceAutoName.class.getSimpleName().toLowerCase(), idField); 104 | assertTrue(sb.toString().contains(" DEFAULT NEXTVAL('\"" + seqName + "\"')")); 105 | assertEquals(1, statementsBefore.size()); 106 | assertTrue(statementsBefore.get(0).contains(seqName)); 107 | assertEquals(1, additionalArgs.size()); 108 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 109 | assertEquals(0, queriesAfter.size()); 110 | } 111 | 112 | @Test 113 | public void testBoolean() throws Exception { 114 | if (connectionSource == null) { 115 | return; 116 | } 117 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 118 | assertEquals(9, tableInfo.getFieldTypes().length); 119 | FieldType booleanField = tableInfo.getFieldTypes()[1]; 120 | assertEquals("booleanField", booleanField.getColumnName()); 121 | StringBuilder sb = new StringBuilder(); 122 | List additionalArgs = new ArrayList(); 123 | List statementsBefore = new ArrayList(); 124 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 125 | assertTrue(sb.toString().contains("BOOLEAN")); 126 | } 127 | 128 | @Test 129 | public void testByte() throws Exception { 130 | if (connectionSource == null) { 131 | return; 132 | } 133 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 134 | assertEquals(9, tableInfo.getFieldTypes().length); 135 | FieldType byteField = tableInfo.getFieldTypes()[3]; 136 | assertEquals("byteField", byteField.getColumnName()); 137 | StringBuilder sb = new StringBuilder(); 138 | List additionalArgs = new ArrayList(); 139 | List statementsBefore = new ArrayList(); 140 | databaseType.appendColumnArg(null, sb, byteField, additionalArgs, statementsBefore, null, null); 141 | assertTrue(sb.toString().contains("SMALLINT")); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/SqlServerDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.sql.SQLException; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import com.j256.ormlite.TestUtils; 14 | import com.j256.ormlite.dao.Dao; 15 | import com.j256.ormlite.field.FieldType; 16 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 17 | import com.j256.ormlite.stmt.QueryBuilder; 18 | import com.j256.ormlite.table.TableInfo; 19 | 20 | public class SqlServerDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 21 | 22 | @Override 23 | protected void setDatabaseParams() throws SQLException { 24 | databaseUrl = "jdbc:sqlserver:db"; 25 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 26 | databaseType = new SqlServerDatabaseType(); 27 | } 28 | 29 | @Override 30 | protected boolean isDriverClassExpected() { 31 | return false; 32 | } 33 | 34 | @Override 35 | @Test 36 | public void testEscapedEntityName() { 37 | String word = "word"; 38 | assertEquals("[" + word + "]", TestUtils.appendEscapedEntityName(databaseType, word)); 39 | } 40 | 41 | @Test 42 | public void testMultipartEscapedEntityName() { 43 | String firstPart = "firstPart"; 44 | String secondPart = "secondPart"; 45 | String input = firstPart + "." + secondPart; 46 | String expected = "[" + firstPart + "].[" + secondPart + "]"; 47 | assertEquals(expected, TestUtils.appendEscapedEntityName(databaseType, input)); 48 | } 49 | 50 | @Override 51 | @Test 52 | public void testLimitAfterSelect() { 53 | assertTrue(databaseType.isLimitAfterSelect()); 54 | } 55 | 56 | @Override 57 | @Test 58 | public void testLimitFormat() throws Exception { 59 | if (connectionSource == null) { 60 | return; 61 | } 62 | Dao dao; 63 | try { 64 | connectionSource.setDatabaseType(databaseType); 65 | dao = createDao(StringId.class, false); 66 | } finally { 67 | connectionSource.setDatabaseType(new H2DatabaseType()); 68 | } 69 | QueryBuilder qb = dao.queryBuilder(); 70 | long limit = 1232; 71 | qb.limit(limit); 72 | String query = qb.prepareStatementString(); 73 | assertTrue(query.startsWith("SELECT TOP " + limit + " "), query + " should start with stuff"); 74 | } 75 | 76 | @Override 77 | @Test 78 | public void testOffsetSupport() { 79 | assertFalse(databaseType.isOffsetSqlSupported()); 80 | } 81 | 82 | @Test 83 | public void testBoolean() throws Exception { 84 | if (connectionSource == null) { 85 | return; 86 | } 87 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 88 | assertEquals(9, tableInfo.getFieldTypes().length); 89 | FieldType booleanField = tableInfo.getFieldTypes()[1]; 90 | assertEquals("booleanField", booleanField.getColumnName()); 91 | StringBuilder sb = new StringBuilder(); 92 | List additionalArgs = new ArrayList(); 93 | List statementsBefore = new ArrayList(); 94 | databaseType.appendColumnArg(null, sb, booleanField, additionalArgs, statementsBefore, null, null); 95 | assertTrue(sb.toString().contains("BIT")); 96 | } 97 | 98 | @Test 99 | public void testByte() throws Exception { 100 | if (connectionSource == null) { 101 | return; 102 | } 103 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 104 | assertEquals(9, tableInfo.getFieldTypes().length); 105 | FieldType byteField = tableInfo.getFieldTypes()[3]; 106 | assertEquals("byteField", byteField.getColumnName()); 107 | StringBuilder sb = new StringBuilder(); 108 | List additionalArgs = new ArrayList(); 109 | List statementsBefore = new ArrayList(); 110 | databaseType.appendColumnArg(null, sb, byteField, additionalArgs, statementsBefore, null, null); 111 | assertTrue(sb.toString().contains("SMALLINT")); 112 | } 113 | 114 | @Test 115 | public void testDate() throws Exception { 116 | if (connectionSource == null) { 117 | return; 118 | } 119 | TableInfo tableInfo = new TableInfo(databaseType, AllTypes.class); 120 | assertEquals(9, tableInfo.getFieldTypes().length); 121 | FieldType byteField = tableInfo.getFieldTypes()[2]; 122 | assertEquals("dateField", byteField.getColumnName()); 123 | StringBuilder sb = new StringBuilder(); 124 | List additionalArgs = new ArrayList(); 125 | List statementsBefore = new ArrayList(); 126 | databaseType.appendColumnArg(null, sb, byteField, additionalArgs, statementsBefore, null, null); 127 | assertTrue(sb.toString().contains("DATETIME")); 128 | } 129 | 130 | @Test 131 | public void testGeneratedIdBuilt() throws Exception { 132 | if (connectionSource == null) { 133 | return; 134 | } 135 | TableInfo tableInfo = 136 | new TableInfo(databaseType, GeneratedId.class); 137 | assertEquals(2, tableInfo.getFieldTypes().length); 138 | StringBuilder sb = new StringBuilder(); 139 | List additionalArgs = new ArrayList(); 140 | List statementsBefore = new ArrayList(); 141 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 142 | null); 143 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, null); 144 | assertTrue(sb.toString().contains(" IDENTITY")); 145 | assertEquals(1, additionalArgs.size()); 146 | assertTrue(additionalArgs.get(0).contains("PRIMARY KEY")); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/SqlServerJtdsDatabaseConnectTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import java.sql.SQLException; 4 | 5 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 6 | 7 | public class SqlServerJtdsDatabaseConnectTypeTest extends SqlServerDatabaseTypeTest { 8 | 9 | @Override 10 | protected void setDatabaseParams() throws SQLException { 11 | databaseUrl = "jdbc:jtds:sqlserver://db/ormlite;ssl=request"; 12 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 13 | databaseType = new SqlServerJtdsDatabaseType(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/db/SqliteDatabaseTypeTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.db; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertThrowsExactly; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | import java.io.Serializable; 9 | import java.sql.SQLException; 10 | import java.util.ArrayList; 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | import org.junit.jupiter.api.Test; 15 | 16 | import com.j256.ormlite.dao.Dao; 17 | import com.j256.ormlite.dao.GenericRawResults; 18 | import com.j256.ormlite.field.DataType; 19 | import com.j256.ormlite.field.DatabaseField; 20 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 21 | import com.j256.ormlite.stmt.QueryBuilder; 22 | import com.j256.ormlite.table.TableInfo; 23 | 24 | public class SqliteDatabaseTypeTest extends BaseJdbcDatabaseTypeTest { 25 | 26 | @Override 27 | protected void setDatabaseParams() throws SQLException { 28 | databaseUrl = "jdbc:sqlite:"; 29 | connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL); 30 | databaseType = new SqliteDatabaseType(); 31 | } 32 | 33 | @Override 34 | protected boolean isDriverClassExpected() { 35 | return false; 36 | } 37 | 38 | @Test 39 | public void testGeneratedIdSequenceNotSupported() throws Exception { 40 | TableInfo tableInfo = 41 | new TableInfo(databaseType, GeneratedIdSequence.class); 42 | assertEquals(2, tableInfo.getFieldTypes().length); 43 | StringBuilder sb = new StringBuilder(); 44 | ArrayList additionalArgs = new ArrayList(); 45 | ArrayList statementsBefore = new ArrayList(); 46 | assertThrowsExactly(SQLException.class, () -> { 47 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 48 | null); 49 | }); 50 | } 51 | 52 | @Test 53 | public void testGeneratedId() throws Exception { 54 | TableInfo tableInfo = 55 | new TableInfo(databaseType, GeneratedId.class); 56 | StringBuilder sb = new StringBuilder(); 57 | List additionalArgs = new ArrayList(); 58 | List statementsBefore = new ArrayList(); 59 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 60 | null); 61 | databaseType.addPrimaryKeySql(tableInfo.getFieldTypes(), additionalArgs, statementsBefore, null, null); 62 | assertTrue(sb.toString().contains(" INTEGER PRIMARY KEY AUTOINCREMENT"), sb + "should contain the stuff"); 63 | assertEquals(0, statementsBefore.size()); 64 | assertEquals(0, additionalArgs.size()); 65 | } 66 | 67 | @Override 68 | @Test 69 | public void testFieldWidthSupport() { 70 | assertFalse(databaseType.isVarcharFieldWidthSupported()); 71 | } 72 | 73 | @Test 74 | public void testCreateTableReturnsZero() { 75 | assertFalse(databaseType.isCreateTableReturnsZero()); 76 | } 77 | 78 | @Test 79 | public void testSerialField() throws Exception { 80 | TableInfo tableInfo = new TableInfo(databaseType, SerialField.class); 81 | StringBuilder sb = new StringBuilder(); 82 | List additionalArgs = new ArrayList(); 83 | List statementsBefore = new ArrayList(); 84 | databaseType.appendColumnArg(null, sb, tableInfo.getFieldTypes()[0], additionalArgs, statementsBefore, null, 85 | null); 86 | assertTrue(sb.toString().contains("BLOB")); 87 | } 88 | 89 | @Test 90 | public void testDateFormat() throws Exception { 91 | Dao dao = createDao(AllTypes.class, true); 92 | AllTypes all = new AllTypes(); 93 | all.dateField = new Date(); 94 | assertEquals(1, dao.create(all)); 95 | GenericRawResults results = dao.queryRaw("select * from alltypes"); 96 | List stringslist = results.getResults(); 97 | String[] names = results.getColumnNames(); 98 | for (String[] strings : stringslist) { 99 | for (int i = 0; i < strings.length; i++) { 100 | System.out.println(names[i] + "=" + strings[i]); 101 | } 102 | } 103 | } 104 | 105 | @Test 106 | public void testLimitOffsetFormat() throws Exception { 107 | if (connectionSource == null) { 108 | return; 109 | } 110 | TableInfo tableInfo = new TableInfo(databaseType, StringId.class); 111 | QueryBuilder qb = new QueryBuilder(databaseType, tableInfo, null); 112 | long limit = 1232; 113 | qb.limit(limit); 114 | long offset = 171; 115 | qb.offset(offset); 116 | String query = qb.prepareStatementString(); 117 | assertTrue(query.contains(" LIMIT " + offset + "," + limit), query + " should contain LIMIT"); 118 | } 119 | 120 | @Test 121 | public void testIsOffsetLimitArgument() { 122 | assertTrue(databaseType.isOffsetLimitArgument()); 123 | } 124 | 125 | @Test 126 | public void testIsNestedSavePointsSupported() { 127 | assertFalse(databaseType.isNestedSavePointsSupported()); 128 | } 129 | 130 | @Test 131 | public void testfIsNestedSavePointsSupported() { 132 | assertThrowsExactly(IllegalStateException.class, () -> { 133 | databaseType.appendOffsetValue(null, 0); 134 | }); 135 | } 136 | 137 | /* ==================================================================== */ 138 | 139 | protected static class GeneratedIdLong { 140 | @DatabaseField(generatedId = true) 141 | public long id; 142 | @DatabaseField 143 | String other; 144 | 145 | public GeneratedIdLong() { 146 | } 147 | } 148 | 149 | protected static class SerialField { 150 | @DatabaseField(dataType = DataType.SERIALIZABLE) 151 | SerializedThing other; 152 | 153 | public SerialField() { 154 | } 155 | } 156 | 157 | protected static class SerializedThing implements Serializable { 158 | private static final long serialVersionUID = -7989929665216767119L; 159 | @DatabaseField 160 | String other; 161 | 162 | public SerializedThing() { 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/datapersister/DataPersisterMain.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.datapersister; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNull; 5 | 6 | import java.util.Date; 7 | 8 | import org.joda.time.DateTime; 9 | 10 | import com.j256.ormlite.dao.Dao; 11 | import com.j256.ormlite.dao.DaoManager; 12 | import com.j256.ormlite.field.DataPersisterManager; 13 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 14 | import com.j256.ormlite.stmt.UpdateBuilder; 15 | import com.j256.ormlite.support.ConnectionSource; 16 | import com.j256.ormlite.table.TableUtils; 17 | 18 | /** 19 | * Main sample routine to show how to define custom data persisters for tuning how ORMLite writes and reads stuff from 20 | * the database. 21 | * 22 | *

23 | * NOTE: We use asserts in a couple of places to verify the results but if this were actual production code, we 24 | * would have proper error handling. 25 | *

26 | */ 27 | public class DataPersisterMain { 28 | 29 | // we are using the in-memory H2 database 30 | private final static String DATABASE_URL = "jdbc:h2:mem:user"; 31 | 32 | private Dao userDao; 33 | 34 | public static void main(String[] args) throws Exception { 35 | // turn our static method into an instance of Main 36 | new DataPersisterMain().doMain(args); 37 | } 38 | 39 | private void doMain(String[] args) throws Exception { 40 | JdbcConnectionSource connectionSource = null; 41 | try { 42 | // create our data-source for the database 43 | connectionSource = new JdbcConnectionSource(DATABASE_URL); 44 | // setup our database and DAOs 45 | setupDatabase(connectionSource); 46 | // read and write some data 47 | readWriteData(); 48 | System.out.println("\n\nIt seems to have worked\n\n"); 49 | } finally { 50 | // destroy the data source which should close underlying connections 51 | if (connectionSource != null) { 52 | connectionSource.close(); 53 | } 54 | } 55 | } 56 | 57 | /** 58 | * Setup our database and DAOs 59 | */ 60 | private void setupDatabase(ConnectionSource connectionSource) throws Exception { 61 | 62 | /* 63 | * We register our own persister for DateTime objects. ORMLite actually has a built in one but it has to use 64 | * reflection. 65 | */ 66 | DataPersisterManager.registerDataPersisters(DateTimePersister.getSingleton()); 67 | 68 | userDao = DaoManager.createDao(connectionSource, User.class); 69 | 70 | // if you need to create the table 71 | TableUtils.createTable(connectionSource, User.class); 72 | } 73 | 74 | /** 75 | * Read and write some example data. 76 | */ 77 | private void readWriteData() throws Exception { 78 | // create an instance of User 79 | String name = "Jim Coakley"; 80 | Date birthDate = new Date(); 81 | DateTime createDateTime = new DateTime().plusDays(10); 82 | User user = new User(name, birthDate, createDateTime); 83 | 84 | // persist the user object to the database 85 | userDao.create(user); 86 | 87 | // if we get the user from the database then we should 88 | User result = userDao.queryForId(user.getId()); 89 | // our result birth-date should now be null because it is too early 90 | assertEquals(birthDate, result.getBirthDate()); 91 | assertEquals(createDateTime, result.getCreateDateTime()); 92 | 93 | // to simulate a 'zero-date' we update the database by hand 94 | UpdateBuilder ub = userDao.updateBuilder(); 95 | // set it to some silly value 96 | ub.updateColumnExpression(User.FIELD_BIRTH_DATE, "'0000-01-01'"); 97 | assertEquals(1, ub.update()); 98 | 99 | // now we pull back out the user to see if we get a null birth-date 100 | result = userDao.queryForId(user.getId()); 101 | // our result birth-date should now be null because it is too early 102 | assertNull(result.getBirthDate()); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/datapersister/DateTimePersister.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.datapersister; 2 | 3 | import org.joda.time.DateTime; 4 | 5 | import com.j256.ormlite.field.DataPersisterManager; 6 | import com.j256.ormlite.field.DatabaseField; 7 | import com.j256.ormlite.field.FieldType; 8 | import com.j256.ormlite.field.SqlType; 9 | import com.j256.ormlite.field.types.DateTimeType; 10 | 11 | /** 12 | * A custom persister that is able to store the Joda {@link DateTime} class in the database as epoch-millis long 13 | * integer. This overrides the {@link DateTimeType} which uses reflection instead. This should run faster. 14 | * 15 | * This can be specified using {@link DatabaseField#persisterClass()} or registered with 16 | * {@link DataPersisterManager#registerDataPersisters(com.j256.ormlite.field.DataPersister...)}. 17 | * 18 | * @author graywatson 19 | */ 20 | public class DateTimePersister extends DateTimeType { 21 | 22 | private static final DateTimePersister singleTon = new DateTimePersister(); 23 | 24 | private DateTimePersister() { 25 | super(SqlType.LONG, new Class[] { DateTime.class }); 26 | } 27 | 28 | public static DateTimePersister getSingleton() { 29 | return singleTon; 30 | } 31 | 32 | @Override 33 | public Object javaToSqlArg(FieldType fieldType, Object javaObject) { 34 | DateTime dateTime = (DateTime) javaObject; 35 | if (dateTime == null) { 36 | return null; 37 | } else { 38 | return dateTime.getMillis(); 39 | } 40 | } 41 | 42 | @Override 43 | public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) { 44 | return new DateTime((Long) sqlArg); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/datapersister/MyDatePersister.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.datapersister; 2 | 3 | import java.sql.SQLException; 4 | import java.sql.Timestamp; 5 | import java.util.Date; 6 | 7 | import com.j256.ormlite.field.DatabaseField; 8 | import com.j256.ormlite.field.FieldType; 9 | import com.j256.ormlite.field.SqlType; 10 | import com.j256.ormlite.field.types.DateType; 11 | import com.j256.ormlite.support.DatabaseResults; 12 | 13 | /** 14 | * A custom persister that tweaks how the Date is stored in the database. If the date is before 1970 then this just 15 | * return null instead of throwing some sort of out-of-range error. This is useful because sometimes we get low values 16 | * of SQL timestamps that are stored in existing schemas which can't be mapped to a Date. 17 | * 18 | *

19 | * You would not want this to override the default behavior for Date so you would use this by specifying the 20 | * class in {@link DatabaseField#persisterClass()}. 21 | *

22 | * 23 | * @author graywatson 24 | */ 25 | public class MyDatePersister extends DateType { 26 | 27 | private static final MyDatePersister singleTon = new MyDatePersister(); 28 | @SuppressWarnings("deprecation") 29 | private static final Timestamp ZERO_TIMESTAMP = new Timestamp(1970, 0, 0, 0, 0, 0, 0); 30 | 31 | private MyDatePersister() { 32 | super(SqlType.DATE, new Class[] { Date.class }); 33 | } 34 | 35 | public static MyDatePersister getSingleton() { 36 | return singleTon; 37 | } 38 | 39 | @Override 40 | public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException { 41 | Timestamp timestamp = results.getTimestamp(columnPos); 42 | if (timestamp == null || ZERO_TIMESTAMP.after(timestamp)) { 43 | return null; 44 | } else { 45 | return timestamp.getTime(); 46 | } 47 | } 48 | 49 | @Override 50 | public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) { 51 | if (sqlArg == null) { 52 | return null; 53 | } else { 54 | return new Date((Long) sqlArg); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/datapersister/README.txt: -------------------------------------------------------------------------------- 1 | This example shows how to define custom data persisters which tune how ORMLite writes and reads 2 | data from the database. The DateTimePersister can store org.joda.time.DateTime objects to the 3 | database and MyDatePersister is used to tune how the database results are returned. 4 | 5 | This example depends on the H2 database which is a native Java SQL implementation. You can 6 | download the latest jar from the website: 7 | 8 | http://www.h2database.com/html/download.html 9 | 10 | For more examples see: http://ormlite.com/docs/examples 11 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/datapersister/User.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.datapersister; 2 | 3 | import java.util.Date; 4 | 5 | import org.joda.time.DateTime; 6 | 7 | import com.j256.ormlite.field.DataPersisterManager; 8 | import com.j256.ormlite.field.DatabaseField; 9 | import com.j256.ormlite.table.DatabaseTable; 10 | 11 | /** 12 | * Example user object that is persisted to disk by the DAO and other example classes. 13 | */ 14 | @DatabaseTable 15 | public class User { 16 | 17 | // for UpdateBuilder to be able to find the fields 18 | public static final String FIELD_BIRTH_DATE = "birthDate"; 19 | 20 | @DatabaseField(generatedId = true) 21 | private int id; 22 | 23 | @DatabaseField 24 | private String name; 25 | 26 | /** 27 | * We use the persisterClass here to use our customer persister for handling invalid SQL Timestamp values. 28 | */ 29 | @DatabaseField(columnName = FIELD_BIRTH_DATE, persisterClass = MyDatePersister.class) 30 | private Date birthDate; 31 | 32 | /** 33 | * NOTE: this is _not_ a default type that is stored by ORMLite so we are going to define a custom persister for 34 | * {@link DateTime} and register it using 35 | * {@link DataPersisterManager#registerDataPersisters(com.j256.ormlite.field.DataPersister...)}. 36 | */ 37 | @DatabaseField 38 | private DateTime createDateTime; 39 | 40 | User() { 41 | // all persisted classes must define a no-arg constructor with at least package visibility 42 | } 43 | 44 | public User(String name, Date birthDate, DateTime createDateTime) { 45 | this.name = name; 46 | this.birthDate = birthDate; 47 | this.createDateTime = createDateTime; 48 | } 49 | 50 | public int getId() { 51 | return id; 52 | } 53 | 54 | public String getName() { 55 | return name; 56 | } 57 | 58 | public Date getBirthDate() { 59 | return birthDate; 60 | } 61 | 62 | public DateTime getCreateDateTime() { 63 | return createDateTime; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/fieldConfig/Account.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.fieldConfig; 2 | 3 | /** 4 | * Example account object that is persisted to disk by the DAO and other example classes. 5 | */ 6 | public class Account { 7 | 8 | // for QueryBuilder to be able to find the fields 9 | public static final String NAME_FIELD_NAME = "name"; 10 | public static final String PASSWORD_FIELD_NAME = "passwd"; 11 | 12 | private int id; 13 | private String name; 14 | private String password; 15 | 16 | Account() { 17 | // all persisted classes must define a no-arg constructor with at least package visibility 18 | } 19 | 20 | public Account(String name) { 21 | this.name = name; 22 | } 23 | 24 | public Account(String name, String password) { 25 | this.name = name; 26 | this.password = password; 27 | } 28 | 29 | public int getId() { 30 | return id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public String getPassword() { 42 | return password; 43 | } 44 | 45 | public void setPassword(String password) { 46 | this.password = password; 47 | } 48 | 49 | @Override 50 | public int hashCode() { 51 | return name.hashCode(); 52 | } 53 | 54 | @Override 55 | public boolean equals(Object other) { 56 | if (other == null || other.getClass() != getClass()) { 57 | return false; 58 | } 59 | return name.equals(((Account) other).name); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/fieldConfig/Delivery.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.fieldConfig; 2 | 3 | import java.util.Date; 4 | 5 | import com.j256.ormlite.field.DatabaseField; 6 | import com.j256.ormlite.field.DatabaseFieldConfig; 7 | 8 | /** 9 | * Example delivery object that does not use any {@link DatabaseField} annotations but uses direct wiring of the field 10 | * configurations using {@link DatabaseFieldConfig} in Java or Spring configurations. 11 | * 12 | * See {@link FieldConfigMain} or {@link SpringFieldConfigMain}. 13 | */ 14 | public class Delivery { 15 | 16 | private int id; 17 | private Date when; 18 | private String signedBy; 19 | private Account account; 20 | 21 | Delivery() { 22 | // all persisted classes must define a no-arg constructor with at least package visibility 23 | } 24 | 25 | public Delivery(Date when, String signedBy, Account account) { 26 | this.when = when; 27 | this.signedBy = signedBy; 28 | this.account = account; 29 | } 30 | 31 | public int getId() { 32 | return id; 33 | } 34 | 35 | public Date getWhen() { 36 | return when; 37 | } 38 | 39 | public String getSignedBy() { 40 | return signedBy; 41 | } 42 | 43 | public Account getAccount() { 44 | return account; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/fieldConfig/FieldConfigMain.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.fieldConfig; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNotNull; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Date; 8 | 9 | import com.j256.ormlite.dao.Dao; 10 | import com.j256.ormlite.dao.DaoManager; 11 | import com.j256.ormlite.db.DatabaseType; 12 | import com.j256.ormlite.field.DatabaseFieldConfig; 13 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 14 | import com.j256.ormlite.support.ConnectionSource; 15 | import com.j256.ormlite.table.DatabaseTableConfig; 16 | import com.j256.ormlite.table.TableUtils; 17 | 18 | /** 19 | * Main sample routine to show how to do basic operations with the package. 20 | * 21 | *

22 | * NOTE: We use asserts in a couple of places to verify the results but if this were actual production code, we 23 | * would have proper error handling. 24 | *

25 | */ 26 | public class FieldConfigMain { 27 | 28 | // we are using the in-memory H2 database 29 | private final static String DATABASE_URL = "jdbc:h2:mem:account"; 30 | 31 | private Dao accountDao; 32 | private Dao deliveryDao; 33 | 34 | public static void main(String[] args) throws Exception { 35 | // turn our static method into an instance of Main 36 | new FieldConfigMain().doMain(args); 37 | } 38 | 39 | private void doMain(String[] args) throws Exception { 40 | JdbcConnectionSource connectionSource = null; 41 | try { 42 | // create our data-source for the database 43 | connectionSource = new JdbcConnectionSource(DATABASE_URL); 44 | // setup our database and DAOs 45 | setupDatabase(connectionSource); 46 | // read and write some data 47 | readWriteData(); 48 | System.out.println("\n\nIt seems to have worked\n\n"); 49 | } finally { 50 | // destroy the data source which should close underlying connections 51 | if (connectionSource != null) { 52 | connectionSource.close(); 53 | } 54 | } 55 | } 56 | 57 | /** 58 | * Setup our database and DAOs 59 | */ 60 | private void setupDatabase(ConnectionSource connectionSource) throws Exception { 61 | 62 | DatabaseType databaseType = connectionSource.getDatabaseType(); 63 | DatabaseTableConfig accountTableConfig = buildAccountTableConfig(databaseType); 64 | accountDao = DaoManager.createDao(connectionSource, accountTableConfig); 65 | 66 | DatabaseTableConfig deliveryTableConfig = buildDeliveryTableConfig(databaseType, accountTableConfig); 67 | deliveryDao = DaoManager.createDao(connectionSource, deliveryTableConfig); 68 | 69 | // if you need to create the table 70 | TableUtils.createTable(connectionSource, accountTableConfig); 71 | TableUtils.createTable(connectionSource, deliveryTableConfig); 72 | } 73 | 74 | private DatabaseTableConfig buildAccountTableConfig(DatabaseType databaseType) { 75 | ArrayList fieldConfigs = new ArrayList(); 76 | DatabaseFieldConfig fieldConfig = new DatabaseFieldConfig("id"); 77 | fieldConfig.setGeneratedId(true); 78 | fieldConfigs.add(fieldConfig); 79 | fieldConfigs.add(new DatabaseFieldConfig("name")); 80 | fieldConfig = new DatabaseFieldConfig("password"); 81 | fieldConfig.setCanBeNull(true); 82 | fieldConfigs.add(fieldConfig); 83 | DatabaseTableConfig tableConfig = 84 | new DatabaseTableConfig(databaseType, Account.class, fieldConfigs); 85 | return tableConfig; 86 | } 87 | 88 | private DatabaseTableConfig buildDeliveryTableConfig(DatabaseType databaseType, 89 | DatabaseTableConfig accountTableConfig) { 90 | ArrayList fieldConfigs = new ArrayList(); 91 | DatabaseFieldConfig fieldConfig = new DatabaseFieldConfig("id"); 92 | fieldConfig.setGeneratedId(true); 93 | fieldConfigs.add(fieldConfig); 94 | fieldConfigs.add(new DatabaseFieldConfig("when")); 95 | fieldConfigs.add(new DatabaseFieldConfig("signedBy")); 96 | fieldConfig = new DatabaseFieldConfig("account"); 97 | fieldConfig.setForeign(true); 98 | fieldConfig.setForeignTableConfig(accountTableConfig); 99 | fieldConfigs.add(fieldConfig); 100 | DatabaseTableConfig tableConfig = 101 | new DatabaseTableConfig(databaseType, Delivery.class, fieldConfigs); 102 | return tableConfig; 103 | } 104 | 105 | /** 106 | * Read and write some example data. 107 | */ 108 | private void readWriteData() throws Exception { 109 | // create an instance of Account 110 | String name = "Jim Coakley"; 111 | Account account = new Account(name); 112 | // persist the account object to the database 113 | accountDao.create(account); 114 | 115 | Delivery delivery = new Delivery(new Date(), "Mr. Ed", account); 116 | // persist the account object to the database 117 | deliveryDao.create(delivery); 118 | 119 | Delivery delivery2 = deliveryDao.queryForId(delivery.getId()); 120 | assertNotNull(delivery2); 121 | assertEquals(delivery.getId(), delivery2.getId()); 122 | assertEquals(account.getId(), delivery2.getAccount().getId()); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/fieldConfig/README.txt: -------------------------------------------------------------------------------- 1 | This shows how to configure a class using Java code instead of annotations. 2 | 3 | See the documentation for more information about how to configure classes: 4 | 5 | http://ormlite.com/docs/class-config 6 | 7 | This example depends on the H2 database which is a native Java SQL implementation. You 8 | can download the latest jar from the website: 9 | 10 | http://www.h2database.com/html/download.html 11 | 12 | For more examples see: http://ormlite.com/docs/examples 13 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreign/Account.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.foreign; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | import com.j256.ormlite.table.DatabaseTable; 5 | 6 | /** 7 | * Example account object that is persisted to disk by the DAO and other example classes. 8 | */ 9 | @DatabaseTable(tableName = "accounts") 10 | public class Account { 11 | 12 | // for QueryBuilder to be able to find the fields 13 | public static final String NAME_FIELD_NAME = "name"; 14 | public static final String PASSWORD_FIELD_NAME = "passwd"; 15 | 16 | @DatabaseField(generatedId = true) 17 | private int id; 18 | 19 | @DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false) 20 | private String name; 21 | 22 | @DatabaseField(columnName = PASSWORD_FIELD_NAME) 23 | private String password; 24 | 25 | Account() { 26 | // all persisted classes must define a no-arg constructor with at least package visibility 27 | } 28 | 29 | public Account(String name) { 30 | this.name = name; 31 | } 32 | 33 | public Account(String name, String password) { 34 | this.name = name; 35 | this.password = password; 36 | } 37 | 38 | public int getId() { 39 | return id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | public String getPassword() { 51 | return password; 52 | } 53 | 54 | public void setPassword(String password) { 55 | this.password = password; 56 | } 57 | 58 | @Override 59 | public int hashCode() { 60 | return name.hashCode(); 61 | } 62 | 63 | @Override 64 | public boolean equals(Object other) { 65 | if (other == null || other.getClass() != getClass()) { 66 | return false; 67 | } 68 | return name.equals(((Account) other).name); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreign/ForeignMain.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.foreign; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNull; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.util.List; 8 | 9 | import com.j256.ormlite.dao.Dao; 10 | import com.j256.ormlite.dao.DaoManager; 11 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 12 | import com.j256.ormlite.stmt.QueryBuilder; 13 | import com.j256.ormlite.support.ConnectionSource; 14 | import com.j256.ormlite.table.TableUtils; 15 | 16 | /** 17 | * Main sample routine to show how to do basic operations with the package. 18 | * 19 | *

20 | * NOTE: We use asserts in a couple of places to verify the results but if this were actual production code, we 21 | * would have proper error handling. 22 | *

23 | */ 24 | public class ForeignMain { 25 | 26 | // we are using the in-memory H2 database 27 | private final static String DATABASE_URL = "jdbc:h2:mem:account"; 28 | 29 | private Dao accountDao; 30 | private Dao orderDao; 31 | 32 | public static void main(String[] args) throws Exception { 33 | // turn our static method into an instance of Main 34 | new ForeignMain().doMain(args); 35 | } 36 | 37 | private void doMain(String[] args) throws Exception { 38 | JdbcConnectionSource connectionSource = null; 39 | try { 40 | // create our data source 41 | connectionSource = new JdbcConnectionSource(DATABASE_URL); 42 | // setup our database and DAOs 43 | setupDatabase(connectionSource); 44 | // read and write some data 45 | readWriteData(); 46 | System.out.println("\n\nIt seems to have worked\n\n"); 47 | } finally { 48 | // destroy the data source which should close underlying connections 49 | if (connectionSource != null) { 50 | connectionSource.close(); 51 | } 52 | } 53 | } 54 | 55 | /** 56 | * Setup our database and DAOs 57 | */ 58 | private void setupDatabase(ConnectionSource connectionSource) throws Exception { 59 | 60 | accountDao = DaoManager.createDao(connectionSource, Account.class); 61 | orderDao = DaoManager.createDao(connectionSource, Order.class); 62 | 63 | // if you need to create the table 64 | TableUtils.createTable(connectionSource, Account.class); 65 | TableUtils.createTable(connectionSource, Order.class); 66 | } 67 | 68 | private void readWriteData() throws Exception { 69 | // create an instance of Account 70 | String name = "Buzz Lightyear"; 71 | Account account = new Account(name); 72 | 73 | // persist the account object to the database 74 | accountDao.create(account); 75 | 76 | // create an associated Order for the Account 77 | // Buzz bought 2 of item #21312 for a price of $12.32 78 | int quantity1 = 2; 79 | int itemNumber1 = 21312; 80 | float price1 = 12.32F; 81 | Order order1 = new Order(account, itemNumber1, price1, quantity1); 82 | orderDao.create(order1); 83 | 84 | // create another Order for the Account 85 | // Buzz also bought 1 of item #785 for a price of $7.98 86 | int quantity2 = 1; 87 | int itemNumber2 = 785; 88 | float price2 = 7.98F; 89 | Order order2 = new Order(account, itemNumber2, price2, quantity2); 90 | orderDao.create(order2); 91 | 92 | // construct a query using the QueryBuilder 93 | QueryBuilder statementBuilder = orderDao.queryBuilder(); 94 | // should find both of the orders that match the account 95 | // ORMLite extracts the id from the account for the query automagically 96 | statementBuilder.where().eq(Order.ACCOUNT_ID_FIELD_NAME, account); 97 | List orders = orderDao.query(statementBuilder.prepare()); 98 | 99 | // sanity checks 100 | assertEquals(2, orders.size(), "Should have found both of the orders for the account"); 101 | assertTrue(orderDao.objectsEqual(order1, orders.get(0))); 102 | assertTrue(orderDao.objectsEqual(order2, orders.get(1))); 103 | 104 | /* 105 | * Notice that in each of the orders that we got from the query, the Account id is good but the name field is 106 | * null. With foreign object fields, only the id field is stored in the table for the order. 107 | */ 108 | assertEquals(account.getId(), orders.get(0).getAccount().getId()); 109 | assertEquals(account.getId(), orders.get(1).getAccount().getId()); 110 | assertNull(orders.get(0).getAccount().getName()); 111 | assertNull(orders.get(1).getAccount().getName()); 112 | 113 | /* 114 | * To get the name field from the order's account field, we need to refresh each of the objects in the list 115 | * which will lookup the id and load in all of the fields. 116 | */ 117 | assertEquals(1, accountDao.refresh(orders.get(0).getAccount())); 118 | assertEquals(1, accountDao.refresh(orders.get(1).getAccount())); 119 | 120 | // now the account name field has been filled in 121 | assertEquals(account.getName(), orders.get(0).getAccount().getName()); 122 | assertEquals(account.getName(), orders.get(1).getAccount().getName()); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreign/Order.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.foreign; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | import com.j256.ormlite.table.DatabaseTable; 5 | 6 | /** 7 | * Example order object that is persisted to disk by the DAO and other example classes. 8 | */ 9 | @DatabaseTable(tableName = "orders") 10 | public class Order { 11 | 12 | public static final String ACCOUNT_ID_FIELD_NAME = "account_id"; 13 | 14 | @DatabaseField(generatedId = true) 15 | private int id; 16 | 17 | @DatabaseField(foreign = true, columnName = ACCOUNT_ID_FIELD_NAME) 18 | private Account account; 19 | 20 | @DatabaseField 21 | private int itemNumber; 22 | 23 | @DatabaseField 24 | private int quantity; 25 | 26 | @DatabaseField 27 | private float price; 28 | 29 | Order() { 30 | // all persisted classes must define a no-arg constructor with at least package visibility 31 | } 32 | 33 | public Order(Account account, int itemNumber, float price, int quantity) { 34 | this.account = account; 35 | this.itemNumber = itemNumber; 36 | this.price = price; 37 | this.quantity = quantity; 38 | } 39 | 40 | public int getId() { 41 | return id; 42 | } 43 | 44 | public Account getAccount() { 45 | return account; 46 | } 47 | 48 | public void setAccount(Account account) { 49 | this.account = account; 50 | } 51 | 52 | public int getItemNumber() { 53 | return itemNumber; 54 | } 55 | 56 | public void setItemNumber(int itemNumber) { 57 | this.itemNumber = itemNumber; 58 | } 59 | 60 | public int getQuantity() { 61 | return quantity; 62 | } 63 | 64 | public void setQuantity(int quantity) { 65 | this.quantity = quantity; 66 | } 67 | 68 | public float getPrice() { 69 | return price; 70 | } 71 | 72 | public void setPrice(float price) { 73 | this.price = price; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreign/README.txt: -------------------------------------------------------------------------------- 1 | This shows how to persist a Order class which has a foreign Account object as one of its fields. 2 | 3 | ORMLite supports what it calls "foreign" objects. These are fields that are other objects 4 | stored in the database. For example, if you have Account and Order objects in your database, 5 | the Order objects may have an associated Account so would have an foreign Account field. See 6 | the documentation for more information: 7 | 8 | http://ormlite.com/docs/foreign 9 | 10 | You may also want to learn about Foreign Collections which use foreign fields: 11 | 12 | http://ormlite.com/docs/foreign-collection 13 | 14 | Also, the many-to-many example also foreign objects in combination with a join table. 15 | 16 | http://ormlite.com/docs/example-many 17 | 18 | This example depends on the H2 database which is a native Java SQL implementation. You can 19 | download the latest jar from the website: 20 | 21 | http://www.h2database.com/html/download.html 22 | 23 | For more examples see: http://ormlite.com/docs/examples 24 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreignCollection/Account.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.foreignCollection; 2 | 3 | import com.j256.ormlite.dao.ForeignCollection; 4 | import com.j256.ormlite.field.DatabaseField; 5 | import com.j256.ormlite.field.ForeignCollectionField; 6 | import com.j256.ormlite.table.DatabaseTable; 7 | 8 | /** 9 | * Example account object that is persisted to disk by the DAO and other example classes. 10 | */ 11 | @DatabaseTable(tableName = "accounts") 12 | public class Account { 13 | 14 | // for QueryBuilder to be able to find the fields 15 | public static final String NAME_FIELD_NAME = "name"; 16 | public static final String PASSWORD_FIELD_NAME = "passwd"; 17 | 18 | @DatabaseField(generatedId = true) 19 | private int id; 20 | 21 | @DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false) 22 | private String name; 23 | 24 | @DatabaseField(columnName = PASSWORD_FIELD_NAME) 25 | private String password; 26 | 27 | @ForeignCollectionField 28 | private ForeignCollection orders; 29 | 30 | Account() { 31 | // all persisted classes must define a no-arg constructor with at least package visibility 32 | } 33 | 34 | public Account(String name) { 35 | this.name = name; 36 | } 37 | 38 | public Account(String name, String password) { 39 | this.name = name; 40 | this.password = password; 41 | } 42 | 43 | public int getId() { 44 | return id; 45 | } 46 | 47 | public String getName() { 48 | return name; 49 | } 50 | 51 | public void setName(String name) { 52 | this.name = name; 53 | } 54 | 55 | public String getPassword() { 56 | return password; 57 | } 58 | 59 | public void setPassword(String password) { 60 | this.password = password; 61 | } 62 | 63 | public ForeignCollection getOrders() { 64 | return orders; 65 | } 66 | 67 | @Override 68 | public int hashCode() { 69 | return name.hashCode(); 70 | } 71 | 72 | @Override 73 | public boolean equals(Object other) { 74 | if (other == null || other.getClass() != getClass()) { 75 | return false; 76 | } 77 | return name.equals(((Account) other).name); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreignCollection/ForeignCollectionMain.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.foreignCollection; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertSame; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | import java.util.List; 9 | 10 | import com.j256.ormlite.dao.CloseableIterator; 11 | import com.j256.ormlite.dao.Dao; 12 | import com.j256.ormlite.dao.DaoManager; 13 | import com.j256.ormlite.dao.ForeignCollection; 14 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 15 | import com.j256.ormlite.support.ConnectionSource; 16 | import com.j256.ormlite.table.TableUtils; 17 | 18 | /** 19 | * Main sample routine to show how to do basic operations with the package. 20 | * 21 | *

22 | * NOTE: We use asserts in a couple of places to verify the results but if this were actual production code, we 23 | * would have proper error handling. 24 | *

25 | */ 26 | public class ForeignCollectionMain { 27 | 28 | // we are using the in-memory H2 database 29 | private final static String DATABASE_URL = "jdbc:h2:mem:account"; 30 | 31 | private Dao accountDao; 32 | private Dao orderDao; 33 | 34 | public static void main(String[] args) throws Exception { 35 | // turn our static method into an instance of Main 36 | new ForeignCollectionMain().doMain(args); 37 | } 38 | 39 | private void doMain(String[] args) throws Exception { 40 | JdbcConnectionSource connectionSource = null; 41 | try { 42 | // create our data source 43 | connectionSource = new JdbcConnectionSource(DATABASE_URL); 44 | // setup our database and DAOs 45 | setupDatabase(connectionSource); 46 | // read and write some data 47 | readWriteData(); 48 | System.out.println("\n\nIt seems to have worked\n\n"); 49 | } finally { 50 | // destroy the data source which should close underlying connections 51 | if (connectionSource != null) { 52 | connectionSource.close(); 53 | } 54 | } 55 | } 56 | 57 | /** 58 | * Setup our database and DAOs 59 | */ 60 | private void setupDatabase(ConnectionSource connectionSource) throws Exception { 61 | 62 | accountDao = DaoManager.createDao(connectionSource, Account.class); 63 | orderDao = DaoManager.createDao(connectionSource, Order.class); 64 | 65 | // if you need to create the table 66 | TableUtils.createTable(connectionSource, Account.class); 67 | TableUtils.createTable(connectionSource, Order.class); 68 | } 69 | 70 | private void readWriteData() throws Exception { 71 | // create an instance of Account 72 | String name = "Buzz Lightyear"; 73 | Account account = new Account(name); 74 | 75 | // persist the account object to the database 76 | accountDao.create(account); 77 | 78 | // create an associated Order for the Account 79 | // Buzz bought 2 of item #21312 for a price of $12.32 80 | int quantity1 = 2; 81 | int itemNumber1 = 21312; 82 | float price1 = 12.32F; 83 | Order order1 = new Order(account, itemNumber1, price1, quantity1); 84 | orderDao.create(order1); 85 | 86 | // create another Order for the Account 87 | // Buzz also bought 1 of item #785 for a price of $7.98 88 | int quantity2 = 1; 89 | int itemNumber2 = 785; 90 | float price2 = 7.98F; 91 | Order order2 = new Order(account, itemNumber2, price2, quantity2); 92 | orderDao.create(order2); 93 | 94 | Account accountResult = accountDao.queryForId(account.getId()); 95 | ForeignCollection orders = accountResult.getOrders(); 96 | 97 | // sanity checks 98 | CloseableIterator iterator = orders.closeableIterator(); 99 | try { 100 | assertTrue(iterator.hasNext()); 101 | Order order = iterator.next(); 102 | assertEquals(itemNumber1, order.getItemNumber()); 103 | assertSame(accountResult, order.getAccount()); 104 | assertTrue(iterator.hasNext()); 105 | order = iterator.next(); 106 | assertEquals(itemNumber2, order.getItemNumber()); 107 | assertFalse(iterator.hasNext()); 108 | } finally { 109 | // must always close our iterators otherwise connections to the database are held open 110 | iterator.close(); 111 | } 112 | 113 | // create another Order for the Account 114 | // Buzz also bought 1 of item #785 for a price of $7.98 115 | int quantity3 = 50; 116 | int itemNumber3 = 78315; 117 | float price3 = 72.98F; 118 | Order order3 = new Order(account, itemNumber3, price3, quantity3); 119 | 120 | // now let's add this order via the foreign collection 121 | orders.add(order3); 122 | // now there are 3 of them in there 123 | assertEquals(3, orders.size()); 124 | 125 | List orderList = orderDao.queryForAll(); 126 | // and 3 in the database 127 | assertEquals(3, orderList.size()); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreignCollection/Order.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.foreignCollection; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | import com.j256.ormlite.table.DatabaseTable; 5 | 6 | /** 7 | * Example order object that is persisted to disk by the DAO and other example classes. 8 | */ 9 | @DatabaseTable(tableName = "orders") 10 | public class Order { 11 | 12 | public static final String ACCOUNT_ID_FIELD_NAME = "account_id"; 13 | 14 | @DatabaseField(generatedId = true) 15 | private int id; 16 | 17 | @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = ACCOUNT_ID_FIELD_NAME) 18 | private Account account; 19 | 20 | @DatabaseField 21 | private int itemNumber; 22 | 23 | @DatabaseField 24 | private int quantity; 25 | 26 | @DatabaseField 27 | private float price; 28 | 29 | Order() { 30 | // all persisted classes must define a no-arg constructor with at least package visibility 31 | } 32 | 33 | public Order(Account account, int itemNumber, float price, int quantity) { 34 | this.account = account; 35 | this.itemNumber = itemNumber; 36 | this.price = price; 37 | this.quantity = quantity; 38 | } 39 | 40 | public int getId() { 41 | return id; 42 | } 43 | 44 | public Account getAccount() { 45 | return account; 46 | } 47 | 48 | public void setAccount(Account account) { 49 | this.account = account; 50 | } 51 | 52 | public int getItemNumber() { 53 | return itemNumber; 54 | } 55 | 56 | public void setItemNumber(int itemNumber) { 57 | this.itemNumber = itemNumber; 58 | } 59 | 60 | public int getQuantity() { 61 | return quantity; 62 | } 63 | 64 | public void setQuantity(int quantity) { 65 | this.quantity = quantity; 66 | } 67 | 68 | public float getPrice() { 69 | return price; 70 | } 71 | 72 | public void setPrice(float price) { 73 | this.price = price; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/foreignCollection/README.txt: -------------------------------------------------------------------------------- 1 | This is similar to the "foreign" example, but this shows how to use "foreign collections". 2 | 3 | Foreign collections are collections of objects in other tables that match the current 4 | object. For example, if you have Account and Order objects in your database, the Order 5 | objects may have an associated Account so would have an foreign Account field. With 6 | foreign objects, the Account can have a Collection of orders that match the account. See 7 | the documentation for more information: 8 | 9 | http://ormlite.com/docs/foreign-collection 10 | 11 | This example depends on the H2 database which is a native Java SQL implementation. You 12 | can download the latest jar from the website: 13 | 14 | http://www.h2database.com/html/download.html 15 | 16 | For more examples see: http://ormlite.com/docs/examples 17 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/manytomany/ManyToManyMain.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.manytomany; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.sql.SQLException; 6 | import java.util.List; 7 | 8 | import com.j256.ormlite.dao.Dao; 9 | import com.j256.ormlite.dao.DaoManager; 10 | import com.j256.ormlite.jdbc.JdbcConnectionSource; 11 | import com.j256.ormlite.stmt.PreparedQuery; 12 | import com.j256.ormlite.stmt.QueryBuilder; 13 | import com.j256.ormlite.stmt.SelectArg; 14 | import com.j256.ormlite.support.ConnectionSource; 15 | import com.j256.ormlite.table.TableUtils; 16 | 17 | /** 18 | * Main sample routine to show how to do many-to-many type relationships. It also demonstrates how we user inner queries 19 | * as well foreign objects. 20 | * 21 | *

22 | * NOTE: We use asserts in a couple of places to verify the results but if this were actual production code, we 23 | * would have proper error handling. 24 | *

25 | */ 26 | public class ManyToManyMain { 27 | 28 | // we are using the in-memory H2 database 29 | private final static String DATABASE_URL = "jdbc:h2:mem:manytomany"; 30 | 31 | private Dao userDao; 32 | private Dao postDao; 33 | private Dao userPostDao; 34 | 35 | public static void main(String[] args) throws Exception { 36 | // turn our static method into an instance of Main 37 | new ManyToManyMain().doMain(args); 38 | } 39 | 40 | private void doMain(String[] args) throws Exception { 41 | JdbcConnectionSource connectionSource = null; 42 | try { 43 | // create our data-source for the database 44 | connectionSource = new JdbcConnectionSource(DATABASE_URL); 45 | // setup our database and DAOs 46 | setupDatabase(connectionSource); 47 | // read and write some data 48 | readWriteData(); 49 | System.out.println("\n\nIt seems to have worked\n\n"); 50 | } finally { 51 | // destroy the data source which should close underlying connections 52 | if (connectionSource != null) { 53 | connectionSource.close(); 54 | } 55 | } 56 | } 57 | 58 | /** 59 | * Setup our database and DAOs 60 | */ 61 | private void setupDatabase(ConnectionSource connectionSource) throws Exception { 62 | 63 | /** 64 | * Create our DAOs. One for each class and associated table. 65 | */ 66 | userDao = DaoManager.createDao(connectionSource, User.class); 67 | postDao = DaoManager.createDao(connectionSource, Post.class); 68 | userPostDao = DaoManager.createDao(connectionSource, UserPost.class); 69 | 70 | /** 71 | * Create the tables for our example. This would not be necessary if the tables already existed. 72 | */ 73 | TableUtils.createTable(connectionSource, User.class); 74 | TableUtils.createTable(connectionSource, Post.class); 75 | TableUtils.createTable(connectionSource, UserPost.class); 76 | } 77 | 78 | /** 79 | * Read and write some example data. 80 | */ 81 | private void readWriteData() throws Exception { 82 | 83 | // create our 1st user 84 | User user1 = new User("Jim Coakley"); 85 | 86 | // persist the user object to the database 87 | userDao.create(user1); 88 | 89 | // have user1 post something 90 | Post post1 = new Post("Wow is it cold outside!!"); 91 | // save the post to the post table 92 | postDao.create(post1); 93 | 94 | // link the user and the post together in the join table 95 | UserPost user1Post1 = new UserPost(user1, post1); 96 | userPostDao.create(user1Post1); 97 | 98 | // have user1 post a second post 99 | Post post2 = new Post("Now it's a bit warmer thank goodness."); 100 | postDao.create(post2); 101 | UserPost user1Post2 = new UserPost(user1, post2); 102 | userPostDao.create(user1Post2); 103 | 104 | // create another user 105 | User user2 = new User("Rose Gray"); 106 | userDao.create(user2); 107 | 108 | // have the 2nd user also say the 2nd post 109 | UserPost user2Post1 = new UserPost(user2, post2); 110 | userPostDao.create(user2Post1); 111 | 112 | /* 113 | * Now go back and do various queries to look things up. 114 | */ 115 | 116 | /* 117 | * show me all of a user's posts: 118 | */ 119 | // user1 should have 2 posts 120 | List posts = lookupPostsForUser(user1); 121 | assertEquals(2, posts.size()); 122 | assertEquals(post1.id, posts.get(0).id); 123 | assertEquals(post1.contents, posts.get(0).contents); 124 | assertEquals(post2.id, posts.get(1).id); 125 | assertEquals(post2.contents, posts.get(1).contents); 126 | 127 | // user2 should have only 1 post 128 | posts = lookupPostsForUser(user2); 129 | assertEquals(1, posts.size()); 130 | assertEquals(post2.contents, posts.get(0).contents); 131 | 132 | /* 133 | * show me all of the users that have a post. 134 | */ 135 | // post1 should only have 1 corresponding user 136 | List users = lookupUsersForPost(post1); 137 | assertEquals(1, users.size()); 138 | assertEquals(user1.id, users.get(0).id); 139 | 140 | // post2 should have 2 corresponding users 141 | users = lookupUsersForPost(post2); 142 | assertEquals(2, users.size()); 143 | assertEquals(user1.id, users.get(0).id); 144 | assertEquals(user1.name, users.get(0).name); 145 | assertEquals(user2.id, users.get(1).id); 146 | assertEquals(user2.name, users.get(1).name); 147 | } 148 | 149 | /* 150 | * Convenience methods to build and run our prepared queries. 151 | */ 152 | 153 | private PreparedQuery postsForUserQuery = null; 154 | private PreparedQuery usersForPostQuery = null; 155 | 156 | private List lookupPostsForUser(User user) throws SQLException { 157 | if (postsForUserQuery == null) { 158 | postsForUserQuery = makePostsForUserQuery(); 159 | } 160 | postsForUserQuery.setArgumentHolderValue(0, user); 161 | return postDao.query(postsForUserQuery); 162 | } 163 | 164 | private List lookupUsersForPost(Post post) throws SQLException { 165 | if (usersForPostQuery == null) { 166 | usersForPostQuery = makeUsersForPostQuery(); 167 | } 168 | usersForPostQuery.setArgumentHolderValue(0, post); 169 | return userDao.query(usersForPostQuery); 170 | } 171 | 172 | /** 173 | * Build our query for Post objects that match a User. 174 | */ 175 | private PreparedQuery makePostsForUserQuery() throws SQLException { 176 | // build our inner query for UserPost objects 177 | QueryBuilder userPostQb = userPostDao.queryBuilder(); 178 | // just select the post-id field 179 | userPostQb.selectColumns(UserPost.POST_ID_FIELD_NAME); 180 | SelectArg userSelectArg = new SelectArg(); 181 | // you could also just pass in user1 here 182 | userPostQb.where().eq(UserPost.USER_ID_FIELD_NAME, userSelectArg); 183 | 184 | // build our outer query for Post objects 185 | QueryBuilder postQb = postDao.queryBuilder(); 186 | // where the id matches in the post-id from the inner query 187 | postQb.where().in(Post.ID_FIELD_NAME, userPostQb); 188 | return postQb.prepare(); 189 | } 190 | 191 | /** 192 | * Build our query for User objects that match a Post 193 | */ 194 | private PreparedQuery makeUsersForPostQuery() throws SQLException { 195 | QueryBuilder userPostQb = userPostDao.queryBuilder(); 196 | // this time selecting for the user-id field 197 | userPostQb.selectColumns(UserPost.USER_ID_FIELD_NAME); 198 | SelectArg postSelectArg = new SelectArg(); 199 | userPostQb.where().eq(UserPost.POST_ID_FIELD_NAME, postSelectArg); 200 | 201 | // build our outer query 202 | QueryBuilder userQb = userDao.queryBuilder(); 203 | // where the user-id matches the inner query's user-id field 204 | userQb.where().in(Post.ID_FIELD_NAME, userPostQb); 205 | return userQb.prepare(); 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/manytomany/Post.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.manytomany; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | 5 | /** 6 | * Post to some blog with String content. 7 | */ 8 | public class Post { 9 | 10 | // we use this field-name so we can query for posts with a certain id 11 | public final static String ID_FIELD_NAME = "id"; 12 | 13 | // this id is generated by the database and set on the object when it is passed to the create method 14 | @DatabaseField(generatedId = true, columnName = ID_FIELD_NAME) 15 | int id; 16 | 17 | // contents of the post 18 | @DatabaseField 19 | String contents; 20 | 21 | Post() { 22 | // for ormlite 23 | } 24 | 25 | public Post(String contents) { 26 | this.contents = contents; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/manytomany/README.txt: -------------------------------------------------------------------------------- 1 | This shows how you can use a join table to implement many-to-many type of object layout. 2 | 3 | This example depends on the H2 database which is a native Java SQL implementation. You 4 | can download the latest jar from the website: 5 | 6 | http://www.h2database.com/html/download.html 7 | 8 | For more examples see: http://ormlite.com/docs/examples 9 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/manytomany/User.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.manytomany; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | 5 | /** 6 | * A user object with a name. 7 | */ 8 | public class User { 9 | 10 | // we use this field-name so we can query for users with a certain id 11 | public final static String ID_FIELD_NAME = "id"; 12 | 13 | // this id is generated by the database and set on the object when it is passed to the create method 14 | @DatabaseField(generatedId = true, columnName = ID_FIELD_NAME) 15 | int id; 16 | 17 | @DatabaseField 18 | String name; 19 | 20 | User() { 21 | // for ormlite 22 | } 23 | 24 | public User(String name) { 25 | this.name = name; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/manytomany/UserPost.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.manytomany; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | 5 | /** 6 | * Join table which links users to their posts. 7 | * 8 | *

9 | * For more information about foreign objects, see the online docs 10 | *

11 | */ 12 | public class UserPost { 13 | 14 | public final static String USER_ID_FIELD_NAME = "user_id"; 15 | public final static String POST_ID_FIELD_NAME = "post_id"; 16 | 17 | /** 18 | * This id is generated by the database and set on the object when it is passed to the create method. An id is 19 | * needed in case we need to update or delete this object in the future. 20 | */ 21 | @DatabaseField(generatedId = true) 22 | int id; 23 | 24 | // This is a foreign object which just stores the id from the User object in this table. 25 | @DatabaseField(foreign = true, columnName = USER_ID_FIELD_NAME) 26 | User user; 27 | 28 | // This is a foreign object which just stores the id from the Post object in this table. 29 | @DatabaseField(foreign = true, columnName = POST_ID_FIELD_NAME) 30 | Post post; 31 | 32 | UserPost() { 33 | // for ormlite 34 | } 35 | 36 | public UserPost(User user, Post post) { 37 | this.user = user; 38 | this.post = post; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/simple/Account.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.examples.simple; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | import com.j256.ormlite.table.DatabaseTable; 5 | 6 | /** 7 | * Example account object that is persisted to disk by the DAO and other example classes. 8 | */ 9 | @DatabaseTable(tableName = "accounts") 10 | public class Account { 11 | 12 | // for QueryBuilder to be able to find the fields 13 | public static final String NAME_FIELD_NAME = "name"; 14 | public static final String PASSWORD_FIELD_NAME = "passwd"; 15 | 16 | @DatabaseField(generatedId = true) 17 | private int id; 18 | 19 | @DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false) 20 | private String name; 21 | 22 | @DatabaseField(columnName = PASSWORD_FIELD_NAME) 23 | private String password; 24 | 25 | Account() { 26 | // all persisted classes must define a no-arg constructor with at least package visibility 27 | } 28 | 29 | public Account(String name) { 30 | this.name = name; 31 | } 32 | 33 | public Account(String name, String password) { 34 | this.name = name; 35 | this.password = password; 36 | } 37 | 38 | public int getId() { 39 | return id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | public String getPassword() { 51 | return password; 52 | } 53 | 54 | public void setPassword(String password) { 55 | this.password = password; 56 | } 57 | 58 | @Override 59 | public int hashCode() { 60 | return name.hashCode(); 61 | } 62 | 63 | @Override 64 | public boolean equals(Object other) { 65 | if (other == null || other.getClass() != getClass()) { 66 | return false; 67 | } 68 | return name.equals(((Account) other).name); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/examples/simple/README.txt: -------------------------------------------------------------------------------- 1 | This shows how to persist a simple, single class using the package. 2 | 3 | This example depends on the H2 database which is a native Java SQL implementation. 4 | You can download the latest jar from the website: 5 | 6 | http://www.h2database.com/html/download.html 7 | 8 | For more examples see: http://ormlite.com/docs/examples 9 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/misc/JdbcTransactionManagerTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.misc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNotNull; 5 | import static org.junit.jupiter.api.Assertions.assertNull; 6 | import static org.junit.jupiter.api.Assertions.fail; 7 | 8 | import java.sql.SQLException; 9 | import java.util.concurrent.Callable; 10 | 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.Test; 13 | 14 | import com.j256.ormlite.dao.Dao; 15 | import com.j256.ormlite.field.DatabaseField; 16 | import com.j256.ormlite.jdbc.BaseJdbcTest; 17 | import com.j256.ormlite.jdbc.JdbcPooledConnectionSource; 18 | import com.j256.ormlite.misc.TransactionManager; 19 | 20 | /** 21 | * This is a base class for the per-database tests and can't be rolled into -core. 22 | */ 23 | public class JdbcTransactionManagerTest extends BaseJdbcTest { 24 | 25 | @Override 26 | @BeforeEach 27 | public void before() throws Exception { 28 | if (connectionSource != null) { 29 | return; 30 | } 31 | super.before(); 32 | if (connectionSource != null) { 33 | connectionSource = new JdbcPooledConnectionSource(databaseUrl, userName, password); 34 | } 35 | } 36 | 37 | /* ============================================================================================================== */ 38 | 39 | @Test 40 | public void testDaoTransactionManagerCommitted() throws Exception { 41 | if (connectionSource == null) { 42 | return; 43 | } 44 | TransactionManager mgr = new TransactionManager(connectionSource); 45 | final Dao fooDao = createDao(Foo.class, true); 46 | testTransactionManager(mgr, null, fooDao); 47 | } 48 | 49 | @Test 50 | public void testRollBack() throws Exception { 51 | if (connectionSource == null) { 52 | return; 53 | } 54 | TransactionManager mgr = new TransactionManager(connectionSource); 55 | final Dao fooDao = createDao(Foo.class, true); 56 | testTransactionManager(mgr, new RuntimeException("What!! I protest!!"), fooDao); 57 | } 58 | 59 | @Test 60 | public void testSpringWiredRollBack() throws Exception { 61 | if (connectionSource == null) { 62 | return; 63 | } 64 | TransactionManager mgr = new TransactionManager(); 65 | mgr.setConnectionSource(connectionSource); 66 | mgr.initialize(); 67 | final Dao fooDao = createDao(Foo.class, true); 68 | testTransactionManager(mgr, new RuntimeException("What!! I protest!!"), fooDao); 69 | } 70 | 71 | @Test 72 | public void testNonRuntimeExceptionWiredRollBack() throws Exception { 73 | if (connectionSource == null) { 74 | return; 75 | } 76 | TransactionManager mgr = new TransactionManager(); 77 | mgr.setConnectionSource(connectionSource); 78 | mgr.initialize(); 79 | final Dao fooDao = createDao(Foo.class, true); 80 | testTransactionManager(mgr, new Exception("What!! I protest via an Exception!!"), fooDao); 81 | } 82 | 83 | @Test 84 | public void testTransactionWithinTransaction() throws Exception { 85 | if (connectionSource == null) { 86 | return; 87 | } 88 | final TransactionManager mgr = new TransactionManager(connectionSource); 89 | final Dao fooDao = createDao(Foo.class, true); 90 | mgr.callInTransaction(new Callable() { 91 | @Override 92 | public Void call() throws Exception { 93 | testTransactionManager(mgr, null, fooDao); 94 | return null; 95 | } 96 | }); 97 | } 98 | 99 | private void testTransactionManager(TransactionManager mgr, final Exception exception, 100 | final Dao fooDao) throws Exception { 101 | final Foo foo1 = new Foo(); 102 | String stuff = "stuff"; 103 | foo1.stuff = stuff; 104 | assertEquals(1, fooDao.create(foo1)); 105 | try { 106 | final int val = 13431231; 107 | int returned = mgr.callInTransaction(new Callable() { 108 | @Override 109 | public Integer call() throws Exception { 110 | // we delete it inside a transaction 111 | assertEquals(1, fooDao.delete(foo1)); 112 | // we can't find it 113 | assertNull(fooDao.queryForId(foo1.id)); 114 | if (exception != null) { 115 | // but then we throw an exception which rolls back the transaction 116 | throw exception; 117 | } else { 118 | return val; 119 | } 120 | } 121 | }); 122 | if (exception == null) { 123 | assertEquals(val, returned); 124 | } else { 125 | fail("Should have thrown"); 126 | } 127 | } catch (SQLException e) { 128 | if (exception == null) { 129 | throw e; 130 | } else { 131 | // expected 132 | } 133 | } 134 | 135 | if (exception == null) { 136 | // still doesn't find it after we delete it 137 | assertNull(fooDao.queryForId(foo1.id)); 138 | } else { 139 | // still finds it after we delete it 140 | Foo foo2 = fooDao.queryForId(foo1.id); 141 | assertNotNull(foo2); 142 | assertEquals(stuff, foo2.stuff); 143 | } 144 | } 145 | 146 | public static class Foo { 147 | @DatabaseField(generatedId = true) 148 | int id; 149 | @DatabaseField 150 | String stuff; 151 | 152 | Foo() { 153 | // for ormlite 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/spring/DaoFactoryTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.spring; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNotNull; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | import com.j256.ormlite.BaseCoreTest; 9 | import com.j256.ormlite.dao.Dao; 10 | import com.j256.ormlite.table.DatabaseTableConfig; 11 | 12 | public class DaoFactoryTest extends BaseCoreTest { 13 | 14 | @Test 15 | public void testCreateDaoConnectionSourceClassOfT() throws Exception { 16 | createTable(Foo.class, true); 17 | Dao fooDao = DaoFactory.createDao(connectionSource, Foo.class); 18 | Foo foo = new Foo(); 19 | assertEquals(1, fooDao.create(foo)); 20 | Foo result = fooDao.queryForId(foo.id); 21 | assertNotNull(result); 22 | assertEquals(foo.id, result.id); 23 | } 24 | 25 | @Test 26 | public void testCreateDaoConnectionSourceDatabaseTableConfigOfT() throws Exception { 27 | createTable(Foo.class, true); 28 | Dao fooDao = 29 | DaoFactory.createDao(connectionSource, DatabaseTableConfig.fromClass(databaseType, Foo.class)); 30 | Foo foo = new Foo(); 31 | assertEquals(1, fooDao.create(foo)); 32 | Foo result = fooDao.queryForId(foo.id); 33 | assertNotNull(result); 34 | assertEquals(foo.id, result.id); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/j256/ormlite/jdbc/spring/TableCreatorTest.java: -------------------------------------------------------------------------------- 1 | package com.j256.ormlite.jdbc.spring; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrowsExactly; 5 | import static org.junit.jupiter.api.Assertions.fail; 6 | 7 | import java.sql.SQLException; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import org.junit.jupiter.api.Test; 12 | 13 | import com.j256.ormlite.dao.Dao; 14 | import com.j256.ormlite.field.DatabaseField; 15 | import com.j256.ormlite.jdbc.BaseJdbcTest; 16 | import com.j256.ormlite.table.TableUtils; 17 | 18 | public class TableCreatorTest extends BaseJdbcTest { 19 | 20 | @Test 21 | public void testInitialize() throws Exception { 22 | Dao fooDao = createDao(Foo.class, false); 23 | try { 24 | fooDao.create(new Foo()); 25 | fail("Should have thrown an exception"); 26 | } catch (SQLException e) { 27 | // expected 28 | } 29 | 30 | TableCreator tableCreator = new TableCreator(); 31 | tableCreator.setConnectionSource(connectionSource); 32 | 33 | List> daoList = new ArrayList>(); 34 | daoList.add(fooDao); 35 | tableCreator.setConfiguredDaos(daoList); 36 | try { 37 | System.setProperty(TableCreator.AUTO_CREATE_TABLES, Boolean.TRUE.toString()); 38 | tableCreator.initialize(); 39 | } finally { 40 | System.clearProperty(TableCreator.AUTO_CREATE_TABLES); 41 | } 42 | 43 | assertEquals(1, fooDao.create(new Foo())); 44 | // shouldn't do anything 45 | tableCreator.destroy(); 46 | assertEquals(1, fooDao.create(new Foo())); 47 | 48 | try { 49 | System.setProperty(TableCreator.AUTO_DROP_TABLES, Boolean.TRUE.toString()); 50 | tableCreator.destroy(); 51 | fooDao.create(new Foo()); 52 | fail("Should have thrown an exception"); 53 | } catch (SQLException e) { 54 | // expected 55 | } finally { 56 | System.clearProperty(TableCreator.AUTO_DROP_TABLES); 57 | } 58 | } 59 | 60 | @Test 61 | public void testAutoCreateNotSet() throws Exception { 62 | TableCreator tableCreator = new TableCreator(); 63 | tableCreator.initialize(); 64 | } 65 | 66 | @Test 67 | public void testNoConfiguredDaos() { 68 | TableCreator tableCreator = new TableCreator(); 69 | tableCreator.setConnectionSource(connectionSource); 70 | 71 | try { 72 | System.setProperty(TableCreator.AUTO_CREATE_TABLES, Boolean.TRUE.toString()); 73 | assertThrowsExactly(SQLException.class, () -> { 74 | tableCreator.initialize(); 75 | }); 76 | } finally { 77 | System.clearProperty(TableCreator.AUTO_CREATE_TABLES); 78 | } 79 | } 80 | 81 | @Test 82 | public void testNonSpring() throws Exception { 83 | Dao fooDao = createDao(Foo.class, false); 84 | List> daoList = new ArrayList>(); 85 | daoList.add(fooDao); 86 | TableCreator tableCreator = new TableCreator(connectionSource, daoList); 87 | try { 88 | System.setProperty(TableCreator.AUTO_CREATE_TABLES, Boolean.TRUE.toString()); 89 | System.setProperty(TableCreator.AUTO_DROP_TABLES, Boolean.TRUE.toString()); 90 | tableCreator.maybeCreateTables(); 91 | tableCreator.maybeDropTables(); 92 | } finally { 93 | System.clearProperty(TableCreator.AUTO_CREATE_TABLES); 94 | System.clearProperty(TableCreator.AUTO_DROP_TABLES); 95 | } 96 | } 97 | 98 | @Test 99 | public void testCreateAlreadyExists() throws Exception { 100 | Dao fooDao = createDao(Foo.class, true); 101 | List> daoList = new ArrayList>(); 102 | daoList.add(fooDao); 103 | TableCreator tableCreator = new TableCreator(connectionSource, daoList); 104 | try { 105 | System.setProperty(TableCreator.AUTO_CREATE_TABLES, Boolean.TRUE.toString()); 106 | tableCreator.maybeCreateTables(); 107 | } finally { 108 | System.clearProperty(TableCreator.AUTO_CREATE_TABLES); 109 | } 110 | } 111 | 112 | @Test 113 | public void testDestroyDoesntExist() throws Exception { 114 | Dao fooDao = createDao(Foo.class, false); 115 | List> daoList = new ArrayList>(); 116 | daoList.add(fooDao); 117 | TableCreator tableCreator = new TableCreator(connectionSource, daoList); 118 | try { 119 | System.setProperty(TableCreator.AUTO_CREATE_TABLES, Boolean.TRUE.toString()); 120 | System.setProperty(TableCreator.AUTO_DROP_TABLES, Boolean.TRUE.toString()); 121 | tableCreator.maybeCreateTables(); 122 | TableUtils.dropTable(connectionSource, Foo.class, true); 123 | tableCreator.maybeDropTables(); 124 | } finally { 125 | System.clearProperty(TableCreator.AUTO_CREATE_TABLES); 126 | System.clearProperty(TableCreator.AUTO_DROP_TABLES); 127 | } 128 | } 129 | 130 | protected static class Foo { 131 | @DatabaseField(generatedId = true) 132 | int id; 133 | @DatabaseField 134 | String stuff; 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/test/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # 2 | # NOTE: we have to use this because spring requires it be available otherwise spring tests fail 3 | # 4 | 5 | log4j.rootLogger=INFO, stdout 6 | 7 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 8 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 9 | 10 | # Print the date in ISO 8601 format 11 | log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} [%p] %c{1} %m%n 12 | 13 | # Be more verbose with our code 14 | log4j.logger.com.j256.ormlite=DEBUG 15 | log4j.logger.com.j256.ormlite.stmt.mapped.BaseMappedStatement=TRACE 16 | log4j.logger.com.j256.ormlite.stmt.mapped.MappedCreate=TRACE 17 | log4j.logger.com.j256.ormlite.stmt.StatementExecutor=TRACE 18 | log4j.logger.com.j256.ormlite.jdbc.JdbcDatabaseConnection=TRACE 19 | -------------------------------------------------------------------------------- /src/test/resources/ormliteLocalLog.properties: -------------------------------------------------------------------------------- 1 | # 2 | # This file configures the log output of the simplelogging LocalLog class. 3 | # 4 | # Simplelogging also supports Log4j and other logging classes. See the documentation. 5 | # 6 | # Lines in this file are in the format: 7 | # 8 | # class-regex-pattern = Level 9 | # 10 | # You should escape any period characters with a single backslash unless they are part of a regex match: 11 | # 12 | # com\.j256\.simplelogging.* = DEBUG 13 | # 14 | com\.j256\.ormlite.* = DEBUG 15 | com\.j256\.ormlite\.LocalLogBackendTest = TRACE 16 | --------------------------------------------------------------------------------